V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
czheo
V2EX  ›  Python

像写 shell 一样写 Python

  •  
  •   czheo ·
    czheo · 2017-01-21 01:38:06 +08:00 · 3261 次点击
    这是一个创建于 2623 天前的主题,其中的信息可能已经有所发展或是发生改变。
    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

    7 条回复    2017-01-22 22:48:47 +08:00
    Sequencer
        1
    Sequencer  
       2017-01-21 01:46:50 +08:00 via iPhone   ❤️ 2
    想像写 python 一样写 shell 才是需求啊...
    czheo
        2
    czheo  
    OP
       2017-01-21 02:01:01 +08:00   ❤️ 1
    @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
        3
    itfanr  
       2017-01-21 08:24:11 +08:00 via Android   ❤️ 1
    @Sequencer shellpy
    freestyle
        4
    freestyle  
       2017-01-21 19:36:57 +08:00
    重载 or 操作符 可以可以
    mingyun
        5
    mingyun  
       2017-01-21 23:33:24 +08:00
    @Sequencer 赞同
    franklinyu
        6
    franklinyu  
       2017-01-22 16:09:46 +08:00
    @itfanr 你說的 shellpy 能改環境變量麼?
    itfanr
        7
    itfanr  
       2017-01-22 22:48:47 +08:00 via Android
    @franklinyu 自己试试呗
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3059 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 28ms · UTC 12:49 · PVG 20:49 · LAX 05:49 · JFK 08:49
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.