What's the canonical way to check for type in Python?
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
?
To check if o
is an instance of str
or any subclass of str
, use isinstance (this would be the "canonical" way):
if isinstance(o, str):
To check if the type of o
is exactly str
:
if type(o) is str:
The following also works, and can be useful in some cases:
if issubclass(type(o), str):
if type(o) in ([str] + str.__subclasses__()):
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:
if 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
). Note that basestring
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):
if isinstance(o, (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 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 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.
isinstance(o, str)
will return true
if o
is an str
or is of a type that inherits from str
.
type(o) is 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
. ----
上一篇: 确定一个对象的类型?