Returning a tuple-struct

James Stroud jstroud at ucla.edu
Thu Jan 19 04:34:22 CET 2006


groups.20.thebriguy at spamgourmet.com wrote:
> 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
> 

I think stylistically better might be

class NewTuple(tuple):
   def __new__(self, atup):
     self.a, self.b = atup[:2]
     return tuple.__new__(self, atup)

x = NewTuple((1, 2, 3, 4, 5))
print x
print x.a
print x.b




More information about the Python-list mailing list