1

I'm not too familiar with the OOP side of Python yet so this is a bit above my head.

>>> a=[[2,3,4]]
>>> types = (list,str,int,str,int)
>>> b=isinstance(a,types)

True

No matter what type I add on after the list type, the expression always returns True.

I have read that isinstance() method accepts derived class types but I can't really convince myself I know whats going on here.

This returns true as well. Is it because all 3 belong to the same class?

>>> isinstance([], (tuple, list, set))
True
1
  • 1
    It's True if any. You're thinking it should be True if all Commented Aug 14, 2015 at 4:35

3 Answers 3

4
In [1]: isinstance?

Docstring:

isinstance(object, class-or-type-or-tuple) -> bool

Return whether an object is an instance of a class or of a subclass thereof. With a type as second argument, return whether that is the object's type. The form using a tuple, isinstance(x, (A, B, ...)), is a shortcut for:

isinstance(x, A) or isinstance(x, B) or ... (etc.).

Type: builtin_function_or_method

So, it is actually a or statement. Very clear, right?

Sign up to request clarification or add additional context in comments.

Comments

1

That's because when you give a tuple of types as second argument to isinstance it works as 'OR' (or any) , it would return True , if the type of first argument is any of the types in that tuple.

Example -

>>> isinstance('asd',(str,bool,int))
True

Comments

1

Although a list [] is considered an Iterator in Python, just like tuple, dictionary and set, it is not derived from the same based class (unless you consider object as the base type, which is pretty much for every type).

Try this:

>>> [].__class__
<type 'list'>
>>> ().__class__
<type 'tuple'>
>>> {}.__class__
<type 'dictionary'>
>>> [].__class__.__bases__
<type 'object'>  # yeah sure

Like other have answered, giving a tuple to isinstance() is like saying this:

>>> type([]) in (tuple, list, set)
True

Classes like tuple and list are not subclasses derived from a same base class, they both just conform to a protocol of Iterable by providing __inter__() and __next__() methods. It's beauty of duck typing.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.