[Python] How to mark a class as abstract in python (no abstract methods and in a mypy...

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

  1. Stack

    Stack Membro Participativo

    I'm trying to make it impossible to instantiate a class directly, without it having any unimplemented abstract methods.

    Based on other solutions online, a class should have something along the lines of:

    class Example:
    def __new__(cls,*args,**kwargs):
    if cls is Example:
    raise TypeError("...")
    return super().__new__(cls,*args,**kwargs)


    I'm trying to move this snippet to a separate place such that each such class does not have to repeat this code.

    C = TypeVar("C")
    def abstract(cls:Type[C])->Type[C]:
    class Abstract(cls):
    def __new__(cls, *args:Any, **kwargs:Any)->"Abstract":
    if cls is Abstract:
    msg = "Abstract class {} cannot be instantiated".format(cls.__name__)
    raise TypeError(msg)
    return cast( Abstract, super().__new__(*args,**kwargs) )

    return Abstract


    This is my attempt and might be incorrect

    But mypy complains:


    error: Invalid base class "cls"
    ​

    How can I have some reusable way (such as a decorator) to achieve what I want whilst passing mypy --strict?

    Context:

    This is in the context of a pyside6 application where I'm subclassing QEvent, to have some additional extra properties. The base class defining these properties (getters) has a default implementation, yet I would like to prevent it from being initialized directly as it is not (and should not) be registered to the Qt event system. (I have a couple more such classes with different default values for convenience)

    Continue reading...

Compartilhe esta Página