From c6adf8150c8a0242c15d86066372673489eb6c77 Mon Sep 17 00:00:00 2001 From: Anton Agestam Date: Thu, 2 Jun 2022 13:24:33 +0200 Subject: [PATCH] Support PEP 604 unions, types.UnionType (#83) --- test_typing_inspect.py | 11 +++++++++++ typing_inspect.py | 9 ++++++++- 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/test_typing_inspect.py b/test_typing_inspect.py index 670f813..954a113 100644 --- a/test_typing_inspect.py +++ b/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, @@ -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 diff --git a/typing_inspect.py b/typing_inspect.py index d27f6c7..531def0 100644 --- a/typing_inspect.py +++ b/typing_inspect.py @@ -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:: @@ -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