Skip to content

Commit

Permalink
Support new X | Y union syntax of Python 3.10 (PEP 604)
Browse files Browse the repository at this point in the history
  • Loading branch information
intgr committed Dec 10, 2021
1 parent effc8f2 commit fc8c6d6
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 2 deletions.
8 changes: 7 additions & 1 deletion src/drf_yasg/inspectors/field.py
Original file line number Diff line number Diff line change
Expand Up @@ -502,10 +502,16 @@ def inspect_collection_hint_class(hint_class):

hinting_type_info.append(((typing.Sequence, typing.AbstractSet), inspect_collection_hint_class))

# typing.UnionType was added in Python 3.10 for new PEP 604 pipe union syntax
try:
from types import UnionType
except ImportError:
UnionType = None


def _get_union_types(hint_class):
origin_type = get_origin_type(hint_class)
if origin_type is typing.Union:
if origin_type is typing.Union or (UnionType is not None and origin_type is UnionType):
return hint_class.__args__


Expand Down
15 changes: 14 additions & 1 deletion tests/test_get_basic_type_info_from_hint.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,19 @@
]


python310_union_tests = []
if sys.version_info >= (3, 10):
# # New PEP 604 union syntax in Python 3.10+
python310_union_tests = [
(bool | None, {'type': openapi.TYPE_BOOLEAN, 'format': None, 'x-nullable': True}),
(list[int] | None, {
'type': openapi.TYPE_ARRAY, 'items': openapi.Items(openapi.TYPE_INTEGER), 'x-nullable': True
}),
# Following cases are not 100% correct, but it should work somehow and not crash.
(int | float, None),
]


@pytest.mark.parametrize('hint_class, expected_swagger_type_info', [
(int, {'type': openapi.TYPE_INTEGER, 'format': None}),
(str, {'type': openapi.TYPE_STRING, 'format': None}),
Expand All @@ -41,7 +54,7 @@
(type('SomeType', (object,), {}), None),
(None, None),
(6, None),
] + python39_generics_tests)
] + python39_generics_tests + python310_union_tests)
def test_get_basic_type_info_from_hint(hint_class, expected_swagger_type_info):
type_info = get_basic_type_info_from_hint(hint_class)
assert type_info == expected_swagger_type_info

0 comments on commit fc8c6d6

Please sign in to comment.