What is the best way to check whether a given object is of a given type? How about checking whether the object inherits from a given type?
Let's say I have an object o
. How do I check whether it's a str
?
What is the best way to check whether a given object is of a given type? How about checking whether the object inherits from a given type?
Let's say I have an object o
. How do I check whether it's a str
?
Here is an example why duck typing is evil without knowing when it is dangerous. For instance: Here is the Python code (possibly omitting proper indenting), note that this situation is avoidable by taking care of isinstance and issubclassof functions to make sure that when you really need a duck, you don't get a bomb.
To check if
o
is an instance ofstr
or any subclass ofstr
, use isinstance (this would be the "canonical" way):To check if the type of
o
is exactlystr
(exclude subclasses):The following also works, and can be useful in some cases:
See Built-in Functions in the Python Library Reference for relevant information.
One more note: in this case, if you're using python 2, you may actually want to use:
because this will also catch Unicode strings (
unicode
is not a subclass ofstr
; bothstr
andunicode
are subclasses ofbasestring
). Note thatbasestring
no longer exists in python 3, where there's a strict separation of strings (str
) and binary data (bytes
).Alternatively,
isinstance
accepts a tuple of classes. This will return True if x is an instance of any subclass of any of (str, unicode):The most Pythonic way to check the type of an object is... not to check it.
Since Python encourages Duck Typing, you should just
try...except
to use the object's methods the way you want to use them. So if your function is looking for a writable file object, don't check that it's a subclass offile
, just try to use its.write()
method!Of course, sometimes these nice abstractions break down and
isinstance(obj, cls)
is what you need. But use sparingly.