8000 gh-85795: Raise a clear error when `super()` is used in `typing.Named… · python/cpython@293fa34 · GitHub
[go: up one dir, main page]

Skip to content

Commit 293fa34

Browse files
authored
gh-85795: Raise a clear error when super() is used in typing.NamedTuple subclasses (#130082)
1 parent 5e73ece commit 293fa34

File tree

4 files changed

+27
-0
lines changed

4 files changed

+27
-0
lines changed

Doc/library/typing.rst

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2398,6 +2398,10 @@ types.
23982398
.. versionchanged:: 3.11
23992399
Added support for generic namedtuples.
24002400

2401+
.. versionchanged:: next
2402+
Using :func:`super` (and the ``__class__`` :term:`closure variable`) in methods of ``NamedTuple`` subclasses
2403+
is unsupported and causes a :class:`TypeError`.
2404+
24012405
.. deprecated-removed:: 3.13 3.15
24022406
The undocumented keyword argument syntax for creating NamedTuple classes
24032407
(``NT = NamedTuple("NT", x=int)``) is deprecated, and will be disallowed

Lib/test/test_typing.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8349,6 +8349,23 @@ class VeryAnnoying(metaclass=Meta): pass
83498349
class Foo(NamedTuple):
83508350
attr = very_annoying
83518351

8352+
def test_super_explicitly_disallowed(self):
8353+
expected_message = (
8354+
"uses of super() and __class__ are unsupported "
8355+
"in methods of NamedTuple subclasses"
8356+
)
8357+
8358+
with self.assertRaises(TypeError, msg=expected_message):
8359+
class ThisWontWork(NamedTuple):
8360+
def __repr__(self):
8361+
return super().__repr__()
8362+
8363+
with self.assertRaises(TypeError, msg=expected_message):
8364+
class ThisWontWorkEither(NamedTuple):
8365+
@property
8366+
def name(self):
8367+
return __class__.__name__
8368+
83528369

83538370
class TypedDictTests(BaseTestCase):
83548371
def test_basics_functional_syntax(self):

Lib/typing.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2889,6 +2889,9 @@ def annotate(format):
28892889
class NamedTupleMeta(type):
28902890
def __new__(cls, typename, bases, ns):
28912891
assert _NamedTuple in bases
2892+
if "__classcell__" in ns:
2893+
raise TypeError(
2894+
"uses of super() and __class__ are unsupported in methods of NamedTuple subclasses")
28922895
for base in bases:
28932896
if base is not _NamedTuple and base is not Generic:
28942897
raise TypeError(
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
Using :func:`super` and ``__class__`` :term:`closure variable` in
2+
user-defined methods of :class:`typing.NamedTuple` subclasses is now
3+
explicitly prohibited at runtime. Contributed by Bartosz Sławecki in :gh:`130082`.

0 commit comments

Comments
 (0)
0