Skip to content

Commit

Permalink
Support PEP 604 unions, types.UnionType (#83)
Browse files Browse the repository at this point in the history
  • Loading branch information
antonagestam committed Jun 2, 2022
1 parent 8f6aa20 commit c6adf81
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 1 deletion.
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

0 comments on commit c6adf81

Please sign in to comment.