How do I check if an object is of a given type, or if it inherits from a given type?
How do I check if the object o
is of type str
?
Beginners often wrongly expect the string to already be "a number" – either expecting Python 3.x input
to convert type, or expecting that a string like '1'
is also simultaneously an integer. This is the wrong canonical for those questions. Please carefully read the question and then use How do I check if a string represents a number (float or int)?, How can I read inputs as numbers? and/or Asking the user for input until they give a valid response as appropriate.
Best Answer
Use
isinstance
to check ifo
is an instance ofstr
or any subclass ofstr
:To check if the type of
o
is exactlystr
, excluding subclasses ofstr
:See Built-in Functions in the Python Library Reference for relevant information.
Checking for strings in Python 2
For Python 2, this is a better way to check if
o
is a string:because this will also catch Unicode strings.
unicode
is not a subclass ofstr
; bothstr
andunicode
are subclasses ofbasestring
. In Python 3,basestring
no longer exists since there's a strict separation of strings (str
) and binary data (bytes
).Alternatively,
isinstance
accepts a tuple of classes. This will returnTrue
ifo
is an instance of any subclass of any of(str, unicode)
: