diff --git a/Doc/library/typing.rst b/Doc/library/typing.rst index 0fee782121b0af..3c65d9d62ce3c4 100644 --- a/Doc/library/typing.rst +++ b/Doc/library/typing.rst @@ -2376,6 +2376,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 f002d28df60e9c..acbdaf6db0dc58 100644 --- a/Lib/test/test_typing.py +++ b/Lib/test/test_typing.py @@ -8359,6 +8359,23 @@ class VeryAnnoying(metaclass=Meta): pass 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 66570db7a5bd74..68b8be44d1f55b 100644 --- a/Lib/typing.py +++ b/Lib/typing.py @@ -2961,6 +2961,9 @@ def annotate(format): 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 00000000000000..dec162bb624a15 --- /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`.