Thanks to visit codestin.com
Credit goes to github.com

Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
Raise a clear error message when __classcell__ is seen in `typing.N…
…amedTuple` subclasses
  • Loading branch information
johnslavik committed Mar 4, 2025
commit ab6131d6a4ffbaa7f665d18119f1cf332777b8d3
4 changes: 4 additions & 0 deletions Doc/library/typing.rst
Original file line number Diff line number Diff line change
Expand Up @@ -2359,6 +2359,10 @@ types.
# A functional syntax is also supported
Employee = NamedTuple('Employee', [('name', str), ('id', int)])

.. note::
Using :func:`super` (and the ``__class__`` :term:`closure variable`) in methods of ``NamedTuple`` subclasses
is unsupported and causes a :class:`RuntimeError`.

.. versionchanged:: 3.6
Added support for :pep:`526` variable annotation syntax.

Expand Down
17 changes: 17 additions & 0 deletions Lib/test/test_typing.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(RuntimeError, msg=expected_message):
class ThisWontWork(NamedTuple):
def __repr__(self):
return super().__repr__()

with self.assertRaises(RuntimeError, msg=expected_message):
class ThisWontWorkEither(NamedTuple):
@property
def name(self):
return __class__.__name__


class TypedDictTests(BaseTestCase):
def test_basics_functional_syntax(self):
Expand Down
3 changes: 3 additions & 0 deletions Lib/typing.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 RuntimeError(
Comment thread
johnslavik marked this conversation as resolved.
Outdated
"uses of super() and __class__ are unsupported in methods of NamedTuple subclasses")
Comment thread
johnslavik marked this conversation as resolved.
for base in bases:
if base is not _NamedTuple and base is not Generic:
raise TypeError(
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
Using :func:`super` and ``__class__`` :term:`closure variable` in
user-defined methods of :class:`typing.NamedTuple` subclasses is now
explicitly prevented at runtime.