推荐学习书目
› 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
kzing
V2EX  ›  Python

Python 中如何利用 decorator 实现异步?

  •  
  •   kzing · Aug 10, 2014 · 3941 views
    This topic created in 4443 days ago, the information mentioned may be changed or developed.
    在 coolshell [1]看到一段代码, 非常酷:

    def async(fn):
    @wraps(fn)
    def async_func(*args, **kwargs):
    _func = Thread(target=fn, args=args, kwargs=kwargs)
    _func.start()
    return _func
    return async_func

    @async
    def print_data():
    pass

    def main():
    print_data()

    可以看到在用 async 装饰之后, 在 main 中是异步调用 print_data.

    1. 这是什么原理呢?
    2. 还有更强大的方法实现异步吗?


    ---------
    [1]: http://coolshell.cn/articles/11265.html
    8 replies  •  2014-08-10 20:50:05 +08:00
    kier
        1
    kier  
       Aug 10, 2014
    这个不就是将函数放到单独的线程执行么?
    async这个decorator只不过是吧线程的操作独立出来,就不用在每个function里面都去重复这段代码而已,没什么特别
    ddzz
        2
    ddzz  
       Aug 10, 2014
    要想酷,玩ruby
    bcxx
        3
    bcxx  
       Aug 10, 2014
    最直接的方法就是用楼主你提到的方案,把要执行的操作放到另外一个 thread 里面做。

    用 decorator 的意图就和 @kier 说的一样,为了复用而已(不要把这个模式和要做的东西混淆噢)


    然后想更舒服一点的还可以用 work queue (例如 rq 之流)、gevent spawn 之类的。
    hahastudio
        4
    hahastudio  
       Aug 10, 2014   ❤️ 2
    Python 的 decorator 非常强大,你可以给函数包装出各种附加功能,比如这里有一堆的样例= =
    https://wiki.python.org/moin/PythonDecoratorLibrary
    zenliver
        5
    zenliver  
       Aug 10, 2014
    看看tornado coroutine的实现呗
    P9
        6
    P9  
       Aug 10, 2014
    Python cookbook 第三版 function --- 7.11. Inlining Callback Functions

    https://glyph.twistedmatrix.com/2014/02/unyielding.html
    《Don't use threads》 此文很长,tornado coroutine 的实现是学习了
    https://twistedmatrix.com/documents/13.1.0/api/twisted.internet.defer.html#inlineCallbacks
    clino
        7
    clino  
       Aug 10, 2014 via Android
    '还有更强大的方法实现异步吗?'
    觉得还是协程好,如gevent
    kzing
        8
    kzing  
    OP
       Aug 10, 2014
    @hahastudio
    @clino
    @zenliver
    @P9
    谢谢: )
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   5323 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 32ms · UTC 05:46 · PVG 13:46 · LAX 22:46 · JFK 01:46
    ♥ Do have faith in what you're doing.