structs in python
Fernando Pérez
fperez528 at yahoo.com
Mon Jul 8 14:51:47 EDT 2002
Christophe Delord wrote:
>
> The dict can be the __dict__ attribute of a particular class :
>
>
> class Record:
>
> def __init__(self, **kw):
> self.__dict__.update(kw);
>
> p = Record(x=10, y=11, color='blue')
>
> print p.x
such a class can then be conveniently updated later with the following:
def with(object, **args):
"""Set multiple attributes for an object, similar to Pascal's with.
Example:
with(jim,
born = 1960,
haircolour = 'Brown',
eyecolour = 'Green')
Credit: Greg Ewing, in
http://mail.python.org/pipermail/python-list/2001-May/040703.html"""
object.__dict__.update(args)
If you want a full-blown class which implements struct-like functionality
with both dictionary-type (s['blah']) and struct-type (s.blah) access for its
data members, you can use my Struct.py from:
http://windom.colorado.edu/~fperez/python/misc/Struct.py
An html syntax-highligted version is at:
http://windom.colorado.edu/~fperez/python/misc/Struct.py.html
Having both kinds of access allows explicit named acess:
s['blah'] == s.blah
but also access by variable:
x='blah'
s[x] == s['blah']
Obviously, any '.' access is explicit by name always.
Besides allowing both types of access (dict and struct), it has all the
behavior of a dict (keys, values, items, update, get, setdefault, etc) plus a
fancy 'merge' method which is a flexible version of update. It allows you to
update a Struct with fine control over what to do when collisions are found
(update simply overwrites old data, not always what you want). This makes it
very useful for keeping configuration information which needs to be updated
in various forms, for example.
I've successfully used this class in several projects, and it's extremely
convenient. Note however that it was coded for convenience, not speed. If you
use it and find any bugs in it, please let me know.
Note that it requires the following function from a module I have around
called genutils. You can simply paste the following in Struct.py and remove
the import line:
def list2dict2(lst,default=''):
"""Takes a list and turns it into a dict.
Much slower than list2dict, but more versatile. This version can take
lists with sublists of arbitrary length (including sclars)."""
dic = {}
for elem in lst:
if type(elem) in (types.ListType,types.TupleType):
size = len(elem)
if size == 0:
pass
elif size == 1:
dic[elem] = default
else:
k,v = elem[0], elem[1:]
if len(v) == 1: v = v[0]
dic[k] = v
else:
dic[elem] = default
return dic
More information about the Python-list
mailing list