[Python] How do I correctly type a processing pipeline in Python

Discussão em 'Python' iniciado por Stack, Junho 7, 2025.

  1. Stack

    Stack Membro Participativo

    I am proposing here a typing challenege. I wonder if anyone has a valid solution since I haven't been able to myself. The problem is as follows:

    We define a class

    class Component[TInput, TOuput]: ...


    the implementation is not important, just that it is parameterised by two types, TInput and TOutput.

    We then define a class which processes components. This class takes in a tuple/sequence/iterable/whatever of Components, as follows:

    class ComponentProcessor[...]:

    def __init__(self, components : tuple[...]): ...


    It may be parameterised by some types, that's up to you.

    The constraint is that for all components which are passed in, the output type TOutput of the n'th component must match the input type TInput of the (n + 1)'th component. This should wrap around such that the TOutput of the last component in the chain is equal to TInput of the first component in the chain.

    Let me give a valid example:

    a = Component[int, str](...)
    b = Component[str, complex](...)
    c = Component[complex, int](...)

    processor = ComponentProcessor((a, b, c))


    And an invalid example:

    a = Component[int, float](...)
    b = Component[str, complex](...)
    c = Component[complex, int](...)

    processor = ComponentProcessor((a, b, c))


    which should yield an error since the output type of a is float which does not match the input type of b which is str.

    My typing knowledge is so-so, so perhaps there are simple ways to achieve this using existing constructs, or perhaps it requires some creativity. I look forward to seeing any solutions!

    Continue reading...

Compartilhe esta Página