I have a generic class like
from typing import Generic, TypeVar, List
T = TypeVar('T')
@my_decorator
class Foo(Generic[T]):
pass
f: Foo[int] = Foo()
g: Foo[List[float]] = Foo()
Is there a clean way to get the type annotations of the constructor call Foo[int], Foo[List[float]] in the decorator? I want to do some type checking at runtime.
I'm able do access the constructor call of Foo via the decorator and I even get the code line f: Foo[int] = Foo() of the constructor call by using inspect.stack() and inspect.getsource(my_frame) in a very unpretty way. Then I'm able to get Foo[int] by some string manipulation.
Beside that this is a very dirty way of doing it, it only get the type as a string. But I need the actually type. In this example I could use eval() to "parse" the string and convert it into a type. But that doesn't work for custom classes, like in this example:
from typing import Generic, TypeVar, List
T = TypeVar('T')
class Bar:
pass
@my_decorator
class Foo(Generic[T]):
pass
h: Foo[List[Bar]] = Foo()
In this case I cannot use eval() because I have no idea how I can get the proper context.
I like to get something like my_file.Foo[typing.List[my_file.Bar]] which would allow me to do type checking at runtime.
So is there any clean way of doing it? Or is there at least a (dirty) way to get the correct context for eval() to "parse" the string?