mirror of https://github.com/python/cpython
bpo-46170: Improve the error message when subclassing NewType (GH-30268)
Co-authored-by: Alex Waygood <alex.waygood@gmail.com> Co-authored-by: Nikita Sobolev <mail@sobolevn.me> Co-authored-by: Ken Jin <28750310+Fidget-Spinner@users.noreply.github.com>
This commit is contained in:
parent
50731297a9
commit
f391f9bf28
|
@ -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
|
||||
|
|
|
@ -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__}'
|
||||
|
||||
|
|
|
@ -0,0 +1 @@
|
|||
Improve the error message when you try to subclass an instance of :class:`typing.NewType`.
|
Loading…
Reference in New Issue