what best way check whether given object of given type? how checking whether object inherits given type?
let's have object o
. how check whether it's str
?
to check if type of o
str
:
type(o) str
to check if o
instance of str
or subclass of str
(this "canonical" way):
isinstance(o, str)
the following works, , can useful in cases:
issubclass(type(o), str) type(o) in ([str] + str.__subclasses__())
see built-in functions in python library reference relevant information.
one more note: in case, may want use:
isinstance(o, basestring)
because catch unicode strings (unicode
not subclass of str
; both str
, unicode
subclasses of basestring
).
alternatively, isinstance
accepts tuple of classes. return true if x instance of subclass of of (str, unicode):
isinstance(o, (str, unicode))