Search code examples
pythonpython-typing

TypeError: typing.Any cannot be used with isinstance()


I was wondering why Python's typing module does not support isinstance(<obj>, Any) and raises a TypeError. I would expect it to always return True. Is there a specific reason why it does not always return True?

  • The TypeError is raised here.
  • Example of the TypeError:
>>> from typing import Any
>>> isinstance(1, Any)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/peter/miniconda3/envs/prefect_utils/lib/python3.9/typing.py", line 338, in __instancecheck__
    raise TypeError(f"{self} cannot be used with isinstance()")
TypeError: typing.Any cannot be used with isinstance()

Solution

  • Most things in typing are not intended for runtime type checking. Most types cannot be sensibly checked dynamically, so typing avoids pretending it's possible.


    The Any type is not a proper type – it is compatible with any type in any usage. Depending on the use, it can be both the super and sub type of another type.
    Most prominently, Any supports all operations. Therefore, isinstance(x, Any) == True would mean that x supports all operations, regardless of x' concrete type. This is not sensible for most proper types.


    Consider for example checking an integer as an "instance of Any", which implies it supports slicing:

    x = 3
    if isinstance(x, Any):  # x supports any operation in this block
        print(x[:3])        # slicing is part of "all operations"