Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python isinstance function

Tags:

python

I cannot understand why isinstance function as second parameter need a tuple instead of some iterable?

isinstance(some_object, (some_class1, some_class2))

works fine, but

isinstance(some_object, [some_class1, some_class2])

raise a TypeError

like image 510
Fanto Avatar asked Oct 21 '25 06:10

Fanto


1 Answers

The reason seems to be "allowing only tuples is enough, it's simpler, it avoids the danger of some corner cases, and it seemed neater to the BDFL" (i.e. Guido). (Kudos to @Caleb for posting the key link in the comments.)

Here is an excerpt from this email conversation with Guido van Rossum that specifically addresses the case of other iterables for the isinstance function. (Click on the link for the complete conversation.)

On Thu, Jan 2, 2014 at 1:37 PM, James Powell wrote:

This is driven by a real-world example wherein a large number of prefixes stored in a set, necessitating:

any('spam'.startswith(c) for c in prefixes)
# or
'spam'.startswith(tuple(prefixes))

Neither of these strikes me as bad. Also, depending on whether the set of prefixes itself changes dynamically, it may be best to lift the tuple() call out of the startswith() call.

...

However, .startswith doesn't seem to be the only example of this, and the other examples are free of the string/iterable ambiguity:

isinstance(x, {int, float})

But this is even less likely to have a dynamically generated argument.

And there could still be another ambiguity here: a metaclass could conceivably make its instances (i.e. classes) iterable.

like image 110
alexis Avatar answered Oct 23 '25 20:10

alexis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!