Python Pipes
I’ve always wanted to have a way to build data processing pipelines in Python using pipes, like this range(10) | F(is_odd) | P(lambda x: x * 2), instead of functions and generators and maps and loops. So I’ve tried … The idea is pretty simple: let’s create a class with implemented OR and ROR operators, the pipes. def __or__(self, other): other.source = self return other def __ror__(self, other): self.source = ( iter(other) if not isinstance(other, (str, bytes)) and hasattr(other, "__iter__") else other ) return self The tricky part was implementation of __next__ since I wanted it to be a lazy operation. After a few trials and errors I’ve ended up with a pretty simple approach where the wrapping class implementing the pipe will call next to its source, added by OR or ROR, apply a transformation and then return the result of the transformation. ...