Friday, September 30, 2011

namedtupledict

With three kinds of member access, it is easier to use than ever.


>>> def namedtupledict(*a, **kw):
...    namedtuple = collections.namedtuple(*a, **kw)
...    def getitem(self, key):
...       if type(key) == str:
...           return getattr(self, key)
...       return tuple.__getitem__(self, key)
...    namedtuple.__getitem__ = getitem
...    return namedtuple
...
>>> t = namedtupledict('t', 'a b c')
>>> t1 = t(1,2,3)
>>> t1.a
1
>>> t1[0]
1
>>> t1['a']
1

No comments:

Post a Comment