What is the best way to check if a given object is of a given type. How about checking if the object inherits from a given type.
Let's say I have an object o
. How do I check if it's an str
?
What is the best way to check if a given object is of a given type. How about checking if the object inherits from a given type.
Let's say I have an object o
. How do I check if it's an str
?
Sorry to be the bad cop, but asking this question is admitting you're not making full use of an object oriented design.
(see also this question about is-a)
I'm going to be a complete karma whore and post an answer because I just remembered it.
isinstance(o, str)
will return true
if o
is an str
or is of a type that inherits from str
.
type(o) == str
will return true
if and only if o
is a str. It will return false
if o
is of a type that inherits from str
.
To check if the type of o is exactly str:
type(o) is strTo check if o is an instance of str or any subclass of str (this would be the "canonical" way):
isinstance(o, str)The following also work, and can be useful in some cases:
issubclass(type(o), str) type(o) in ([str] + str.__subclasses__())
See Built-in Functions in the Python Library Reference for relevant information.
One more note: in this case, you may actually want to use
isinstance(o, basestring)
because this will also catch Unicode strings (unicode is not a subclass of str; both str and unicode are subclasses of basestring).
Alternatively, isinstance accepts a tuple of classes. This will return True if x is an instance of any subclass of any of (str, unicode):
isinstance(o, (str, unicode))
I think the cool thing about using a dynamic language like python is you really shouldn't have to check something like that.
I would just call the required methods on your object and catch an AttributeError
. Later on this will allow you to call your methods with other (seemingly unrelated) objects to accomplish different tasks, such as mocking an object for testing.
I've used this alot when getting data off the web with urllib2.urlopen()
which returns a file like object. This can in turn can be passed to almost any method that reads from a file, because is implements the same read()
method as a real file.
But I'm sure there is a time and place for using isinstance()
, otherwise it probably wouldn't be there :)
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 to use the object's methods the way you want to use them. So if you're function is looking for a writable file object, don't check that it's a subclass of file
, 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.