[issue46450] namedtuple leaks data between instances when field's default value is empty list

Dennis Sweeney report at bugs.python.org
Thu Jan 20 23:46:58 EST 2022


Dennis Sweeney <sweeney.dennis650 at gmail.com> added the comment:

This seems to be the standard confusion people have with mutable defaults, just with namedtuple defaults rather than function defaults.

Similar behavior elsewhere in Python:

>>> def f(x, y=[]):
...     y.append(x)
...     print(y)
... 
...     
>>> f(1)
[1]
>>> f(2)
[1, 2]
>>> f(15)
[1, 2, 15]

Or even

>>> a = []
>>> b = a
>>> b.append(4)
>>> a
[4]

This happens because the values you provide as defaults are *objects*, not *expressions* to be re-evaluated. If you make one of the defaults a list, you ask the namedtuple to "give me this particular list every time", and it will give you that same list, even if it has been modified.

There is currently no support for "construct a brand new list every time" in namedtuples. You could look to the dataclasses module for such a feature, where you can specify default_factory=list, and it will make a new list for each instance.

https://docs.python.org/3/library/dataclasses.html#dataclasses.field

----------
nosy: +Dennis Sweeney

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue46450>
_______________________________________


More information about the Python-bugs-list mailing list