On Tue, Mar 15, 2022 at 10:04:45AM +1100, Chris Angelico wrote: > Since a namedtuple *is* supposed to > be both a sequence and a record, the names are part of the record > interface, and the sequence is still part of that. Also, the field > names don't have to be valid identifiers (although they usually will).
>>> from collections import namedtuple >>> T = namedtuple('T', 'a b + c') Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/local/lib/python3.10/collections/__init__.py", line 373, in namedtuple raise ValueError('Type names and field names must be valid ' ValueError: Type names and field names must be valid identifiers: '+' > But if it's a sequence of arbitrary length, then why is it a tuple at > all? def func(p, q, *sequence_of_arbitrary_length): ... I guess that the interpreter is Doing It All Wrong and making an XY Problem mistake. Right? > You assume that it has to be a tuple but not a namedtuple, but a > namedtuple IS a tuple. To be precise, namedtuples are a subclass of tuple. For many purposes, we can treat namedtuples and tuples the same way. But namedtuples **extend the tuple API**. In terms of the Liskov Substitution Principle, we can say that any place you use a tuple, you can replace it with a namedtuple, but not the other way around. However, in *practical* terms, the LSP is not the full truth. The problem here is easily seen by considering the *args tuple from function definitions again. If we choose to replace the plain tuple with a namedtuple, what meaningful names would you use for the fields? Aside from the practical problem that namedtuple() doesn't support arbitrary length records, there is no meaningful names for the fields. The best we can do is some mapping of index to ordinals: zeroeth, first, second, third, fourth, fifth, ... but that's hardly meaningful in the sense intended. So namedtuple is a red herring here and the LSP is not the whole truth. Despite what Liskov says, plain vanilla tuples can be considered a superset of named tuples, not a subset: - tuples support records of arbitrary length; - tuples support anonymous fields. The bottom line here is this: There is nothing wrong with using plain tuples as your data structure, and the instance from certain people that wfdc is wrong to do so is arrogant, rude and condescending. -- Steve _______________________________________________ Python-ideas mailing list -- python-ideas@python.org To unsubscribe send an email to python-ideas-le...@python.org https://mail.python.org/mailman3/lists/python-ideas.python.org/ Message archived at https://mail.python.org/archives/list/python-ideas@python.org/message/QSB6674WWCZ44UI4O7ULW4C43PZL42BG/ Code of Conduct: http://python.org/psf/codeofconduct/