Structures

George Sakkis george.sakkis at gmail.com
Mon Nov 3 19:33:55 EST 2008


On Nov 3, 6:32 pm, "Paulo J. Matos" <pocma... at gmail.com> wrote:

> Even though I can use dicts where the keys are strings (as if it were
> the name of the field), it seems to heavy, since a structure doesn't
> need to be resizable (and dicts are) and it has constant time access
> (which depending on the implementation I would guess dicts don't
> have).
>
> Can someone please clarify?

For all practical purposes, dicts have almost constant access time (at
least with any half-decent __hash__  method). If you're paranoid about
micro-optimizations, you can define a class with __slots__:

>>> class MyStruct(object):
...     __slots__ = ('x', 'y')
...
>>> s = MyStruct()
>>> s.x = 3
>>> s.y = 4
>>> s.z= 5
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'MyStruct' object has no attribute 'z'

More often than not, that's premature optimization.

George



More information about the Python-list mailing list