Skip to content

Commit

Permalink
Merge pull request #21 from erezsh/annotated
Browse files Browse the repository at this point in the history
Added support for typing_extensions.Annotated
  • Loading branch information
erezsh authored Dec 29, 2022
2 parents e09d003 + c767797 commit 532bb2e
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 0 deletions.
3 changes: 3 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,9 @@ packages = [{ include = "runtype" }]
python = "^3.6"
dataclasses = {version = "*", python = "~3.6"}

[tool.poetry.dev-dependencies]
typing_extensions = "*"

[build-system]
requires = ["poetry-core>=1.0.0"]
build-backend = "poetry.core.masonry.api"
12 changes: 12 additions & 0 deletions runtype/pytypes.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,11 @@ def _forwardref_evaluate(self, g, l, _):
else:
_forwardref_evaluate = ForwardRef._evaluate

try:
import typing_extensions
except ImportError:
typing_extensions = None



py38 = sys.version_info >= (3, 8)
Expand Down Expand Up @@ -367,6 +372,13 @@ def _to_canon(self, t):
if hasattr(typing, '_AnnotatedAlias') and isinstance(t, typing._AnnotatedAlias):
return to_canon(t.__origin__)

if typing_extensions:
if hasattr(typing_extensions, '_AnnotatedAlias') and isinstance(t, typing_extensions._AnnotatedAlias):
return to_canon(t.__origin__)
elif hasattr(typing_extensions, 'AnnotatedMeta') and isinstance(t, typing_extensions.AnnotatedMeta):
# Python 3.6
return to_canon(t.__args__[0])

try:
t.__origin__
except AttributeError:
Expand Down
15 changes: 15 additions & 0 deletions tests/test_basic.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,11 @@
from runtype import Dispatch, DispatchError, dataclass, isa, is_subtype, issubclass, assert_isa, String, Int, validate_func
from runtype.dataclass import Configuration

try:
import typing_extensions
except ImportError:
typing_extensions = None


class TestIsa(TestCase):
def setUp(self):
Expand Down Expand Up @@ -133,6 +138,16 @@ def f(a: List[int] = None):
f()
self.assertRaises(TypeError, f, [1, None])

def test_typing_extensions(self):
if typing_extensions is None:
logging.info("Skipping tests for typing extensions")
return

a = typing_extensions.Annotated[int, range(1, 10)]
assert is_subtype(a, int)
assert is_subtype(int, a)
assert isa(1, a)



class TestDispatch(TestCase):
Expand Down

0 comments on commit 532bb2e

Please sign in to comment.