f---ing typechecking

James Stroud jstroud at mbi.ucla.edu
Wed Feb 14 23:34:20 EST 2007


skip at pobox.com wrote:
>     >> Concatenating tuples and lists seems logical if you think of tuples
>     >> as sequences.  If you think of them more like Pascal records or C
>     >> structs instead (I believe that's Guido's perspective on tuples) then
>     >> it makes no sense at all.
> 
>     James> Then iterating over them makes no sense?
> 
> I agree that tuples are a bit schizophrenic.  They really are sequences from
> an implementation standpoint, but from a logical standpoint it's maybe best
> not to think of them that way.
> 
> That said, this:
> 
>     for x in (1,2,3):
>       pass
> 
> is a skosh faster (perhaps an immeasurably small skosh) than this:
> 
>     for x in [1,2,3]:
>       pass
> 
> so people will probably continue to use tuples instead of lists in these
> sorts of situations.
> 
> For an example of the struct-ness of a tuple consider the output of os.stat:
> 
>     >>> import os
>     >>> s = os.stat("/etc/hosts")
>     >>> s
>     (33188, 34020475L, 234881029L, 1, 0, 0, 214L, 1170562950, 1124700602, 1142602578)
>     >>> s.st_mtime
>     1124700602.0
>     >>> s[0]
>     33188
>     >>> type(s)
>     <type 'posix.stat_result'>
> 
> It's effectively a tuple with field names.  I don't know when the switch
> occurred (it's in 2.2, as far back as my built interpreter versions
> currently go), but back in the day os.stat used to return a plain old tuple.
> 
> I have no idea if the schizophrenic personality of tuples will improve with
> drugs^H^H^H^H^H Python 3, but I wouldn't be at all surprised if it did.
> 
> Skip

The arguments for how tuples behave are all very compelling and indeed I 
keep them in mind when I code--careful not to confuse their uses. The 
problem is that, to the uninitiated, they are redundant and are often 
used interchangably. Also, it is very easy for the uninitiated to create 
highly functional code in python, and so we get many hybrid uses and 
confusion. I increasingly come to the decision to avoid tuples 
altogether because, eventually, you end up turning them into lists 
anyway and so they begin to represent extra overhead--although its 
always fun to try to identify cases when they might provide some value.

James



More information about the Python-list mailing list