Friday, 20 May 2022

What is the best way to work with classes that subclass from Generic types?

Assume we are given a generic class definition such as:

from dataclasses import dataclass
from typing import TypeVar, Generic, List


T1 = TypeVar('T1')
T2 = TypeVar('T2')


@dataclass
class MyGenericClass(Generic[T1, T2]):
    val: T1
    results: List[T2]


@dataclass
class BaseClass:
    my_str: str


@dataclass
class MyTestClass(BaseClass, MyGenericClass[str, int]):
    ...

What is the best way to determine that MyTestClass is a Generic class - i.e. as opposed to a regular dataclass?

Also, does the typing module provide an easy way to resolve generic type (TypeVar) to concrete type relations in this case?

For ex. given results: List[T2] above, I want to understand that T2 in the context of MyTestClass would resolve to an int type.

Determine if class is Generic

Currently if I run set(vars(MyTestClass)) - set(vars(BaseClass)), I get the following result:

{'__parameters__', '__orig_bases__'}

However I'm wondering if typing provides an easy way to determine if a class is a Generic or sub-classes from a Generic class, such as for example typing.Dict.

So something to the effect of is_cls_generic() is what I'd be interested in.

Resolve TypeVar types

Currently, when I call typing.get_type_hints(MyTestClass), I get the following result:

{'val': ~T1, 'results': typing.List[~T2], 'my_str': <class 'str'>}

I am wondering if the typing module provides an easy way to resolve those TypeVar variables, so that the desired result would be:

{'val': str, 'results': typing.List[int], 'my_str': str}


from What is the best way to work with classes that subclass from Generic types?

No comments:

Post a Comment