Friday, September 10, 2004

Named Tuples and attrdicts

Named Tuples and attrdicts:
Daily Python-URL has a flurry on "named tuples" today.

This lead me to submit the following comment

"attrdicts, Jon Schull, 2004/09/10
In a footnote to recipe 'Method for constructing a dictionary without excessive quoting' Ganesan Rajagopal introduced the the attrdict...upon which I have become quite dependent: here it is again (in its entirety)

class attrdict(dict):
def __getattr__(self, name):
return self[name]

def __setattr__(self, name, value):
self[name] = value

data = attrdict(red=1, green=2, blue=3)
print = 4

Doesn't this do everything the named tuples (do with additional power?)

I'm sure I'll find out why this is a horse of a different color (sorting and mutability come to mind), but I do want to advertise attrdicts more widely. I've found them very useful because they let me create and referernce to dictionaries in a very readable.manner (as well as in the traditional[fashion] ) and to use the inbuilt facilities of dictionaries (such keys() values() items() etc. ).