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
🌐
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

Discussions

Why if TYPE_CHECKING?
from __future__ import annotations Then you will not get this error (NameError: name 'Sequence' is not defined) because it will not need the reference to `Sequence` for the annotation but the annotation is simply a string · Using `if TYPE_CHECKING` is also useful when you want to speed up ... More on news.ycombinator.com
🌐 news.ycombinator.com
72
28
December 22, 2023
python - How does mypy use typing.TYPE_CHECKING to resolve the circular import annotation problem? - Stack Overflow
I have the following structure for a package: /prog -- /ui ---- /menus ------ __init__.py ------ main_menu.py ------ file_menu.py -- __init__.py __init__.py prog.py These are my import/classes More on stackoverflow.com
🌐 stackoverflow.com
TYPE_CHECKING only imports should trigger errors on non-annotation usage
Bug Report this should warn for all non-annotation usages of FunctionType from typing import TYPE_CHECKING, cast if TYPE_CHECKING: from types import FunctionType def testit(func: FunctionType) ->... More on github.com
🌐 github.com
8
November 29, 2023
How to use type checking dynamically
You say “type checking” but then disregard mypy and static type checking, but that is what type checking is in Python. There is no “typing system” to do type checking at runtime in Python unless you add your own manual checks as suggested by another commenter. If you did want to use mypy, it seems to me that your only type issue is the fact that Pandas columns can have different types that cannot always be known in advance. I suggest generics. Otherwise you need something like dependent types which would be hard to implement in Python. More on reddit.com
🌐 r/Python
26
1
May 21, 2025
🌐
Python documentation
docs.python.org › 3 › library › typing.html
typing — Support for type hints
For most containers in Python, the typing system assumes that all elements in the container will be of the same type. 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'] # Type checker will infer that all keys in ``z`` are meant to be strings, # and that all values in ``z`` are meant to be either strings or ints z: Mapping[str, str | int] = {}
🌐
Vickiboykis
vickiboykis.com › 2023 › 12 › 11 › why-if-type_checking
Why if TYPE_CHECKING?
December 11, 2023 - When CPython is building the program, how does it know which types the variables are if we don’t specify them? It doesn’t. All it knows is that the variables are objects. Everything in Python is an Object, until it’s not (i.e. it becomes a more specific type), that is when we specifically check it.
🌐
GeeksforGeeks
geeksforgeeks.org › python › type-isinstance-python
type and isinstance in Python - GeeksforGeeks
July 25, 2022 - The isinstance() function checks if the object (first argument) is an instance or subclass of the class info class (second argument). ... Return: true if the object is an instance or subclass of a class, or any element of the tuple false otherwise.
🌐
Real Python
realpython.com › python-type-checking
Python Type Checking (Guide) – Real Python
January 7, 2019 - The following dummy examples demonstrate that Python has dynamic typing: ... >>> if False: ... 1 + "two" # This line never runs, so no TypeError is raised ... else: ... 1 + 2 ... 3 >>> 1 + "two" # Now this is type checked, and a TypeError is raised TypeError: unsupported operand type(s) for +: 'int' and 'str'
Find elsewhere
🌐
Python
peps.python.org › pep-0781
PEP 781 – Make TYPE_CHECKING a built-in constant | peps.python.org
March 24, 2025 - This PEP proposes adding a new ... Python code with type annotations. It is evaluated as True when the code is being analyzed by a static type checker, and as False during normal runtime......
🌐
Hacker News
news.ycombinator.com › item
Why if TYPE_CHECKING? | Hacker News
December 22, 2023 - from __future__ import annotations Then you will not get this error (NameError: name 'Sequence' is not defined) because it will not need the reference to `Sequence` for the annotation but the annotation is simply a string · Using `if TYPE_CHECKING` is also useful when you want to speed up ...
🌐
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
Learn Python data types and how to check them using `type()` and `isinstance()`. Explore type conversion techniques with practical examples.
🌐
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 - Type checkers help ensure that you’re using variables and functions in your code correctly. With mypy, add type hints (PEP 484) to your Python programs, and mypy will warn you when you use those types incorrectly.
Top answer
1 of 1
37

