Returning a tuple-struct

Giovanni Bajo noway at sorry.com
Thu Jan 19 05:47:35 EST 2006


groups.20.thebriguy at spamgourmet.com wrote:

>>>> time.localtime()
> (2006, 1, 18, 21, 15, 11, 2, 18, 0)
>>>> time.localtime()[3]
> 21
>>>> time.localtime().tm_hour
> 21
>
> Anyway, I guess there's a few of ways to do this.  In the case above,
> it would seem reasonable to override __getitem__() and other things to
> get that result.


I have a generic solution for this (never submitted to the cookbook... should
I?)


import operator
def NamedTuple(*args, **kwargs):
    class named_tuple_class(tuple):
        pass

    values = []
    idx = 0
    for arg in args:
        for name in arg[:-1]:
            setattr(named_tuple_class, name,
property(operator.itemgetter(idx)))
        values.append(arg[-1])
        idx += 1
    for name,val in kwargs.iteritems():
        setattr(named_tuple_class, name, property(operator.itemgetter(idx)))
        values.append(val)
        idx += 1

    return named_tuple_class(values)




>>> t = NamedTuple(("x", 12), ("y", 18))
>>> t
(12, 18)
>>> t[0]
12
>>> t.x
12
>>> t[1]
18
>>> t.y
18
>>> t.z
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
AttributeError: 'named_tuple_class' object has no attribute 'z'


>>> t = NamedTuple(("p", "pos", "position", 12.4))
>>> t
(12.4,)
>>> t.p
12.4
>>> t.pos
12.4
>>> t.position
12.4



>>> t = NamedTuple(("p", "pos", 12.4), length="foo")
>>> t
(12.4, 'foo')
>>> t.p
12.4
>>> t.pos
12.4
>>> t.length
'foo'
-- 
Giovanni Bajo





More information about the Python-list mailing list