Returning a tuple-struct

James Stroud jstroud at ucla.edu
Sun Jan 22 22:01:16 EST 2006


Tom Anderson wrote:
> On Thu, 18 Jan 2006 groups.20.thebriguy at spamgourmet.com wrote:
> 
>> Is there a better way?  Thoughts?
> 
> 
> I was thinking along these lines:
> 
> class NamedTuple(tuple):
>     def __init__(self, indices, values):
>         "indices should be a map from name to index"
>         tuple.__init__(self, values)
>         self.indices = indices
>     def __getattr__(self, name):
>         return self[self.indices[name]]
> 
> colourNames = {"red": 0, "green": 1, "blue":2}
> plum = NamedTuple(colourNames, (219, 55, 121))
> 
> The idea is that it's a tuple, but it has some metadata alongside 
> (shared with other similarly-shaped tuples) which allows it to resolve 
> names to indices - thus avoiding having two references to everything.
> 
> However, if i try that, i get:
> 
> Traceback (most recent call last):
>   File "<stdin>", line 1, in ?
> TypeError: tuple() takes at most 1 argument (2 given)
> 
> As far as i can tell, inheriting from tuple is forcing my constructor to 
> only take one argument. Is that the case? If so, anyone got any idea why?
> 

This error message is not coming from __init__, but from __new__. See

      http://www.python.org/2.2/descrintro.html#__new__

James



More information about the Python-list mailing list