-
-
Notifications
You must be signed in to change notification settings - Fork 32.4k
Description
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