DEV Community

mtwtkman
mtwtkman

Posted on

1 1

Piping in Python

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.

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (1)

Collapse
 
mellen profile image
Matt Ellen-Tsivintzeli

Would it work as well if you implement __or__ instead of __ror__?

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay