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)):
Answer from Fredrik Johansson on Stack Overflow
🌐
Real Python
realpython.com β€Ί python-type-checking
Python Type Checking (Guide) – Real Python
January 7, 2019 - In the first example, the branch 1 + "two" never runs so it’s never type checked. The second example shows that when 1 + "two" is evaluated it raises a TypeError since you can’t add an integer and a string in Python.
🌐
Python documentation
docs.python.org β€Ί 3 β€Ί library β€Ί typing.html
typing β€” Support for type hints
For example: from collections.abc import Mapping # Type checker will infer that all elements in ``x`` are meant to be ints x: list[int] = [] # Type checker error: ``list`` only accepts a single type argument: y: list[int, str] = [1, 'foo'] # ...
Discussions

What's the canonical way to check for type in Python? - Stack Overflow
So a and b would have to be the ... See for example stackoverflow.com/a/133024/1072212 2017-06-09T17:47:25.187Z+00:00 ... @JonCoombs According to the rationale of PEP 622, isinstance() is the second most called builtin function, after len(). I think we have to accept that isinstance is de facto canonical Python. 2020-07-04T16:10:48.437Z+00:00 ... Save this answer. ... Show activity on this post. The most Pythonic way to check the type of an object ... More on stackoverflow.com
🌐 stackoverflow.com
Can someone explain to me what TYPE_CHECKING does?
Documentation for that is here: https://docs.python.org/3/library/typing.html#typing.TYPE_CHECKING More on reddit.com
🌐 r/learnpython
4
9
September 24, 2020
Best practice for type checking and assert statement
Hi, I would like to learn the ideas and concepts around how to code and/or design Python programs in order to define type hints, check type of inputs and/or if the inputs do exist. For instance, image I need to define a function that takes a list of strings as inputs. def fun(input: list[str]): ... More on discuss.python.org
🌐 discuss.python.org
4
0
September 14, 2023
Why is typechecking bad in Python?

This is a pretty good summary of why it is considered bad form, and what to do instead (i.e. capability checking): http://blog.codekills.net/2011/09/26/checking-types-in-python/

-- edit: for a very simple tldr, it is hard to typecheck, so it is better to just publish the interface and assume your users will conform, or break if they do not.

More on reddit.com
🌐 r/learnpython
15
14
September 23, 2014
🌐
Python
typing.python.org β€Ί en β€Ί latest β€Ί spec β€Ί directives.html
Type checker directives β€” typing documentation
For example, if the __add__ method of a class C is deprecated, then the code C() + C() should trigger a diagnostic. Similarly, if the setter of a property is marked deprecated, attempts to set the property should trigger a diagnostic. If a method is marked with the @override decorator and the ...
🌐
TestDriven.io
testdriven.io β€Ί blog β€Ί python-type-checking
Python Type Checking | TestDriven.io
December 1, 2023 - For example, a = 1 + '0' will set a to 10. While dynamic typing brings flexibility, it isn't always desirable so, there have been a number of efforts as of late to bring static type inference to dynamic languages.
🌐
Medium
john-tucker.medium.com β€Ί type-checking-python-306ad8339da1
Type Checking Python. Learning that we can have our cake… | by John Tucker | Medium
November 22, 2021 - On the other hand, let us say we wrote the same example using type checking. ... As before, we change the behavior of the read_metadata method to instead return None instead of an empty Dict[str, MetadataItem] when the Resource object’s metadata does not have any of the items as keys. With this change, we can immediately see a problem with the has_name function in our editor (here with VSCode enabled with Python type checking).
🌐
DataCamp
datacamp.com β€Ί tutorial β€Ί type-checking-in-python
Type Checking in Python Tutorial | DataCamp
May 5, 2020 - Also, the type system of the language doesn't force to explicitly declare the 'data-type' of the variable before its usage. The programming languages which are dynamically typed are: Python, Javascript, Ruby, etc. For example, the String in Python is defined below: myCar = "Mercedes" The above ...
Find elsewhere
🌐
GeeksforGeeks
geeksforgeeks.org β€Ί python β€Ί type-isinstance-python
type and isinstance in Python - GeeksforGeeks
July 25, 2022 - Python has a built-in method called type which generally comes in handy while figuring out the type of the variable used in the program in the runtime. The canonical way to check for type in Python is given below: ... In this example, we are trying to check the data type of each variable, such as x, s, and y using type() function.
🌐
Guru99
guru99.com β€Ί home β€Ί python β€Ί type() and isinstance() in python with examples
type() and isinstance() in Python with Examples
July 10, 2026 - In this example we are going to compare the float value with type float i.e. 3.14 value will be compare with type float. pi = isinstance(3.14,float) print("pi is a float:", pi) ... The code checks for a tuple (1,2,3,4,5) with type tuple.
🌐
LabEx
labex.io β€Ί tutorials β€Ί python-how-to-perform-type-checking-in-python-398052
How to perform type checking in Python | LabEx
In this example, we use the typing module to specify that the calculate_average() function expects a list of floats as input and returns a float. We also use type annotations to indicate that the result is a tuple of two floats.
🌐
DEV Community
dev.to β€Ί saranshabd β€Ί python-w-strict-typechecker-3l7g
Python w/ strict typechecker - DEV Community
December 23, 2022 - Fun fact: mypy has been around even before Python3.x. Programmers would add special comments to annotate types to their functions in Python2.x; similar to how types can be defined in JavaScript using JSDocs. mypy will go through all the files (that you specify) and check the type definitions of all the functions, methods and variables. For example, you will get the following output when running the above example.py file through mypy:
🌐
Digis
digiscorp.com β€Ί python-check-type-of-variable-top-3-methods-explained
Python Check Type of Variable: Top 3 Methods Explained
December 9, 2024 - This distinction is important because ... For example, checking whether type(value) is exactly a particular class asks a narrower question than asking whether the value belongs to that class hierarchy....
🌐
Reddit
reddit.com β€Ί r/learnpython β€Ί can someone explain to me what type_checking does?
r/learnpython on Reddit: Can someone explain to me what TYPE_CHECKING does?
September 24, 2020 -

