summaryrefslogtreecommitdiffstats
path: root/Lib/typing.py
diff options
context:
space:
mode:
authorYurii Karabas <1998uriyyo@gmail.com>2021-07-20 13:20:38 (GMT)
committerGitHub <noreply@github.com>2021-07-20 13:20:38 (GMT)
commit965dd76e9060e27e2253ba8c8d21a142b178720d (patch)
tree9dd54317abe0b0a0009de0b07a7ee5fd2b5e0f39 /Lib/typing.py
parent4c0deb25ac899fbe4da626ce3cb21f204cdd3aa9 (diff)
downloadcpython-965dd76e9060e27e2253ba8c8d21a142b178720d.zip
cpython-965dd76e9060e27e2253ba8c8d21a142b178720d.tar.gz
cpython-965dd76e9060e27e2253ba8c8d21a142b178720d.tar.bz2
bpo-44353: Refactor typing.NewType into callable class (GH-27250)
Diffstat (limited to 'Lib/typing.py')
-rw-r--r--Lib/typing.py27
1 files changed, 22 insertions, 5 deletions
diff --git a/Lib/typing.py b/Lib/typing.py
index 4a6efee..1aff0a1 100644
--- a/Lib/typing.py
+++ b/Lib/typing.py
@@ -1374,6 +1374,12 @@ def _no_init(self, *args, **kwargs):
if type(self)._is_protocol:
raise TypeError('Protocols cannot be instantiated')
+def _callee(depth=2, default=None):
+ try:
+ return sys._getframe(depth).f_globals['__name__']
+ except (AttributeError, ValueError): # For platforms without _getframe()
+ return default
+
def _allow_reckless_class_checks(depth=3):
"""Allow instance and class checks for special stdlib modules.
@@ -2350,7 +2356,7 @@ _TypedDict = type.__new__(_TypedDictMeta, 'TypedDict', (), {})
TypedDict.__mro_entries__ = lambda bases: (_TypedDict,)
-def NewType(name, tp):
+class NewType:
"""NewType creates simple unique types with almost zero
runtime overhead. NewType(name, tp) is considered a subtype of tp
by static type checkers. At runtime, NewType(name, tp) returns
@@ -2369,12 +2375,23 @@ def NewType(name, tp):
num = UserId(5) + 1 # type: int
"""
- def new_type(x):
+ def __init__(self, name, tp):
+ self.__name__ = name
+ self.__qualname__ = name
+ self.__module__ = _callee(default='typing')
+ self.__supertype__ = tp
+
+ def __repr__(self):
+ return f'{self.__module__}.{self.__qualname__}'
+
+ def __call__(self, x):
return x
- new_type.__name__ = name
- new_type.__supertype__ = tp
- return new_type
+ def __or__(self, other):
+ return Union[self, other]
+
+ def __ror__(self, other):
+ return Union[other, self]
# Python-version-specific alias (Python 2: unicode; Python 3: str)