[Python] How do I formalize a repeated relationship among disjoint groups of classes in python?

Discussão em 'Python' iniciado por Stack, Abril 10, 2025.

  1. Stack

    Stack Membro Participativo

    I have Python code that has the following shape to it:

    from dataclasses import dataclass


    @dataclass
    class Foo_Data:
    foo: int


    class Foo_Processor:
    def process(self, data: Foo_Data): ...


    class Foo_Loader:
    def load(self, file_path: str) -> Foo_Data: ...

    #----------------------------------------------------------------

    @dataclass
    class Bar_Data:
    bar: str


    class Bar_Processor:
    def process(self, data: Bar_Data): ...


    class Bar_Loader:
    def load(self, file_path: str) -> Bar_Data: ...


    I have several instances of this sort of Data/Processor/Loader setup, and the classes all have the same method signatures modulo the specific class family (Foo, Bar, etc.). Is there a pythonic way of formalizing this relationship among classes to enforce a similar structure if I decide to create a Spam_Data, Spam_Processor, and Spam_Loader family of classes? For instance, I want something to enforce that Spam_Processor has a process method which takes an argument of type Spam_Data. Is there a way of achieving this standardization somehow with abstract classes, generic types, or some other structure?

    I tried using abstract classes, but mypy correctly points out that having all *_Data classes be subclasses of an abstract Data class and similarly having all *_Processor classes be subclasses of an abstract Processor class violates the Liskov substitution principle, since each processor is only designed for its respective Data class (i.e., Foo_Processor can't process Bar_Data, but one would expect that it could if these classes have superclasses Processor and Data which are compatible in this way).

    Continue reading...

Compartilhe esta Página