3 ms·
> aside: please don't abuse collections.namedtuple to make a simple Python object; the class is meant to help porting APIs that return a tuple to a more object-
by luhn 10y ago
> aside: please don't abuse collections.namedtuple to make a simple Python object; the class is meant to help porting APIs that return a tuple to a more object-oriented one, so starting with namedtuple means you end up leaking a tuple API that you probably didn't want to begin with
I haven't heard this before. I subclass namedtuples regularly—whenever I need a simple immutable object. I haven't had any problems personally. (Except when pickling them. I would not recommend that.)
Can any experienced Pythonistas weigh in? Is this bad practice?
- TTPrograms 10y agoI don't really see how it's a problem that it's "leaking" a tuple API - it's not like there's private methods in Python. Everything can see everything. If anything having the state of an object available explicitly as a tuple seems like a good idea to me, as opposed to trying to figure out what's a stateful variable and what's a method etc.
- joshuamorton 10y agoYou'll get surprises such as your subclass being indexable when you (probably) don't want that.
- lgas 10y agoWhat problem would that cause? Wouldn't it only be a problem if you attempted to index into it, which you wouldn't do (on purpose) if you didn't think it was indexable? And if you did try to index into it thinking that it wasn't indexable, it would be a bug, which is the same as when it's indexable...
- joshuamorton 10y agoExactly. You probably don't want this thing that is essentially a namespace to be indexable, but you index into it, which is a bug, but it quacks like a tuple, so your mistake propagates silently, which is a bad thing. Its more permissive than one would expect. Although the bigger issue is what dragonne mentioned.
- deleted 10y ago[deleted]
- dragonne 10y agoThe biggest gotcha is that namedtuples compare exactly like regular tuples. Thus, two namedtuple types with identical elements will compare equal even if the type and field names differ. Usually that isn't what you want. I've taken to using attrs everywhere for exactly this reason: http://attrs.readthedocs.io/en/stable/why.html#namedtuples http://attrs.readthedocs.io/en/stable/why.html#namedtuples