Does the process of "type checking" mean code is not executed?

Yes, exactly. The type checker never executes your code: instead, it analyzes it. Type checkers are implemented in pretty much the same way compilers are implemented, minus the "generate bytecode/assembly/machine code" step.

This means your type checker has more strategies available for resolving import cycles (or cycles of any kind) than the Python interpreter will have during runtime since it doesn't need to try blindly importing modules.

For example, what mypy does is basically start by analyzing your code module-by-module, keeping track of each new class/new type that's being defined. During this process, if mypy sees a type hint using a type that hasn't been defined yet, substitute it with a placeholder type.

Once we've finished checking all the modules, check and see if there are still any placeholder types floating around. If so, try re-analyzing the code using the type definitions we've collected so far, replacing any placeholders when possible. We rinse and repeat until there are either no more placeholders or we've iterated too many times.

After that point, mypy assumes any remaining placeholders are just invalid types and reports an error.


In contrast, the Python interpreter doesn't have the luxury of being able to repeatedly re-analyze modules like this. It needs to run each module it sees, and repeatedly re-running modules could break some user code/user expectations.

Similarly, the Python interpreter doesn't have the luxury of being able to just swap around the order in which we analyze modules. In contrast, mypy can theoretically analyze your modules in any arbitrary order ignoring what imports what -- the only catch is that it'll just be super inefficient since we'd need lots of iterations to reach fixpoint.

(So instead, mypy uses your imports as suggestions to decide in which order to analyze modules. For example, if module A directly imports module B, we probably want to analyze B first. But if A imports B behind if TYPE_CHECKING, it's probably fine to relax the ordering if it'll help us break a cycle.)

