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?
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.
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.
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.
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) == ...
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With