Herge Herge - 2 years ago 83
Python Question

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

. How do I check whether it's a

Answer Source

To check if the type of o is exactly str:

type(o) is str

To 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 works, 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))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download