structs in python

Kevin O'Connor kevin at koconnor.net
Sat Jul 6 23:12:00 EDT 2002


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
>>>

- a mix between python tuples and C99 struct initializers.  This type of
declaration would provide a convenient way of naming the parts of small
stand-alone objects - the objects that typically use tuples today.

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.

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?

Thanks,
-Kevin

-- 
 ------------------------------------------------------------------------
 | Kevin O'Connor                     "BTW, IMHO we need a FAQ for      |
 | kevin at koconnor.net                  'IMHO', 'FAQ', 'BTW', etc. !"    |
 ------------------------------------------------------------------------





More information about the Python-list mailing list