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 - For functions, you can annotate arguments and the return value. This is done as follows: ... For arguments the syntax is argument: annotation, while the return type is annotated using -> annotation. Note that the annotation must be a valid Python expression. The following simple example adds annotations to a function that calculates the circumference of a circle:
🌐
TestDriven.io
testdriven.io › blog › python-type-checking
Python Type Checking | TestDriven.io
December 1, 2023 - You can similarly use a decorator for functions like so: from typeguard import typechecked @typechecked def sum_ab(a: int, b: int) -> int: return a + b · It also comes with a pytest plugin. To check types for package my_package while running tests you can run this command: $ python -m pytest --typeguard-packages=my_package
Discussions

How to check for a function type in Python? - Stack Overflow
I've got a list of things, of which some can also be functions. If it is a function I would like to execute it. For this I do a type-check. This normally works for other types, like str, int or flo... More on stackoverflow.com
🌐 stackoverflow.com
Python type checking for functions - Stack Overflow
I'm having some issues figuring out how to mark up functions for type checking. Let's say I have the following situation: class BaseClass: def __init__(self): self.name = 'base' class More on stackoverflow.com
🌐 stackoverflow.com
Type checking in Python - Stack Overflow
How can I check the type of function's parameters? For example, def hello(x): # check if x is tuple # check if x is dictionary. ... ... Save this answer. ... Show activity on this post. ... You should never be unsure of the type of a thing in python; it's basically impossible to check accurately. More on stackoverflow.com
🌐 stackoverflow.com
Do type hints/strict argument type checking works in Python?
Python itself ignores all type annotations, there are currently no plans to change that. They're entirely optional. However, that's why tools such as mypy exist. With IDE integrations, you can see all the type mismatches your heart desires, and if you want to enforce them at deployment time you can add a check as part of your CI pipeline to block commits that have type errors. You can also use mypyc (pip install mypy[mypyc]) to get a decent performance boost from using them, without any extra cost on your part. EDIT: Certain packages like Pydantic and FastAPI do make use of them to offer automatic type validation/conversion/parsing capabilities, I felt like that was worth mentioning. More on reddit.com
🌐 r/learnpython
7
2
July 31, 2024
🌐
DataCamp
datacamp.com › tutorial › type-checking-in-python
Type Checking in Python Tutorial | DataCamp
May 5, 2020 - 'mypy' is a python module which helps in a static type checking, which uses the Python's own dynamic checking or duck typing with the type-hinting. You need to install 'mypy' packages pip install mypy · You can create a file named 'mypy_example.py' in your local machine and type the following code. The below code is a simple program that accepts two integers as an input in the parameter and after '->' shows the returned data type, which is also an 'int'. However, the function needs to return int, but string 'Subtracted two integers' is returned.
🌐
Berkeley
pythonnumericalmethods.studentorg.berkeley.edu › notebooks › chapter10.04-Type-Checking.html
Type Checking — Python Numerical Methods
Try your function for erroneous input arguments to verify that they are checked. def my_adder(a, b, c): # type check if isinstance(a, float) and isinstance(b, float) and isinstance(c, float): pass else: raise(TypeError('Input arguments must be floats')) out = a + b + c return out
🌐
Python
typing.python.org › en › latest › spec › directives.html
Type checker directives — typing documentation
Any syntax that indirectly triggers a call to the function. 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.
Find elsewhere
🌐
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.
🌐
CodeGenes
codegenes.net › blog › how-to-do-type-check-in-python
Mastering Type Checking in Python — codegenes.net
In this example, the add_numbers function checks if both arguments a and b are either integers or floats. If not, it raises a TypeError. Type hints are a way to annotate the expected types of variables and function arguments in Python.
🌐
Python documentation
docs.python.org › 3 › library › typing.html
typing — Support for type hints
1 week ago - When a TypeIs function returns False, type checkers can narrow the type of the variable to exclude the TypeIs type. Added in version 3.10. ... Typing operator to conceptually mark an object as having been unpacked. For example, using the unpack operator * on a type variable tuple is equivalent to using Unpack to mark the type variable tuple as having been unpacked:
🌐
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 - Here we will walk through a concrete problem with Python without type checking. Please note: The example code here is provided in the larkintuckerllc / typelearning Repository. ... Based on the usage, it appears that the Resource object’s read_metadata method returns a Dict[str, MetadataItem] object · Finally, it passes the Dict[str, MetadataItem] to the has_name function and prints its return value (in this case True)
🌐
DEV Community
dev.to › on_stash › type-checking-in-python-1mcn
Type-checking in Python - DEV Community
June 6, 2018 - In the course of discussing how to improve the Developer Experience (DX) of a Python developer, my mentor, Sriram, and I came with up with an idea of a type checking decorator for type checking function arguments. Introducing typy_checker, an easy-to-use library for type-checking your functions without losing your sanity over it. Here is how we could use typy_checker in our example.
🌐
Kansas State University
textbooks.cs.ksu.edu › cc410 › z-examples › 01-hello-real-world › 04-python › 09-type-checking
Type Checking :: CC 410 Textbook
September 10, 2025 - To add type hinting, we need to add information to each variable and function at a bare minimum. So, let’s look at the function first. Recall that functions can return a value using the return keyword. We don’t see that in our main function, so it doesn’t return a value, right? In fact, any Python function that doesn’t explicitly return a value within the code actually returns the value None by default.
🌐
pythontutorials
pythontutorials.net › blog › how-to-perform-type-checking-with-the-typing-python-module
How to Implement Dynamic Type Checking in Python with the typing Module: Building a check_type Function for Generics and Basic Types — pythontutorials.net
We check length and element types accordingly. Combining all these, here’s the complete function: from typing import Any, Union, Tuple, List, Dict, Set, FrozenSet, get_origin, get_args # Compatibility mapping for typing generics (Python <3.9) TYPING_TO_BUILTIN = { List: list, Dict: dict, Set: set, FrozenSet: frozenset, Tuple: tuple, } def check_type(value: Any, type_hint: Any) -> bool: """ Dynamically check if `value` conforms to `type_hint`. Args: value: The value to validate.
🌐
DigitalOcean
digitalocean.com › community › tutorials › python-type
Python type() Function Explained | DigitalOcean
Learn how to use Python’s type() function to check data types and create dynamic classes. Includes syntax, examples, and practical tips.
🌐
Mouse Vs Python
blog.pythonlibrary.org › home › type checking in python
Type Checking in Python - Mouse Vs Python
October 5, 2021 - def some_function(a, b, c): # type: (str, int, int) -> None print(a) Some Python IDEs may support type hinting in the docstring instead. PyCharm lets you do the following for example:
🌐
Digis
digiscorp.com › python-check-type-of-variable-top-3-methods-explained
Python Check Type of Variable: Top 3 Methods Explained
December 9, 2024 - For that reason, type checking and data validation should be treated as related but separate concerns. The built-in type() function is the most direct way to find the exact type of an object in Python. When passed a variable, it returns the class to which that object belongs. A basic example is ...
🌐
Medium
medium.com › @ageitgey › learn-how-to-use-static-type-checking-in-python-3-6-in-10-minutes-12c86d72677b
How to Use Static Type Checking in Python 3.6 | by Adam Geitgey | Medium
June 26, 2017 - You can use the Union type to declare a function that can accept multiple types and you can use Any to accept anything. Python 3.6 also supports some of the fancy typing stuff you might have seen in other programming languages like generic types and custom user-defined types. While Python 3.6 gives you this syntax for declaring types, there’s absolutely nothing in Python itself yet that does anything with these type declarations. To actually enforce type checking, you need to do one of two things: