[Python] Combine `Protocol` with base class requirement, type intersection

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

  1. Stack

    Stack Membro Participativo

    I want to express some type which inherits from nn.Module. I would do so as follows:

    ModuleType = TypeVar("ModuleType", bound=nn.Module)


    At the same time, I want to express that it has an __init__ function of a certain format. I would do so using Protocol, as follows:

    class InitWithCfgProtocol(Protocol):
    def __init__(self, cfg: dict):
    ...


    Now, how can I express a type which has both properties? Basically an intersection of ModuleType and InitWithCfgProtocol. Is this possible?

    Further, how can this again be expressed as a TypeVar, such that I can use it as a template argument for a Generic? Like this:

    ModuleInitWithCfgType = TypeVar(...) # ?


    @dataclass
    class ModuleFactory(Generic[ModuleInitWithCfgType]):
    module_class: Type[ModuleInitWithCfgType]

    def make(self, cfg: dict) -> ModuleInitWithCfgType:
    return self.module_class(cfg)


    In this example, I want to have proper checks (via PyCharm, mypy or similar) for:

    • self.module_class(cfg) - it should warn when I pass wrong arguments
    • factory = ModuleFactory(MyModule) - it should warn when I pass a wrong MyModule class

    Continue reading...

Compartilhe esta Página