Skip to main content

A simple piping syntax

Project description

A simple syntax for piping in Python.

Compare:

from bookends import _
from toolz.curried import map

l = _| [1, 2, 3] | map(lambda n: n*2) |_   # [2, 4, 6]
l = map(lambda n: n*2, [1, 2, 3])

l = [n*2 for n in [1, 2, 3]]

l = []
for n in [1, 2, 3]:
    l.append(n*2)

For an extended comparison, see example.py.

For similar tools, see:

Note: for multiline usage, wrap the expression in parens.

import csv
from StringIO import StringIO

(_| '40,5,10\n20,6,9\n41,10,10\n'
  | StringIO
  | csv.reader
  | sorted
  |_)

# [['20', '6', '9'], ['40', '5', '10'], ['41', '10', '10']]

Wrap lone lambdas in parens as well.

(_| ['addition', 'multiplication']
  | (lambda l: l + ['exponentiation', 'tetration'])
  | ', '.join
  |_)

# 'addition, multiplication, exponentiation, tetration'

You’ll need to use partial or curried functions.

from functools import partial
from toolz.curried import drop

(_| ['ca', 'tx', 'ny']
  | partial(map, lambda state: state.upper())
  | drop(1)
  | list
  |_)

# ['TX', 'NY']

Plays nice with Kachayev’s _.

from fn import _ as __

_| [1, 2, 3] | __ + [4, 5] |_

# [1, 2, 3, 4, 5]

Here’s the entire source:

class Bookend():
    def __or__(self, operand):
        return Piped(operand)


class Piped():
    def __init__(self, operand):
        self.operand = operand

    def __or__(self, f):
        if isinstance(f, Bookend):
            return self.operand
        else:
            return Piped(f(self.operand))


_ = Bookend()

Contact: @bzrry.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

bookends-0.0.1.tar.gz (2.3 kB view hashes)

Uploaded Source

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page