11

In the following snippet:

In [1]: x = [0]

In [2]: isinstance(x, list)
Out[2]: True

In [3]: isinstance(x, (list, set))
Out[3]: True

In [4]: isinstance(x, [list, set])
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-4-95dd12d6777a> in <module>()
----> 1 isinstance(x, [list, set])

TypeError: isinstance() arg 2 must be a type or tuple of types

Why does isinstance in [4] insist on the second argument being a tuple, and not just an iterable (e.g. a list or a set)? Seems like a weird design decision.

pzelasko
  • 2,082
  • 1
  • 16
  • 24
  • 1
    Here's a possibly relevant answer : https://stackoverflow.com/a/45118023/6419007 – Eric Duminil Dec 11 '18 at 10:11
  • 1
    I've decided to close as duplicate since this is basically the same question and the same answer, just regarding a different built-in function. If you disagree feel free to vote to reopen. – DeepSpace Dec 11 '18 at 10:15
  • BTW, `isinstance` works recursively, so `isinstance(1, (list, (tuple, int)))` will return `True`. – DeepSpace Dec 11 '18 at 10:16
  • 5
    @DeepSpace: As far as I know, "duplicates" are used for duplicate questions, not for related questions which might have the same answer. – Eric Duminil Dec 11 '18 at 10:19
  • 3
    @Eric In this case I think the questions are *close enough* (the *title* is very different but the question *body* basically has the same question), and the answer there is so extensive and good that it applies here 100%. – deceze Dec 11 '18 at 10:41
  • 4
    I've closed this, as we don't need a separate question on why *every* built-in which supports only tuples instead of *any* iterable has this requirement. – jpp Dec 11 '18 at 10:51
  • I've also upvoted this question as it's a good duplicate marker. – jpp Dec 11 '18 at 10:53
  • 1
    The answer for startswith() uses the rationale that strings are iterable. This is not applicable to isinstance(), where the second argument can never be a string. – Marius Gedminas Dec 18 '18 at 16:38

0 Answers0