list vs. tuple [Re: len() should always return something]

Duncan Booth duncan.booth at invalid.invalid
Fri Jul 24 17:14:06 EDT 2009


Roy Smith <roy at panix.com> wrote:

> In article <mailman.3674.1248461573.8015.python-list at python.org>,
>  Terry Reedy <tjreedy at udel.edu> wrote:
> 
>> Better:    if isinstance(x, (int, float, complex)):
> 
> I never noticed this before, but it seems odd that the second argument
> to isinstance() should be a tuple.  Using the normal arguments made
> about tuples vs. lists, it seems like a list would be the right data
> structure here.  I suppose a set would be even more right, but (I'm
> pretty sure) isinstance() predates sets.
> 
> I'm curious why a tuple was chosen.

There's a very good reason[*]. The second argument to isinstance() is a 
classinfo where a classinfo is a type or a tuple of classinfo.

That means you can have an arbitrarily complex set of nested tuples e.g. 
(int, (float, complex)), but the immutable nature of tuples means the 
implementation of isinstance can walk the tuple tree without ever having to 
worry about infinite loops.

If classinfo could be a list of types then someone somewhere would feed it 
a recursive list and then complain that the interpreter crashed.

Exception specifications are tuples for the same reason.

[*] For some definition of 'very good'. Would Python be significantly 
impaired if you couldn't combine classinfos into a tree structure? Probably 
not.



More information about the Python-list mailing list