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

Closes #500 Python3.11 and | syntax works for model creation #501

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion odmantic/model.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import decimal
import enum
import pathlib
import types
import uuid
from abc import ABCMeta
from collections.abc import Callable as abcCallable
Expand Down Expand Up @@ -193,7 +194,7 @@ def validate_type(type_: Type) -> Type:
# FIXME: remove this hack when a better solution to handle dynamic
# generics is found
# https://github.com/pydantic/pydantic/issues/8354
if type_origin is Union:
if type_origin is Union or type_origin is getattr(types, "UnionType", Union):
# as new_arg_types is a tuple, we can directly create a matching Union
# instance, instead of hacking our way around it:
# https://stackoverflow.com/a/72884529/3784643
Expand Down
12 changes: 12 additions & 0 deletions tests/unit/test_model_definition.py
Original file line number Diff line number Diff line change
Expand Up @@ -528,3 +528,15 @@ class Person(Model):
"hashed_password": "hashed_password",
}
Person(**user)


@pytest.mark.skipif(
sys.version_info[:3] < (3, 10, 0),
reason="Union syntax not supported by python < 3.10",
)
def test_model_with_p310_union_syntax():
class M(Model):
f: int | str # type: ignore[syntax]

assert M(f=1).f == 1
assert M(f="hello").f == "hello"