Tuple question

Donn Cave donn at drizzle.com
Mon Sep 6 01:23:13 EDT 2004


Quoth aleaxit at yahoo.com (Alex Martelli):
| Donn Cave <donn at drizzle.com> wrote:
|> Quoth aleaxit at yahoo.com (Alex Martelli):
...
|> | So by this argument len(t) should not work if t is a tuple...
|> 
|> I expect it's used relatively infrequently, and for different
|> reasons.  "if len(info) == 5", for example - just from that
|> line from a relatively popular Python application, would you
|> guess info is a list, or a tuple?
|
| No idea -- could just as well be a dict, an array.array, whatever.
| That's the very point and the beauty of polymorphism - I don't CARE what
| kind of container 'info' is, I know by this snippet that we're testing
| if it has exactly 5 items, or not.

I can't tell if you're just being playfully obtuse, or you really
don't recognize the pattern.  For me, usage like this is a fairly
familiar sight with tuples, where it's part of a kind of poor man's
user defined data type - we get this tuple, and if it's 5 items it
would be last version's info, 6 items is the present version.  This
use for len() is totally about the intact tuple and has nothing to
do with sequential access.

|> There you go, they shouldn't be indexed or sliced, that's right!
|> Named attributes would be nice, but otherwise you use pattern
|> matching (to the extent support in Python --  key, value = item.)
|> Makes for more readable code.
|
| Not for sufficiently long tuples.  Take the 9-item tuples that the time
| module used to use before they grew names: having to unpack the tuple to
| access a single item of it would be exceedingly tedious and heavily
| boilerplatey to boot.
|
| Besides, I _do_ need to have immutable sequences that are suitable as
| dict keys.  Today, x=tuple(mylist) performs that role admirably.  So,
| say I have a dict d, indexed by such tuples -- of different lengths --
| and I want all the keys into d that have 23 as their first item.  Today
| this is a trivial task -- but if I couldn't index tuples I WOULD have a
| problem... basically I would need "frozen lists" (and "frozen dicts"
| where I today use tuple(d.iteritems())...).  Today, tuples serve all of
| these roles -- poor man's structs (lacking names), immutable 'frozen'
| lists for dict-keying roles, etc.  We need at least two new builtin
| types to take their place if we want to remove tuple indexing...

Well, it's not like I'm really proposing to take away the ersatz
list properties that tuples have.  It's just that if they were gone,
I think you'd have roughly the tuple that languages of the Lisp family
have had for so long, and apparently been so happy with while discontent
has festered in the Python world.  (It has been a long while since I
wrote my last Lisp program, but I'm assuming that's where all the FP
languages got it from.)

	Donn



More information about the Python-list mailing list