structs in python

Alex Martelli aleax at aleax.it
Sun Jul 7 07:45:45 EDT 2002


Kevin O'Connor wrote:

> Hello,
> 
> I often find myself using Python tuples in the same way I might use C
> structs.  For example, I might store a "point" as "p = (x, y, color)".
> 
> Unfortunately, this quickly becomes cumbersome when the code starts to
> make
> frequent references to tuple positions instead of member names.  For
> example, one would see code like "delta = (p1[0] - p2[0], p1[1] - p2[1])".
> Ideally, this code would read something more like "delta = (p1.x - p2.x,
> p1.y - p2.y)".
> 
> Clearly, the use of classes makes the code much more readable, but
> unfortunately the declarations necessary to instantiate a class is often
> too much of a hassle for small and infrequently used objects.
> 
> It would be useful if there were a simple way of declaring a class with
> only member variables (and no methods); an object more akin to a C struct.
> 
> What if a syntax like the following were permitted:
>>>> p = ( .x = 10, .y = 11, .color = 'blue')
>>>> print p.x
> 10
>>>>

I think you're looking for the recipe which I described in the Cookbook
as Bunch.

> I know this concept is not unique - I've seen implementations of a "class
> Struct" that implements the above using Python's **kw syntax (Eg. "p =
> Struct(x=10, y=11, color='blue')" ).  However, I have not seen wide spread
> adoption of it, and I have not seen an attempt to standardize an
> implementation.

What sort of implementation standardization might possibly be necessary,
or even helpful?

class Bunch:
    def __init__(self, **kw): self.__dict__ = kw

How can you possibly get simpler than this?

As for "widespread adoption", I guess the occurrence of classes with no
behavior, just state, isn't all that frequent when one does OOP.  It
does happen, and when it happens Bunch is fine -- as long as issues of
amount of memory consumed don't interfere.  __slots__ is OK, to save
memory, when you have many instances with just a few data fields each
(and the same field names in each instance), but it does admittedly
demand more sophisticated implementation than Bunch, presumably via a
metaclass.


> My intention here is not really to propose any changes, but instead to
> query the community's feelings on this topic.  Do other people find code
> that uses tuples a bit cryptic?  Would others like a named initializer? 
> Is this a recurring request with obvious problems?

I just don't see what the lack of classname and extra leading dots in your 
proposed :

>>>> p = ( .x = 10, .y = 11, .color = 'blue')

add to current usage such as p = Bunch(x=10, y=11, color='blue'), I guess.


Alex




More information about the Python-list mailing list