Skip to content

Commit ab6131d

Browse files
committed
Raise a clear error message when __classcell__ is seen in typing.NamedTuple subclasses
1 parent f9a7d41 commit ab6131d

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
@@ -2359,6 +2359,10 @@ types.
23592359
# A functional syntax is also supported
23602360
Employee = NamedTuple('Employee', [('name', str), ('id', int)])
23612361

2362+
.. note::
2363+
Using :func:`super` (and the ``__class__`` :term:`closure variable`) in methods of ``NamedTuple`` subclasses
2364+
is unsupported and causes a :class:`RuntimeError`.
2365+
23622366
.. versionchanged:: 3.6
23632367
Added support for :pep:`526` variable annotation syntax.
23642368

Lib/test/test_typing.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8359,6 +8359,23 @@ class VeryAnnoying(metaclass=Meta): pass
83598359
class Foo(NamedTuple):
83608360
attr = very_annoying
83618361

8362+
def test_super_explicitly_disallowed(self):
8363+
expected_message = (
8364+
"uses of super() and __class__ are unsupported "
8365+
"in methods of NamedTuple subclasses"
8366+
)
8367+
8368+
with self.assertRaises(RuntimeError, msg=expected_message):
8369+
class ThisWontWork(NamedTuple):
8370+
def __repr__(self):
8371+
return super().__repr__()
8372+
8373+
with self.assertRaises(RuntimeError, msg=expected_message):
8374+
class ThisWontWorkEither(NamedTuple):
8375+
@property
8376+
def name(self):
8377+
return __class__.__name__
8378+
83628379

83638380
class TypedDictTests(BaseTestCase):
83648381
def test_basics_functional_syntax(self):

Lib/typing.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2961,6 +2961,9 @@ def annotate(format):
29612961
class NamedTupleMeta(type):
29622962
def __new__(cls, typename, bases, ns):
29632963
assert _NamedTuple in bases
2964+
if "__classcell__" in ns:
2965+
raise RuntimeError(
2966+
"uses of super() and __class__ are unsupported in methods of NamedTuple subclasses")
29642967
for base in bases:
29652968
if base is not _NamedTuple and base is not Generic:
29662969
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 prevented at runtime.

0 commit comments

Comments
 (0)