New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Mapping types are coerced to dict #2323
Comments
Hi @ofek pydantic allows you to use arbitrary classes for validation with the setting from __future__ import annotations
from immutables import Map
from pydantic import BaseModel
class Model(BaseModel):
class Config:
arbitrary_types_allowed = True
test: Map
print(type(Model(test=Map(key=42)).test))
# > <class 'immutables._map.Map'> I hope this help ! |
Hi @ofek @samuelcolvin We already support quite well |
I opened a PR based on the linked comment: #2325 |
@PrettyWood Yours looks more robust, should I close mine? |
You can keep yours open! Happy to share the work 👍 In my code, I added an extra In my opinion we should probably try to support most common mapping types (stdlib ones) like it is done for try:
return type(v)(**result), None
except TypeError:
# add a warning ?
return result, None It would mean that all of this would work from collections import ChainMap, OrderedDict, defaultdict
class M(BaseModel):
x: Mapping[str, int]
assert repr(M(x=OrderedDict({1: '3'}))) == "M(x=OrderedDict([('1', 3)]))"
default_d = defaultdict(int)
default_d[1] = '3'
default_d['2']
assert repr(M(x=default_d)) == "M(x=defaultdict(<class 'int'>, {'1': 3, '2': 0}))"
map1 = {1: '3', '2': '4'}
map2 = {'3': 2, 4: '5'}
assert repr(M(x=ChainMap(map1, map2))) == "M(x=ChainMap({'1': 3, 2: '4'}, {3: '2', 4: '5'})" @ofek WDYT? |
@PrettyWood That sounds good! If you don't mind though, can you please continue with your approach and open a PR? I trust your knowledge of this codebase much more than mine 🙂 |
@PrettyWood Okay I updated my PR! |
@ofek Thanks! I had a quick look on my side too and updated my code https://github.com/PrettyWood/pydantic/pull/70/files |
For anyone else stumbling across this issue in search of how to use ChainMap in Pydantic, I implemented it as a custom type which subclasses the stdlib ChainMap https://gist.github.com/laundmo/909707aa63f8842737af6e7de8f81d0d I tested that it can:
It's treated just like an array of objects in JSON |
Bug
Output of
python -c "import pydantic.utils; print(pydantic.utils.version_info())"
:I'm trying to use https://github.com/MagicStack/immutables
produces
Is there a way to keep the type of encountered Mappings, or create a type representing
immutables.Map
?I've been at this for hours reading docs/closed issues, trying various approaches, and now I'm simply at a loss here.
The text was updated successfully, but these errors were encountered: