On Thu, 18 Jan 2006 [EMAIL PROTECTED] 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? If i rewrite it like this: class NamedTuple(tuple): def __init__(self, values): tuple.__init__(self, values) def __getattr__(self, name): return self[self.indices[name]] class ColourTuple(NamedTuple): indices = {"red": 0, "green": 1, "blue":2} plum = ColourTuple((219, 55, 121)) Then it works. This is even an arguably better style. Changing the constructor to take *values rather than values, and to validate the length of the value tuple against the length of the index tuple, would be good, but, since i'm lazy, is left as an exercise to the reader. tom -- Throwin' Lyle's liquor away is like pickin' a fight with a meat packing plant! -- Ray Smuckles -- http://mail.python.org/mailman/listinfo/python-list