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
kzing
V2EX  ›  Python

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

  •  
  •   kzing · 2014-08-10 10:50:15 +08:00 · 3131 次点击
    这是一个创建于 3566 天前的主题,其中的信息可能已经有所发展或是发生改变。
    在 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 条回复    2014-08-10 20:50:05 +08:00
    kier
        1
    kier  
       2014-08-10 10:56:25 +08:00
    这个不就是将函数放到单独的线程执行么?
    async这个decorator只不过是吧线程的操作独立出来,就不用在每个function里面都去重复这段代码而已,没什么特别
    ddzz
        2
    ddzz  
       2014-08-10 11:47:13 +08:00
    要想酷,玩ruby
    bcxx
        3
    bcxx  
       2014-08-10 11:51:28 +08:00
    最直接的方法就是用楼主你提到的方案,把要执行的操作放到另外一个 thread 里面做。

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


    然后想更舒服一点的还可以用 work queue (例如 rq 之流)、gevent spawn 之类的。
    hahastudio
        4
    hahastudio  
       2014-08-10 11:55:54 +08:00   ❤️ 2
    Python 的 decorator 非常强大,你可以给函数包装出各种附加功能,比如这里有一堆的样例= =
    https://wiki.python.org/moin/PythonDecoratorLibrary
    zenliver
        5
    zenliver  
       2014-08-10 13:46:28 +08:00
    看看tornado coroutine的实现呗
    P9
        6
    P9  
       2014-08-10 14:21:13 +08:00
    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  
       2014-08-10 14:24:22 +08:00 via Android
    '还有更强大的方法实现异步吗?'
    觉得还是协程好,如gevent
    kzing
        8
    kzing  
    OP
       2014-08-10 20:50:05 +08:00
    @hahastudio
    @clino
    @zenliver
    @P9
    谢谢: )
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   6230 人在线   最高记录 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 06:23 · PVG 14:23 · LAX 23:23 · JFK 02:23
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.