I'm doing a tutorial right now and they use it in multiple classes and I have no idea what it does for the program.

I've tried looking through the documentation, but it hasn't helped much and I can't find anyone talking about what it does.

Sorry if this is an googleable question, but maybe I've just been searching the wrong thing. All I can find is general type checking help instead of this specific function or library. Generally when it's used they'll import TYPE_CHECKING from typing and then use it like:

if TYPE_CHECKING:

# import from another file here

🌐
CodeGenes
codegenes.net β€Ί blog β€Ί how-to-check-type-in-python
Mastering Type Checking in Python β€” codegenes.net
It takes an object as an argument and returns a type object. # Example of using type() num = 42 print(type(num)) # Output: <class 'int'> name = "John" print(type(name)) # Output: <class 'str'>
🌐
Codecademy
codecademy.com β€Ί article β€Ί what-are-python-data-types-and-how-to-check-them
What are Python Data Types and How to Check Them | Codecademy
In the example code, the isinstance() function checks whether a variable belongs to a specified type or a tuple of types and returns the boolean values. Note: In Python, bool is a subclass of int, so isinstance(True, int) returns True.
🌐
Python.org
discuss.python.org β€Ί python help
Best practice for type checking and assert statement - Python Help - Discussions on Python.org
September 14, 2023 - Hi, I would like to learn the ideas and concepts around how to code and/or design Python programs in order to define type hints, check type of inputs and/or if the inputs do exist. For instance, image I need to define a function that takes a list of strings as inputs. def fun(input: list[str]): if input and isinstance(input, str): input = [input] assert isistance(input, list), "input should be a list" Now, is that example a best practice on how to define a function?
🌐
CodeRivers
coderivers.org β€Ί blog β€Ί python-type-check
Python Type Checking: A Comprehensive Guide - CodeRivers
February 22, 2026 - Dynamic Type Checking: Python performs dynamic type checking during runtime. For example, when you try to add a string and an integer, Python will raise a TypeError at the point where the operation is attempted.
🌐
CodeRivers
coderivers.org β€Ί blog β€Ί how-to-check-type-in-python
Checking Types in Python: A Comprehensive Guide - CodeRivers
February 22, 2026 - Code Clarity: Type checking can make your code more understandable, especially for other developers who may be reading or maintaining it. It clearly shows the expected types of variables and function arguments. The type() function in Python returns the type of an object. The basic syntax is type(object). Here are some examples:
🌐
Index.dev
index.dev β€Ί blog β€Ί check-python-variable-types
How to Check the Type of Variable in Python (+Examples)
Use type() when you need the exact class, and isinstance() when subclasses should count. For real safety, do not lean on runtime checks. Add type hints with built-in generics like list[int], then catch errors before they ship with a static checker such as mypy, Pyright, or ty. Python is dynamically typed, so you never declare a variable's type.
🌐
Altcademy
altcademy.com β€Ί blog β€Ί how-to-check-type-in-python
How to check type in Python - Altcademy.com
September 12, 2023 - While the type() function is great for checking the exact type of an object, Python also provides another function, isinstance(), which is often more useful. The isinstance() function checks if an object is of a certain type or is a subclass of that type.