Skip to content

NamedTuple class body does not support super() or __class__ #136765

@GugelRobin

Description

@GugelRobin

Dear typing community,

I tried to find if this bug was already reported, but didn't find any mentions.
The following code crashes unexpectedly.

Reproduction steps:

from typing import NamedTuple

class Foo(NamedTuple):
    def bar(self):
         print(__class__)

Expected behaviour:

Class Foo gets created successuflly.

Current behaviour:

RuntimeError: __class__ not set defining 'Foo' as <class '__main__.Foo'>. Was __classcell__ propagated to type.__new__?

Since the bug lives inside of the typing module I submit this bug report here instead of the python github.

As far as I was able to dig into the code it happens because when _make_nmtuple is called (which eventually calls type.__new__(...)) inside of NamedTupleMeta.__new__ the __classcell__ object isn't passed along.
Which leads to a runtime error as described in the documentation

Suggested solution:

  • Add "__classcell__" to _special (else __classcell__ will be a attribute of the new NamedTuple).
  • Add the following code before if Generic in bases:
if "__classcell__" in ns:
    ns["__classcell__"].cell_contents = nm_tpl
### already existing code:
if Generic in bases:
    nm_tpl.__init_subclass__()
return nm_tpl

Version:

Output of python -VV: Python 3.13.3 (main, Apr 8 2025, 13:54:08) [Clang 16.0.0 (clang-1600.0.26.6)]

I suspect though that any version >=3.8 is affected.

I haven't yet ever contributed to open source, if appropriate I can open a PR for this fix though.

Best regards,
Robin

Metadata

Metadata

Assignees

No one assigned

    Labels

    pendingThe issue will be closed if no feedback is providedstdlibPython modules in the Lib dirtype-bugAn unexpected behavior, bug, or error

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions