Using tuples correctly?

Robert Brewer fumanchu at amor.org
Mon Oct 11 11:48:27 EDT 2004


BJörn Lindqvist wrote:
> > > So you could write stuff like this:
> > >
> > > return (r: 10, g: 20, b: 30) or maybe return (.r 10, .g 20, .b 30)
> > 
> Robert Brewer:
> > 
> > color = RGB(10, 20, 30)
> > print "The red value is: ", color.red
> > 
> > If you *must* have a tuple to throw around, give your class 
> a 'tuple' method:
> > 
> > class RGB(object):
> >     def __init__(self, r=0, g=0, b=0):
> >         self.red = r
> >         self.green = g
> >         self.blue = b
> > 
> >     def tuple(self):
> >         return (self.r, self.g, self.b)
> > 
> > Why bother to shoehorn all of the name scaffolding into 
> tuples when it's already present in classes?
> 
> Because you have to declare classes before you can instantiate them.
> If you wanted a RGB tuple, would you really create a class for it? If
> you wanted a 2d point? I guess tuples aren't really needed in python,
> you can always get by by creating objects when you would have used
> types. However, creating a class when all you want is a C-like struct
> leads to alot of tedious and unnecessary work.
> 
> In my thinking, this:
> 
> return (r: 10, g: 20, b: 30)
> 
> would be read more as "create and return an anonymous object with
> three attributes r, g, b set to 10, 20, 30".

I have a feeling you also expect three *ordered* attributes; otherwise you could just say:

return {'r': 10, 'g': 20, 'b': 30}

or

return dict(r=10, g=20, b=30)

One of the problems with an imaginary anonymous tuple (as opposed to a class) is that it's truly anonymous: there's nothing about the tuple that indicates what r, g, and b are, nor anything which indicates what the tuple as a whole is, and in fact, no way to do so except bare #comments in the code. A class collects the semantics of your data and its attributes and behaviors into a single place, forcing you to make it more readable and more accessible to those who follow you (even if that's you-in-5-years).


Robert Brewer
MIS
Amor Ministries
fumanchu at amor.org



More information about the Python-list mailing list