Piping in Python

mtwtkman - Jul 28 '20 - - Dev Community

Piping of shell likes cat foo | sort | uniq | wc -l is very simple, clear and fun.
Python gives us the way to implement this piping idiom by overriding special method.

All you needs are only the special method __ror__ like below.

class Pipable:
    def __init__(self, cmd):
        if callable(cmd):
            self.cmd = cmd
        else:
            raise ValueError

    def __ror__(self, other):
        return self.cmd(other)

    def __call__(self, *args):
        return self.cmd(*args)

OK, use it.

import os


def read_file(f):
    with open(f) as fd:
        return fd.read()

p1 = Pipable(read_file)
p2 = Pipable(lambda x: x.upper())
p3 = Pipable(lambda x: '-'.join(x))

f = 'foo.txt'
with open(f, 'w') as fd:
    fd.write('meow')
assert p1(f) == 'meow'
assert p1(f) | p2 == 'MEOW'
assert p1(f) | p2 | p3 == 'M-E-O-W'
os.remove(f)

Now you have the simple magic of function composition in Python!

You can override other operation symbols via corresponded special methods, so let's explore there.

. . . . . . .