[Python-ideas] namedtuple baseclass

Chris Angelico rosuav at gmail.com
Sun Jan 12 09:17:56 CET 2014


On Sun, Jan 12, 2014 at 6:53 PM, Andrew Barnert <abarnert at yahoo.com> wrote:
> So to satisfy this use case, you'd either need an actual namedtuple base class instead of an abc, or an abc that adds some API for getting the field names (or name-value pairs). Either of which seems reasonable--except for the odd quirk of having a public API in a class that's prefixed with an underscore. (If it's not prefixed with an underscore, it can conflict with a field name, which defeats the whole purpose of namedtuple.)
>

Is compatibility with the current namedtuple important, or can this be
done another way? For instance, the fields could be retrieved with
__getitem__ instead:

# Hacking it in with a subclass. Gives no benefit
# but is a proof of concept.
class Point(namedtuple('Point', ['x', 'y'])):
    def __getitem__(self, which):
        if which=="fields": return self._fields
        return super().__getitem__(which)

>>> a=Point(1,2)
>>> a.x
1
>>> a.y
2
>>> a.fields
Traceback (most recent call last):
  File "<pyshell#233>", line 1, in <module>
    a.fields
AttributeError: 'Point' object has no attribute 'fields'
>>> a["fields"]
('x', 'y')
>>> a[0]
1
>>> a[1]
2

Normally, __getitem__ will be used with integers (since this is
basically a sequence, not a mapping). Would it break things to use a
string in this way? It's guaranteed not to collide with either form of
access (as a tuple, or as fields).

ChrisA


More information about the Python-ideas mailing list