Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use isinstance() instead of type()? [duplicate]

Tags:

python

types

I've seen people often recommend using isinstance() instead of type(), which I find odd because type() seems more readable to me.

>>> isinstance("String",str)
True
>>> type("String") is str
True

The latter seems more pythonic and clear while the former is slightly obfuscated and implies a specific use to me (for example, testing user built classes rather than built in types) but is there some other benefit that I'm unaware of? Does type() cause some erratic behaviour or miss some comparisons?

like image 607
SuperBiasedMan Avatar asked May 05 '15 09:05

SuperBiasedMan


People also ask

Why is it better to use Isinstance?

isinstance is usually the preferred way to compare types. It's not only faster but also considers inheritance, which is often the desired behavior. In Python, you usually want to check if a given object behaves like a string or a list, not necessarily if it's exactly a string.

Why should I use Isinstance Python?

If you need to check the type of an object, it is recommended to use the Python isinstance() function instead. It's because isinstance() function also checks if the given object is an instance of the subclass.

What is the purpose of Isinstance () function?

The isinstance() function returns True if the specified object is of the specified type, otherwise False . If the type parameter is a tuple, this function will return True if the object is one of the types in the tuple.

Is Isinstance the best way to check types?

Generally speaking isinstance is a 'more' elegant way of checking if an object is of a certain "type" (since you are aware of the Inheritance chain). On the other hand, if you are not aware of the inheritance chain and you need to be pick, go for type(x) == ...


1 Answers

Let me give you a simple example why they can be different:

>>> class A(object): pass
>>> class B(A) : pass
>>> a = A()
>>> b = B()

So far, declared a variable A and a variable B derived from A.

>>> isinstance(a, A)
True
>>> type(a) == A
True

BUT

>>> isinstance(b, A)
True
>>> type(b) == A
False
like image 63
rafaelc Avatar answered Sep 20 '22 01:09

rafaelc