From: Bartosz Sławecki Date: Thu, 6 Mar 2025 04:45:47 +0000 (+0100) Subject: gh-85795: Raise a clear error when `super()` is used in `typing.NamedTuple` subclasse... X-Git-Tag: v3.14.0a6~138 X-Git-Url: http://git.ipfire.org/gitweb.cgi?a=commitdiff_plain;h=293fa3433e40f5b0a7aa4d5b94f53c06b2187b25;p=thirdparty%2FPython%2Fcpython.git gh-85795: Raise a clear error when `super()` is used in `typing.NamedTuple` subclasses (#130082) --- diff --git a/Doc/library/typing.rst b/Doc/library/typing.rst index d4ab6eaea12d..aa613ee9f52f 100644 --- a/Doc/library/typing.rst +++ b/Doc/library/typing.rst @@ -2398,6 +2398,10 @@ types. .. versionchanged:: 3.11 Added support for generic namedtuples. + .. versionchanged:: next + Using :func:`super` (and the ``__class__`` :term:`closure variable`) in methods of ``NamedTuple`` subclasses + is unsupported and causes a :class:`TypeError`. + .. deprecated-removed:: 3.13 3.15 The undocumented keyword argument syntax for creating NamedTuple classes (``NT = NamedTuple("NT", x=int)``) is deprecated, and will be disallowed diff --git a/Lib/test/test_typing.py b/Lib/test/test_typing.py index e88c811bfcac..a7901dfa6a4e 100644 --- a/Lib/test/test_typing.py +++ b/Lib/test/test_typing.py @@ -8349,6 +8349,23 @@ class NamedTupleTests(BaseTestCase): class Foo(NamedTuple): attr = very_annoying + def test_super_explicitly_disallowed(self): + expected_message = ( + "uses of super() and __class__ are unsupported " + "in methods of NamedTuple subclasses" + ) + + with self.assertRaises(TypeError, msg=expected_message): + class ThisWontWork(NamedTuple): + def __repr__(self): + return super().__repr__() + + with self.assertRaises(TypeError, msg=expected_message): + class ThisWontWorkEither(NamedTuple): + @property + def name(self): + return __class__.__name__ + class TypedDictTests(BaseTestCase): def test_basics_functional_syntax(self): diff --git a/Lib/typing.py b/Lib/typing.py index 4b3c63b25aee..1dd115473fb9 100644 --- a/Lib/typing.py +++ b/Lib/typing.py @@ -2889,6 +2889,9 @@ _special = frozenset({'__module__', '__name__', '__annotations__', '__annotate__ class NamedTupleMeta(type): def __new__(cls, typename, bases, ns): assert _NamedTuple in bases + if "__classcell__" in ns: + raise TypeError( + "uses of super() and __class__ are unsupported in methods of NamedTuple subclasses") for base in bases: if base is not _NamedTuple and base is not Generic: raise TypeError( diff --git a/Misc/NEWS.d/next/Library/2025-02-13-15-10-56.gh-issue-85795.jeXXI9.rst b/Misc/NEWS.d/next/Library/2025-02-13-15-10-56.gh-issue-85795.jeXXI9.rst new file mode 100644 index 000000000000..dec162bb624a --- /dev/null +++ b/Misc/NEWS.d/next/Library/2025-02-13-15-10-56.gh-issue-85795.jeXXI9.rst @@ -0,0 +1,3 @@ +Using :func:`super` and ``__class__`` :term:`closure variable` in +user-defined methods of :class:`typing.NamedTuple` subclasses is now +explicitly prohibited at runtime. Contributed by Bartosz Sławecki in :gh:`130082`.