Uh oh!
There was an error while loading.Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork32.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:
fromtypingimportNamedTupleclassFoo(NamedTuple):defbar(self):print(__class__)
Expected behaviour:
ClassFoo
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 thetyping
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 callstype.__new__(...)
) inside ofNamedTupleMeta.__new__
the__classcell__
object isn't passed along.
Which leads to a runtime error as described inthe 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__"inns:ns["__classcell__"].cell_contents=nm_tpl### already existing code:ifGenericinbases:nm_tpl.__init_subclass__()returnnm_tpl
Version:
Output ofpython -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