Skip to content

Commit

Permalink
Allow None when using a Union containing Any or object (#3452)
Browse files Browse the repository at this point in the history
* Add unit test for Union[int, Any]

* Allow None when Any or object is in Union

Resolves #3444

* Add changelog entry for #3444

* Prefer `is_none_type()` over `type_ is NoneType`

* fix(lint): remove useless import

Co-authored-by: PrettyWood <em.jolibois@gmail.com>
  • Loading branch information
tharradine and PrettyWood committed Dec 10, 2021
1 parent 91ecfd6 commit 6ad80cd
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 2 deletions.
1 change: 1 addition & 0 deletions changes/3444-tharradine.md
@@ -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
Expand Up @@ -34,7 +34,6 @@
Callable,
ForwardRef,
NoArgAnyCallable,
NoneType,
display_as_type,
get_args,
get_origin,
Expand Down Expand Up @@ -574,10 +573,11 @@ def _type_analysis(self) -> None: # noqa: C901 (ignore complexity)
elif 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
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

0 comments on commit 6ad80cd

Please sign in to comment.