Dennis Sweeney <sweeney.dennis...@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 <rep...@bugs.python.org> <https://bugs.python.org/issue46450> _______________________________________ _______________________________________________ Python-bugs-list mailing list Unsubscribe: https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com