Python 3 isinstance
Duncan Booth
duncan.booth at invalid.invalid
Thu Jan 15 04:35:42 EST 2009
Terry Reedy <tjreedy at udel.edu> wrote:
> Lambert, David W (S&T) wrote:
>> Overly terse. I do mean that this is illegal:
>>
>> isinstance(s, {str, bytes})
>>
>> tuples have order, immutability, and the possibility of repeat items.
>>
>> A set is most reasonable in a mathematical sense.
>
> I agree. However, isinstance predates set. Hence the status quo.
>
>
There is another reason which nobody has mentioned, and which might make it
tricky to do a good implementation that does accept sets.
The second argument to isinstance or issubclass is a classinfo where a
classinfo is either a class or a tuple of classinfo. This makes it easy to
group related types: you can just combine existing groups of types together
without having to flatten tuples. The immutability of tuples guarantees
that you cannot create a recursive structure this way.
If you allow sets then the code which traverses the classinfo has to
protect itself against the possibility of an infinite recursion.
The same argument also applies to exception handlers which also accept a
type or a tuple of things they accept.
Of course you could allow either an existing classinfo or a set of types,
but not allow the set to contain anything other than types. That would
still prevent recursion but means you have to be stricter about knowing
what you are combining. That probably wouldn't be a bad thing if everyone
used sets consistently but I suspect would be messy if introduced at this
stage.
--
Duncan Booth http://kupuguy.blogspot.com
More information about the Python-list
mailing list