Search code examples
pythongenericspython-typing

Is it possible to check the exact type of parameterized generics at runtime in Python ^3.10?


I have some custom type definitions using parameterized generics. Now at runtime, I want to find out if a variable does have this custom type. Here's a minimal example:

>>> from collections.abc import Callable
>>> MyType = Callable[[int], int]
>>> my_fun: MyType = lambda x: x
>>> isinstance(my_fun, MyType)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: isinstance() argument 2 cannot be a parameterized generic

Is there any way to achieve this currently?


Solution

  • Not sure, what you are trying to achieve with this, but assuming the annotation is done in module scope and you are dealing with the same variable name, you can always just refer to the __annotations__ dictionary and utilize get_args/get_origin:

    from collections.abc import Callable
    from typing import get_args, get_origin
    
    
    MyType = Callable[[int], int]
    my_fun: MyType = lambda x: x
    
    my_fun_annotation = __annotations__["my_fun"]
    
    assert get_origin(my_fun_annotation) is Callable
    assert get_args(my_fun_annotation) == ([int], int)
    

    But you should probably explain a bit more, why you think you need to do this because it seems like an XY Problem.