Skip to content
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

Allow None when using a Union containing Any or object #3452

Merged
merged 6 commits into from
Dec 10, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
1 change: 1 addition & 0 deletions changes/3444-tharradine.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Fix issue where `None` was considered invalid when using a `Union` type containing `Any` or `object`
4 changes: 2 additions & 2 deletions pydantic/fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,6 @@
Callable,
ForwardRef,
NoArgAnyCallable,
NoneType,
display_as_type,
get_args,
get_origin,
Expand Down Expand Up @@ -563,10 +562,11 @@ def _type_analysis(self) -> None: # noqa: C901 (ignore complexity)
if is_union(origin):
types_ = []
for type_ in get_args(self.type_):
if type_ is NoneType:
if is_none_type(type_) or type_ is Any or type_ is object:
if self.required is Undefined:
self.required = False
self.allow_none = True
if is_none_type(type_):
continue
types_.append(type_)

Expand Down
17 changes: 17 additions & 0 deletions tests/test_edge_cases.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,23 @@ class Model(BaseModel):
]


def test_union_int_any():
class Model(BaseModel):
v: Union[int, Any]

m = Model(v=123)
assert m.v == 123

m = Model(v='123')
assert m.v == 123

m = Model(v='foobar')
assert m.v == 'foobar'

m = Model(v=None)
assert m.v is None


def test_union_priority():
class ModelOne(BaseModel):
v: Union[int, str] = ...
Expand Down