Skip to content
Fix Code Error

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

March 13, 2021 by Code Error
Posted By: Herge

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?

Solution

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 (exclude subclasses):

if type(o) is str:

The following also works, and can be useful in some cases:

if issubclass(type(o), str):

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

if isinstance(o, (str, unicode)):
Answered By: fredrikj

Related Articles

  • Can't install via pip because of egg_info error
  • What are the differences between type() and isinstance()?
  • Spark EMR job jackson error -…
  • What's the difference between eval, exec, and compile?
  • Determine the type of an object?
  • Git command to show which specific files are ignored…
  • Usage of __slots__?
  • How to declare global variables in Android?
  • super() raises "TypeError: must be type, not…
  • Creating a singleton in Python
  • Maven Jacoco Configuration - Exclude…
  • How to update Python?
  • How to "properly" create a custom object in JavaScript?
  • How can I wrap all BeautifulSoup existing…
  • python 3.2 UnicodeEncodeError: 'charmap' codec can't…
  • Smart way to truncate long strings
  • Aurelia: partial injection for base class
  • Can we instantiate an abstract class?
  • What are type hints in Python 3.5?
  • Install pip in docker
  • Test if a variable is a list or tuple
  • Python: how to assign a name of a list variable to a class
  • What are the nuances of scope prototypal /…
  • How do I merge two dictionaries in a single…
  • Is turtle.Screen a subclass of turtle.TurtleScreen…
  • Do subclasses inherit private fields?
  • Are static methods inherited in Java?
  • check if variable is dataframe
  • Java serialization - java.io.InvalidClassException…
  • How do SO_REUSEADDR and SO_REUSEPORT differ?
  • configure: error: C compiler cannot create executables
  • Elegant ways to support equivalence ("equality") in…
  • Check if a Class Object is subclass of another Class…
  • using d3.js with aurelia framework
  • Best way to replace multiple characters in a string?
  • How do I keep only the first map and when the game…
  • Extracting values from a nested object and sorting…
  • Manually raising (throwing) an exception in Python
  • Is CSS Turing complete?
  • How do I check if a type is a subtype OR the type of…
  • Examples of GoF Design Patterns in Java's core libraries
  • Relative imports for the billionth time
  • TypeError: Cannot read property 'webpackJsonp' of undefined
  • How does PHP 'foreach' actually work?
  • Reference - What does this regex mean?
  • Logging best practices
  • AppCompat v7 r21 returning error in values.xml?
  • Use Robocopy to copy only changed files?
  • Are dictionaries ordered in Python 3.6+?
  • How do I exclude all instances of a transitive…
  • Keras Sequential API is replacing every layer with…
  • Python File Error: unpack requires a buffer of 16 bytes
  • What does Ruby have that Python doesn't, and vice versa?
  • Shell command to tar directory excluding certain…
  • How to get exception message in Python properly
  • C++ template,typename and operator
  • Start redis-server with config file
  • Android APK signatures V1 and V2 conflict
  • How can a maven build fail when certain dependencies…
  • Confusion with Haskell classes
  • Copy folder recursively, excluding some folders
  • Deploying Maven project throws…
  • What version of Python is on my Mac?
  • How can I install a previous version of Python 3 in…
  • Using setInterval for creating animation
  • Is False == 0 and True == 1 an implementation detail…
  • Difference between
  • For-each over an array in JavaScript
  • Checking whether a variable is an integer or not
  • Django testing custom signal arguments with…
  • Why does .loc not always match column names?
  • What does "Fatal error: Unexpectedly found nil while…
  • Making a map of composite types typescript
  • What is the best (idiomatic) way to check the type…
  • Add Keypair to existing EC2 instance
  • What is the difference between venv, pyvenv, pyenv,…
  • What is an optional value in Swift?
  • Why do Python classes inherit object?
  • Amazon Interview Question: Design an OO parking lot
  • Install opencv for Python 3.3
  • How to monitor a filtered version of a metric in…
  • Connection failure using EC2 Instance Connect…
  • Java error: Implicit super constructor is undefined…
  • Why is "except: pass" a bad programming practice?
  • SwiftUI Parsing and displaying values form a JSON call
  • How to compare type of an object in Python?
  • How do I find all files containing specific text on Linux?
  • Flatten an irregular list of lists
  • The definitive guide to form-based website authentication
  • CSS animate a conical gradient as border image
  • Finding index of character in Swift String
  • How to serialize SqlAlchemy result to JSON?
  • How do you read a Python Traceback error?
  • Assigning a variable NaN in python without numpy
  • Convert Django Model object to dict with all of the…
  • Best way to namespace multiple or suit of emberjs apps
  • /exclude in xcopy just for a file type
  • Using Auto Layout in UITableView for dynamic cell…
  • How to check if an element of a list is a list (in Python)?
  • What's the difference between getPath(),…

Disclaimer: This content is shared under creative common license cc-by-sa 3.0. It is generated from StackExchange Website Network.

Post navigation

Previous Post:

How do I delete an exported environment variable?

Next Post:

Upgrading Node.js to latest version

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

.net ajax android angular arrays aurelia backbone.js bash c++ css dataframe ember-data ember.js excel git html ios java javascript jquery json laravel linux list mysql next.js node.js pandas php polymer polymer-1.0 python python-3.x r reactjs regex sql sql-server string svelte typescript vue-component vue.js vuejs2 vuetify.js

  • you shouldn’t need to use z-index
  • No column in target database, but getting “The schema update is terminating because data loss might occur”
  • Angular – expected call-signature: ‘changePassword’ to have a typedeftslint(typedef)
  • trying to implement NativeAdFactory imports deprecated method by default in flutter java project
  • What should I use to get an attribute out of my foreign table in Laravel?
© 2022 Fix Code Error