Super Tuples
Paul Prescod
paul at prescod.net
Wed Dec 29 08:44:23 EST 1999
Eugene Goodrich wrote:
>
> When I started in Python, my PyMentor described tuples as immutable
> lists. When they start acting like much more than that, isn't it time
> to use an object?
I agree that tuples in Python are often used merely as immutable lists.
This bothers me for several reasons:
* that isn't what "tuple" means in mathematics. In most mathematics
EVERYTHING is immutable. Tuples and lists are still distinct
* why does Python need an immutable list type but not an immutable
dictionary?
* isn't immutability more a property of where an object is used than
the objects actual type? For example, don't you sometimes want to pass a
list to a function but guarantee that the list won't be modified?
* it is because of this abuse that the "one-item tuple" problem arises
so often. There is no such problem in mathematics because a one-item
tuple does not make sense.
In Python world we most often use tuples as mathematicians do. Really, a
tuple is supposed to be a collection of things where the sender and the
recieiver have agreed on the number of items in advance, and every item
has a special "meaning." The time library is a perfect example of this:
"The time tuple as returned by gmtime(), localtime(), and strptime(),
and accepted by asctime(), mktime() and strftime(), is a tuple of 9
integers: year (e.g. 1993), month (1-12), day (1-31), hour (0-23),
minute (0-59), second (0-59), weekday (0-6, monday is 0), Julian day
(1-366) and daylight savings flag (-1, 0 or 1)."
The primary weakness with the time library is that you have to index
daylight savings flag by (for example) [9] instead of .daylight .
If you use tuples as mathematicians do then single-item tuples can never
arise because senders and recievers would never agree on a "protocol"
(used loosely) that involves 1 length tuples (why use a tuple!).
Paul Prescod
More information about the Python-list
mailing list