Skip to content

collections.namedtuple fails to reconstruct from _asdict() when typename and field_name are the same non-ASCII identifier #140914

@T90REAL

Description

@T90REAL

Bug report

Bug description:

namedtuple fails to reconstruct an instance from its own _asdict() output when the typename and the field_name are the same non-ASCII character (e.g., 'µ').

Calling nt(**nt_instance._asdict()) should always be valid, but in this case, it raises a TypeError:

from collections import namedtuple

# 'µ' (mu) is a valid Python identifier.
nt = namedtuple('µ', ['µ'])

print(f"Created class: {nt}")

instance = nt(0)
print(f"Created instance: {instance}")

as_dict = instance._asdict()
print(f"Got _asdict(): {as_dict}")

reconstructed = nt(**as_dict)
Created class: <class '__main__.µ'>
Created instance: µ(µ=0)
Got _asdict(): {'µ': 0}
Traceback (most recent call last):
  File "/data/src/test.py", line 14, in <module>
    reconstructed = nt(**as_dict)
                    ^^^^^^^^^^^^^
TypeError: µ.__new__() got an unexpected keyword argument 'µ'

CPython versions tested on:

3.12

Operating systems tested on:

Linux

Metadata

Metadata

Assignees

No one assigned

    Labels

    stdlibStandard Library Python modules in the Lib/ directorytype-bugAn unexpected behavior, bug, or error

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions