Returning a tuple-struct
groups.20.thebriguy at spamgourmet.com
groups.20.thebriguy at spamgourmet.com
Wed Jan 18 22:01:10 EST 2006
I've noticed that there's a few functions that return what appears to
be a tuple, but that also has attributes for each item in the tuple.
For example, time.localtime() returns a time.time_struct, which looks
like a tuple but also like a struct. That is, I can do:
>>> 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.
To my question... It seems like a useful but very simple way to
accomplish the above (that is, to have your return value accessible as
both a sequence and a struct) is to subclass tuple. Something like
this:
def foo():
class NewTuple(tuple): pass
x = NewTuple((1,2))
x.a, x.b = x
return x
And so I can do:
x = foo()
print x
print x.a
print x.b
And the result is:
(1, 2)
1
2
So, the question I have is just a style and/or pattern question...
Does anyone do this? Does is seem reasonably intuitive, or ugly? Is
there a better way? Thoughts?
-bri
More information about the Python-list
mailing list