summaryrefslogtreecommitdiffstats
path: root/Lib
diff options
context:
space:
mode:
Diffstat (limited to 'Lib')
-rw-r--r--Lib/test/test_typing.py11
-rw-r--r--Lib/typing.py15
2 files changed, 26 insertions, 0 deletions
diff --git a/Lib/test/test_typing.py b/Lib/test/test_typing.py
index 17d78cf..c76aa0a 100644
--- a/Lib/test/test_typing.py
+++ b/Lib/test/test_typing.py
@@ -4423,6 +4423,17 @@ class NewTypeTests:
)
exec(code, {})
+ def test_error_message_when_subclassing(self):
+ with self.assertRaisesRegex(
+ TypeError,
+ re.escape(
+ "Cannot subclass an instance of NewType. Perhaps you were looking for: "
+ "`ProUserId = NewType('ProUserId', UserId)`"
+ )
+ ):
+ class ProUserId(UserId):
+ ...
+
class NewTypePythonTests(NewTypeTests, BaseTestCase):
module = py_typing
diff --git a/Lib/typing.py b/Lib/typing.py
index 360129e..721afb7 100644
--- a/Lib/typing.py
+++ b/Lib/typing.py
@@ -2639,6 +2639,21 @@ class NewType:
if def_mod != 'typing':
self.__module__ = def_mod
+ def __mro_entries__(self, bases):
+ # We defined __mro_entries__ to get a better error message
+ # if a user attempts to subclass a NewType instance. bpo-46170
+ superclass_name = self.__name__
+
+ class Dummy:
+ def __init_subclass__(cls):
+ subclass_name = cls.__name__
+ raise TypeError(
+ f"Cannot subclass an instance of NewType. Perhaps you were looking for: "
+ f"`{subclass_name} = NewType({subclass_name!r}, {superclass_name})`"
+ )
+
+ return (Dummy,)
+
def __repr__(self):
return f'{self.__module__}.{self.__qualname__}'