Python 3 isinstance

Duncan Booth duncan.booth at invalid.invalid
Fri Jan 16 10:58:53 CET 2009

Carl Banks <pavlovevidence at> wrote:

> On Jan 15, 1:08 pm, Duncan Booth < at invalid.invalid> wrote:
>> Carl Banks <pavlovevide... at> wrote:
>> > I don't see what the big deal is.  Right now isinstance accepts a
>> > typ 
> e
>> > or a tuple of types.  The code could be changed to allow a type, or
>> > any iterable the returns types (wherein every items of the sequence
>> > is required to be a type).  What's messy about that?
>> No, it isn't restricted to a type or a tuple of types: right now
>> isinstan 
> ce
>> accepts X where X is a type or a tuple of X. The definition is
>> recursive, and the data structure can be deeply nested, but (because
>> tuples are immutable) it cannot be infinite.
>> e.g.>>> isinstance('x', (((((int, (float, str)),),),),))
>> True
> Oh.  Not sure what the use case for THAT was, but that would make
> things messy.
Duck typing purism?

If you can use it to specify an exception you want to handle, then you 
can put it in a tuple with other exception specifications you can also 
handle. If you had to check whether it was a class or tuple to work out 
which sort of concatenation to use then you are breaking the first law 
of ducks.

I think exception specifications came first and isinstance/issubclass 
followed suit, except of course exception specification were more 
complex as they could be classes, strings, or tuples of exception 

That still leaves the question whether anyone has ever actually taken 
advantage of this feature. You can do isinstance(x, (IntType, LongType, 
StringTypes)) but I didn't even know that StringTypes existed until a 
couple of moments ago, and I intend to forget about it again 
immediately. Grepping through the Python libraries on my system it looks 
like a lot of programmers don't even realise you can combine types into 
a tuple.

Duncan Booth

More information about the Python-list mailing list