[Python] How do I type a generic subclass correctly?

Discussão em 'Python' iniciado por Stack, Março 20, 2025.

  1. Stack

    Stack Membro Participativo

    Here is some example code:

    I have my underlying generic object.

    T = TypeVar("T", str, int, bytes)


    class MyObj(Generic[T]):
    id: T


    and some implementations

    class MyObjImplInt(MyObj[int]): ...
    class MyObjImplStr(MyObj[str]): ...


    obj_int = MyObjImplInt()
    type(obj_int.id) # int

    obj_str = MyObjImplStr()
    type(obj_str.id) # str


    Now I have built a manager for these objects

    TObj = TypeVar("TObj", bound=MyObj)

    class MyObjMgr(Generic[TObj, T]):
    objs: list[TObj]

    def __init__(self, objs: list[TObj]):
    self.objs = objs

    def get_by_id(self, obj_id: T):
    return [e for e in self.objs if e.id == obj_id]


    class MyObjMgrInts(MyObjMgr[MyObjImplInt, int]): ...
    class MyObjMgrStrs(MyObjMgr[MyObjImplStr, str]): ...


    My issue is that I have to provide the type T for MyObjMgr(Generic[TObj, T]) in order to specify the id type of the underlying object. Is there a way to infer T from TObj[T]?

    i.e. just write this:

    class MyObjMgr2(Generic[TObj]):
    objs: list[TObj]

    def __init__(self, objs: list[TObj]):
    self.objs = objs

    def get_by_id(self, obj_id: T@TObj): # err here
    return [e for e in self.objs if e.id == obj_id]


    class MyObjMgr2Ints(MyObjMgr2[MyObjImplInt]): ...

    Continue reading...

Compartilhe esta Página