Say I have a Generic dataclass like the following:
from dataclasses import dataclass
from typing import TypeVar, Generic
T = TypeVar('T')
U = TypeVar('U')
@dataclass
class Class(Generic[T, U]):
foo: U
bar: T
IntStrClass = Class[int, str]
When we read the code you can see that for IntStrClass:
- the
Tlines up withint, which makes the type ofbaranint. - the
Ulines up withstr, which makes the type offooastr.
But how can I figure this out progamatically?
I've been playing around with the typing module, but can't see from the outputs how I would match them up. What I have is:
from typing import get_type_hints, get_origin, get_args
print("Class field types:", get_type_hints(get_origin(IntStrClass)))
print("Class generic args:", get_args(IntStrClass))
Class field types: {'foo': ~U, 'bar': ~T}
Class generic args: (<class 'int'>, <class 'str'>)
What I'm missing here is from the definition of Class, to determine that T -> int and U -> str. If I had this information, then I could infer the proper types of foo and bar.
Thanks in advance!