英文原文:http://dev-tricks.net/pipe-infix-syntax-for-python
翻译版本:http://blog.csdn.net/lanphaday/article/details/6287114
刚刚才发现的这东西,觉得挺有意思的,一个简单的例子是:
>>> from pipe import *
>>> [1, 2, 3, 4, 5] | add
15
复杂一点的,例如求Fibonacci数列前100项的和:
from pipe import *
def fib():
a, b = 1, 0
while True:
yield a
a, b = a + b, a
print enumerate(fib()) | take_while(lambda (i, x): i < 100) | select(lambda (i, x): x) | add
除了add之外,作者还实现了常见的方法,例如
select: 类似于 map
where: 类似于 filter,后者
sort/reverse/max/min/take/tail/skip ...
这个库在pypi里有:http://pypi.python.org/pypi/pipe
看了下核心实现非常简单,就是利用了 __ror__ 和 decorator:
class Pipe:
def __init__(self, function):
self.function = function
def __ror__(self, other):
return self.function(other)
def __call__(self, *args, **kwargs):
return Pipe(lambda x: self.function(x, *args, **kwargs))
@
Pipedef add(x):
return sum(x)