Using tuples correctly?

BJörn Lindqvist bjourne at gmail.com
Mon Oct 11 05:53:47 CEST 2004


I like tuples alot. But in some situations you seem to be forced to
access the elements of a tuple via its indexes and that is pretty
ugly. For example:

# make_color() returns a rgb tuple (r, g, b). I.e. (255, 0, 0)
print "The red value is: ", make_color()[0]

Not nice at all. It is maybe OK for a rgb tuple that only has three
elements, but for a tuple that has 10+ elements, index access is
rediculous. In that case, unpacking wont helpe either. What you would
like to write is:

print "The red value is: ", make_color().r

You can get that to work by using this recipe
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/218485 from
the Python Cookbook. Then write this:

Color = superTuple("Color", ["r", "g", "b"])
def make_color():
      return Color(12, 24, 48)

However, then make_color has to assume that there already exists a
special tuple type named Color. But that assumption is bad and you
shouldn't need to assume it. You could also write

return superTuple("Color", ["r", "g", "b"])(12, 24, 48)

To create the tuple type and instantiate it at the same type. But it
is alot to write. You could trim it down to: st("r", "g", "b")(12, 24,
48) if you want to save your fingers. Still to much and looks kinda
awkward.

After some more browsing of the Python Cookbook and googling it seems
like lots of people is trying to emulate structs on the fly in python.
So why aren't there a tuple-with-named-attributes type in python? So
you could write stuff like this:

return (r: 10, g: 20, b: 30) or maybe return (.r 10, .g 20, .b 30)

Clearly, I must be thinking wrong or it would already be implemented
in python. Atleast there would have been a PEP for it. Maybe I'm just
using tuples incorrectly and that is why my code uses index access to
tuples? Someone must have already thought about this and they must
have discussed it and quickly realized that this is A Very Bad Thing.
But why?  I'm new, so please dont get to angry if the answer is
obvious.

-- 
mvh Björn



More information about the Python-list mailing list