India PyCon 2009
Quick wallpaper changer
Load testing with Grinder
Adding namespace to XML
Opera RSS to OPML
« Exuberant ctags and Vim
» Joy of python: dir, help and pprint
Python makes pretty good use of dictionaries in its implementation of classes. Some times, it is much more pleasant to express things in object.attribute form rather than like dictionary['key']. Here is a simple and useless python script that might give you some idea about converting classes to dictionaries and making classes out of dictionaries.
"""Attribute-style access is so lovely I often start off classes as a descendant of object with no definition (``pass``), just to give me something I can use attribute-style access with rather than dict-style access.
BTW: In dict2class, I'd eliminate the loop with either of the following:
# single-call update
c.__dict__.update(d)
# or, assign to __dict__
c.__dict__ = d.copy()
(If you don't copy, you'll end up with shared state, which is sometimes useful -- check out the Singleton pattern in the ASPN cookbook.)
In class2dict I'd precompute: privatePrefix = '_' + o.__class__.__name__
and then use elem.startswith(privatePrefix) as the comparison. Or, you could use list comprehensions to reduce the entire function to one line:
return dict([(k, v) for (k, v) in o.__dict__.items if not k.startswith('_'+o.__class__.__name__)])
To make long list comprehensions readable, I sometimes break the line before the 'for' (especially if the expression before it is big), the 'in' (especially if the expression producing the sequence is big), and the 'if' (especially if the test expression is big). In this case, I'd only do it before the 'if'.
Thanks Garth.
Personally, I try not to use list comprehensions as much - it reminds me too much of my Perl days :-)