It's tricky to statically type a "pipe" function in Python
I wanted a type-safe pipe utility to help me write Python in a more functional style, but unfortunately toolz.pipe and returns.pipelines.flow both output Any.
Happily, it turns out creating your own pipe mechanism is a one-liner:
Which you can reuse by wrapping it in a function:
And calling it with any number of functions:
So you can stop thinking up names for throwaway variables like these:
While the pipe function above with the Callable[[A], A] type hint works fine if every function in the pipeline outputs the same type (A), the example I showed above doesn’t actually work out very well! Mypy notices that some of the functions (int and float) output a different type than we started with (str), so we aren’t actually passing A all the way through.
After trying a number of workarounds (and getting some good advice on Reddit), I learned that you can either tell Mypy what’s going on by painstakingly articulating every possible overload: