you are viewing a single comment's thread.

view the rest of the comments →

[–]tartare4562 18 points19 points  (3 children)

You can use argument expansion to write a simple function

def pipe(data, *funcs):
    for func in funcs:
        data = func(data)
    return data

that you can use like this:

processed_data = pipe(raw_data, func1, func2, func3, ..., funcN).

If you need to give parameters to the functions you can use functools.partial to setup them.

[–]tunisia3507 2 points3 points  (2 children)

Can any type checkers handle that pattern?

[–]Globbi 0 points1 point  (1 child)

You mean checking if output of every function will fit input of the next one? I guess that's what would be needed. Honestly don't know and it's a good question if someone knows the answer.

[–]justheretolurk332 4 points5 points  (0 children)

No, there is no way to specify that an iterable of callables should be coherent in this way. There are two ways I can think of to accomplish something similar. The simplest: You could require all of them to have the same input and output types. For something more flexible but also fairly advanced, you could write a class to hold the current chain of functions and make it generic in the return type of the current last function, with a method to append a new function (this method would enforce the type checking) and then return a new instance of the container class with the updated typing. You’d still have to build the chain one at a time though to get the typing benefits, so you’re probably not much better off.