Factory for Struct-like classes

Dan Lenski dlenski at gmail.com
Mon Aug 18 17:28:53 CEST 2008


On Aug 13, 1:30 pm, Christian Heimes <li... at cheimes.de> wrote:
> Trynamedtuplehttp://code.activestate.com/recipes/500261/
>
> Anamedtupleimplementation is part of Python 2.6 and 3.0. For older
> versions of Python use the recipe from activestate.
>
> Christian

This named tuple recipe is pretty cool...  I think there may be a
slight bug in the Python docs, though.  The ActiveState page explains
that it avoids the overhead of a per-instance __dict__ by using the
__slots__ variable.  However, according to the most-recent Python
docs, __slots__ does *NOT* work with subclasses of list, str, or
tuple.

From http://docs.python.org/ref/slots.html#l2h-222:

# __slots__ do not work for classes derived from ``variable-length''
built-in types such as long, str and tuple.

On the other hand, nametuple does appear to work as advertised.

>>> Person=namedtuple.namedtuple('Person', ('name', 'age', 'height'))
>>> p=Person('Bob', 24, 1.86)
>>> p.name
'Bob'
>>> p.shoe_size
AttributeError: 'Person' object has no attribute 'shoe_size'
>>> p.__dict__
AttributeError: 'Person' object has no attribute '__dict__'

So is there a bug in the Python docs?  Does __slots__ in fact work
with subclasses of tuple?

Dan



More information about the Python-list mailing list