Skip to content

Commit 43fac1e

Browse files
committed
fix detection of typing.NewType on Python 3.10
1 parent ef7698f commit 43fac1e

1 file changed

Lines changed: 10 additions & 3 deletions

File tree

unpythonic/typecheck.py

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
"""
1616

1717
import collections
18+
import sys
1819
import typing
1920

2021
try:
@@ -93,7 +94,7 @@ def isoftype(value, T):
9394
# there's not much we can do.
9495

9596
# TODO: Right now we're accessing internal fields to get what we need.
96-
# TODO: Would be nice to update this if Python, at some point, adds an
97+
# TODO: Would be nice to rewrite this if Python, at some point, adds an
9798
# TODO: official API to access the static type information at run time.
9899

99100
if T is typing.Any:
@@ -185,8 +186,14 @@ def get_origin(tp):
185186
if T is typing.Union: # isinstance(T, typing._SpecialForm) and T._name == "Union":
186187
return False # pragma: no cover, Python 3.7+ only.
187188

188-
# TODO: in Python 3.7+, what is the mysterious callable that doesn't have `__qualname__`?
189-
if callable(T) and hasattr(T, "__qualname__") and T.__qualname__ == "NewType.<locals>.new_type":
189+
def isNewType(T):
190+
# In Python 3.10, an instance of `typing.NewType` is now actually such and not just a function. Nice!
191+
if sys.version_info >= (3, 10, 0):
192+
return isinstance(T, typing.NewType)
193+
# Python 3.6 through Python 3.9
194+
# TODO: in Python 3.7+, what is the mysterious callable that doesn't have a `__qualname__`?
195+
return callable(T) and hasattr(T, "__qualname__") and T.__qualname__ == "NewType.<locals>.new_type"
196+
if isNewType(T):
190197
# This is the best we can do, because the static types created by `typing.NewType`
191198
# have a constructor that discards the type information at runtime:
192199
# UserId = typing.NewType("UserId", int)

0 commit comments

Comments
 (0)