[Python] How can I call a @staticmethod on a generic type argument (defined with TypeVar)?...

Discussão em 'Python' iniciado por Stack, Janeiro 26, 2025.

  1. Stack

    Stack Membro Participativo

    I have a generic class in which I would like to call a static method on the type argument, but if I naively try it like in the following example, I get an error because the identifier representing the type is actually an instance of TypeVar which does not have this attribute:

    from abc import ABC, abstractmethod
    from typing import Generic, TypeVar

    class MyInterface(ABC):
    @staticmethod
    @abstractmethod
    def default() -> int: ...

    class SubclassA(MyInterface):
    @staticmethod
    def default() -> int:
    return 0

    class SubclassB(MyInterface):
    @staticmethod
    def default() -> int:
    return 1

    SomeSubclass = TypeVar('SomeSubclass', bound=MyInterface)

    class InterfaceContainer(Generic[SomeSubclass]):
    def check_if_default(self, value: int) -> bool:
    return value == SomeSubclass.default() # AttributeError: 'TypeVar' object has no attribute 'default'

    # optional, shows runtime error even without static type checking:
    container = InterfaceContainer[SubclassA]()
    container.check_if_default(42)


    How can I access attributes of the type specified as argument?

    How to access the type arguments of typing.Generic? is a related question where I learned how to access the argument given the type InterfaceContainer[SubclassA] (e.g., via __args__ since Python 3.6+), but the instance container does not have __args__, and type(container) or cls in a @classmethod just give me the generic type InterfaceContainer without its argument.

    I wonder if instances of a generic class lose their type argument information completely, maybe because it is only meant for type checking?

    Continue reading...

Compartilhe esta Página