py-op

Python operators for easier chaining


Keywords
functional, programming, operator, utility
License
MIT
Install
pip install py-op==0.1.0

Documentation

pyop

Mis-use python in a proper way. To install i would use

pip install -e .

so it’s easy to add more of these small functions later on.

O function

What it does is to wrap around a function such that one can do the following

from pyop import *

x = [1,2,3,4,5]
x // O(len) // O(print)

Output:

5

This is a pipe operation that the output is passed directly to the next. Similarly, @ is a mapping operation

x @ O(lambda x: x+1)

Output:

[2, 3, 4, 5, 6]
x // O(enumerate) @ O(lambda x: x[0]) // O(print)

Output:

[2, 3, 4, 5, 6]

You get the idea.

Useful built-in functions

I have made a number of these O functions and give them a name that often add a postfix _ (underscore) to the function name. This will make it easy to use and one don’t have to always add O in front. Let me illustrate some of them here.

First i have borrowed some basic lisp functions here

x // cdr_ // cdr_ // car_

Output:

3

This is equivalent to x // caddr_.

x // filter_(lambda x: x>2) // list_ // print_
[3, 4, 5]

The original function should be obvious (without _). I’ve also borrowed the _ function from fn package and have it available by default, in interactive environment like ipython notebook _ won’t work so one can use the alias it_ that i have made. With this the above function look like

x // filter_(it_>2) // list_ // print_ 

The output is the same as above.

x = [1,1,2,3,3,4,6,8,2,0]
x // reduce_(it_+it_)

Output:

30
x // topk_(3)

Output:

(8, 6, 4)

Note these functions wrap around functions in toolz.itertoolz which is also made availabe in the namespace.

x // partition_(3) // list_

Output:

[(1, 1, 2), (3, 3, 4), (6, 8, 2)]
x // partition_(3) // list_ @ car_

Output:

[1, 3, 6]

This is pure joy to play with. Enjoy!