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鈥檒l occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support PEP 604 unions, types.UnionType #83

Merged
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
11 changes: 11 additions & 0 deletions test_typing_inspect.py
@@ -1,4 +1,7 @@
import sys

import pytest

from typing_inspect import (
is_generic_type, is_callable_type, is_new_type, is_tuple_type, is_union_type,
is_optional_type, is_final_type, is_literal_type, is_typevar, is_classvar,
Expand Down Expand Up @@ -173,6 +176,14 @@ def test_union(self):
nonsamples = [int, Union[int, int], [], Iterable[Any]]
self.sample_test(is_union_type, samples, nonsamples)

@pytest.mark.skipif(sys.version_info < (3, 10), reason="requires 3.10 or higher")
def test_union_pep604(self):
T = TypeVar('T')
S = TypeVar('S')
samples = [T | int, int | (T | S), int | str]
nonsamples = [int, int | int, [], Iterable[Any]]
self.sample_test(is_union_type, samples, nonsamples)

def test_optional_type(self):
T = TypeVar('T')
samples = [type(None), # none type
Expand Down
9 changes: 8 additions & 1 deletion typing_inspect.py
Expand Up @@ -205,6 +205,12 @@ def is_final_type(tp):
return WITH_FINAL and type(tp) is _Final


try:
MaybeUnionType = types.UnionType
except AttributeError:
MaybeUnionType = None


def is_union_type(tp):
"""Test if the type is a union type. Examples::

Expand All @@ -215,7 +221,8 @@ def is_union_type(tp):
"""
if NEW_TYPING:
return (tp is Union or
isinstance(tp, typingGenericAlias) and tp.__origin__ is Union)
(isinstance(tp, typingGenericAlias) and tp.__origin__ is Union) or
(MaybeUnionType and isinstance(tp, MaybeUnionType)))
return type(tp) is _Union


Expand Down