🌐
TestDriven.io
testdriven.io › blog › python-type-checking
Python Type Checking | TestDriven.io
December 1, 2023 - In this article, we'll look at what type hints are and how they can benefit you. We'll also dive into how you can use Python's type system for static type checking with mypy and runtime type checking with pydantic, marshmallow, and typeguard.
🌐
Switowski
switowski.com › blog › type-vs-isinstance
type() vs. isinstance()
October 15, 2020 - Python is a dynamically typed language. A variable, initially created as a string, can be later reassigned to an integer or a float. And the interpreter won't complain: name = "Sebastian" # Dynamically typed language lets you do this: name = 42 name = None name = Exception() It's quite common to see code that checks variable's type.
🌐
Scientific Python Development
learn.scientific-python.org › development › guides › mypy
Static type checking - Scientific Python Development Guide
You may have code that runs rarely, that requires remote resources, that is slow, etc. All those can be checked by MyPy. It also keeps you (too?) truthful in your types. There are three ways to add types. They can be inline as annotations. Best for Python 3 code, usually.
🌐
Medium
medium.com › @k.a.fedorov › type-annotations-and-circular-imports-0a8014cd243b
Type Annotations and circular imports | by Kirill Fedorov | Medium
October 23, 2024 - To mitigate these issues, Python offers two powerful tools: using if TYPE_CHECKING from the typing module and the from __future__ import annotations statement.
🌐
GitHub
github.com › python › mypy › issues › 16587
TYPE_CHECKING only imports should trigger errors on non-annotation usage · Issue #16587 · python/mypy
November 29, 2023 - Bug Report this should warn for all non-annotation usages of FunctionType from typing import TYPE_CHECKING, cast if TYPE_CHECKING: from types import FunctionType def testit(func: FunctionType) -> None: assert isinstance(func, FunctionTyp...
Author: python
🌐
Python
typing.python.org › en › latest › spec › directives.html
Type checker directives — typing documentation
For such situations the typing module defines a constant, TYPE_CHECKING, that is considered True during type checking (or other static analysis) but False at runtime. Example: import typing if typing.TYPE_CHECKING: import expensive_mod def a_func(arg: 'expensive_mod.SomeClass') -> None: a_var: ...
🌐
Reddit
reddit.com › r/python › how to use type checking dynamically
r/Python on Reddit: How to use type checking dynamically
May 21, 2025 -

I have a set of classes and functions that perform analysis on pandas series. It is meant to be able to plug in new analysis, that takes a dictionary of "required" pre-computed values, and each analysis "provides" a dictionary. This way I don't ahve to recompute the same values over and over... and I can arrange the analysis objects into a DAG, I can also tell before execution if there are required values that aren't provided.

class SometimesProvides(ColAnalysis):
    provides_defaults = {'conditional_on_dtype':'xcvz'}
    requires_summary = []
    
    @staticmethod
    def series_summary(ser, _sample_ser):
        import pandas as pd
        is_numeric = pd.api.types.is_numeric_dtype(ser)
        if is_numeric:
            return dict(conditional_on_dtype=True)
        return {}

class DumbTableHints(ColAnalysis):
    provides_defaults = {
        'is_numeric':False, 'is_integer':False, 'histogram':[]}

    requires_summary = ['conditional_on_dtype']

    
    @staticmethod
    def computed_summary(summary_dict):
        return {'is_numeric':True,
                'is_integer': summary_dict['conditional_on_dtype'],
                'histogram': []}
sdf3, errs = produce_series_df(
    test_df, order_analysis(DumbTableHints, SometimesProvides))

That's a bit of a contrived example, but it should be enough to understand.

I understand how I can provide hinting for SometimesProvides.provides_defaults, and how I could verify that SometimesProvides.series_summary returns that type.

I don't know how, at runtime I can get a typing system to verify that the type of summary_dict going to DumbTableHints.summary_dict is as expected for that function.

This is all meant to be used interactively in the Jupyter notebook. So even if I could do this with mypy statically, that still wouldn't solve my problem. Also I think that the error messages from some Generic typing construction would be very hard to read in that case.

How would you all approach this?

🌐
Better Stack
betterstack.com › community › questions › what-is-best-way-to-check-for-type-in-python
What's the best way to check for type in Python? | Better Stack Community
The built-in type() function is the most commonly used method for checking the type of an object in Python. For example, type(my_variable) will return the type of my_variable. Additionally, you can use the isinstance() function to check if an ...
🌐
Reddit
reddit.com › r/python › to pycharm users: how are you type checking your code?
r/Python on Reddit: To PyCharm users: How are you type checking your code?
February 5, 2024 -

There are five major type checkers for Python users: Mypy (PSF?), Pyright (Microsoft), Pyre (Meta), Pytype (Google) and the built-in type checker of PyCharm (JetBrains).

According to pypistats.org, Mypy is the most downloaded last month and most popular overall:

  • Mypy: 20.4M

  • Pyright: 1.5M, albeit just a CLI wrapper.

  • Pytype: 632K

  • Pyre: 600, and this is not a typo. I guess it is just installed indirectly?

These stats may not reflect the actual usage. I have no experience with Pyre and Pytype and have rarely, if ever, seen anyone using these two. For VSCode users, the go-to extension is Pylance, which ships with Pyright and has 84M installs thus far. Among the two Mypy competitors of it, one is made by Microsoft (127K installs) and one independent (172K installs). The Python Developer Survey 2022 by JetBrains shows that the number of users who use PyCharm as their primary IDE for Python programming is 29%, second only to VSCode (37%). The annual report of the same year says JetBrains have 15.9M users, but the number of PyCharm users or downloads are not mentioned. One popular and currently the only working Mypy plugin has mixed reviews.

Personally, I think Pyright is the best type checker. It has support for latest feature, doesn't choke on WIP code and the maintainers are very responsive. Mypy is not as good, but is quite decent. On the contrary, PyCharm's type checker has many major problems. It is either too lenient or just fails to infer the right types most of the times.

PyCharm users, how do you or your team type check your code? Do you use one or multiple of the first four type checkers? If so, is it via the CLI or a plugin? Do you just use whatever people around you use? Or do you don't care about type hinting at all?