像写 shell 一样写 Python

2017-01-21 01:38:06 +08:00
 czheo
from functools import partial

ret = None

class pipe:
    def __init__(self, data):
        self.data = data

    def __or__(self, right):
        if right is ret:
            return self.data
        elif isinstance(right, tuple):
            return pipe(partial(*right)(self.data))
        else:
            return pipe(right(self.data))

# with partial function
pipe(10) | range | partial(map, lambda x: x ** 2) | list | print
# simplify partial function
pipe(10) | range | (map, lambda x: x ** 2) | list | print
# assign return value to x
x = pipe(10) | range | (map, lambda x: x ** 2) | list | ret

另外两个成果:

https://github.com/czheo/czheo.github.io/issues/9

https://github.com/czheo/czheo.github.io/issues/10

3283 次点击
所在节点    Python
7 条回复
Sequencer
2017-01-21 01:46:50 +08:00
想像写 python 一样写 shell 才是需求啊...
czheo
2017-01-21 02:01:01 +08:00
@Sequencer Just for fun. 再来一个例子:
···
from itertools import groupby
{k: list(v) for k, v in pipe([4,3,1,3,4,2,1,9]) | sorted | groupby | ret}
## {1: [1, 1], 2: [2], 3: [3, 3], 4: [4, 4], 9: [9]}
···
itfanr
2017-01-21 08:24:11 +08:00
@Sequencer shellpy
freestyle
2017-01-21 19:36:57 +08:00
重载 or 操作符 可以可以
mingyun
2017-01-21 23:33:24 +08:00
@Sequencer 赞同
franklinyu
2017-01-22 16:09:46 +08:00
@itfanr 你說的 shellpy 能改環境變量麼?
itfanr
2017-01-22 22:48:47 +08:00
@franklinyu 自己试试呗

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/335984

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX