HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonCriticalCanonical

What's the canonical way to check for type in Python?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
checkthefortypewaycanonicalwhatpython

Problem

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?

Editor's note: Beginners often wrongly expect a 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 question does not address those types of questions. Instead, see 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.

Solution

Use isinstance to check if o is an instance of str or any subclass of str:

if isinstance(o, str):


To check if the type of o is exactly str, excluding subclasses of str:

if type(o) is str:


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:

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. 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 return True if o is an instance of any subclass of any of (str, unicode):

if isinstance(o, (str, unicode)):

Code Snippets

if isinstance(o, str):
if type(o) is str:
if isinstance(o, basestring):
if isinstance(o, (str, unicode)):

Context

Stack Overflow Q#152580, score: 2362

Revisions (0)

No revisions yet.