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

Python 协程, 我这样写有没有问题, 通过字符串调用函数

  •  
  •   jin7 · 2020-04-22 18:59:34 +08:00 · 2027 次点击
    这是一个创建于 1459 天前的主题,其中的信息可能已经有所发展或是发生改变。
    import asyncio
    
    
    async def do_foo(what):
        return what
    
    
    async def do_bar(what):
        return what
    
    
    async def main(param):
        result = asyncio.gather(do_foo(param), do_bar(param))
        await result
        print(result.result())
    
    
    asyncio.run(main('123'))
    
    
    # 我这样写有没有问题, 通过字符串调用函数
    async def question(param):
        coros = []
        funs = ['do_foo', 'do_bar']
        for fun in funs:
            coros.append(globals()[fun](param))
        result = asyncio.gather(*coros)
        await result
        print(result.result())
    
    
    asyncio.run(question('123'))
    
    7 条回复    2020-04-28 10:58:43 +08:00
    ClericPy
        1
    ClericPy  
       2020-04-22 19:05:25 +08:00   ❤️ 1
    前期没有大问题, 后期可能会有小问题

    从设计角度说, 可以搞一个类专门放方法, 然后使用的时候, getattr(obj, 'string')()
    ClericPy
        2
    ClericPy  
       2020-04-22 19:07:48 +08:00
    看起来像策略模式
    black11black
        3
    black11black  
       2020-04-22 19:11:33 +08:00   ❤️ 1
    搞封装不是问题,问题一个是污染全局变量,第二是有些封装方式不适合高可用环境,比如 getattr,还有你的 globals,根据需求自己选实现方法吧。
    ClericPy
        4
    ClericPy  
       2020-04-22 19:12:54 +08:00
    上面口误, 看了下代码好像是责任链... 溜了散步去了
    jin7
        5
    jin7  
    OP
       2020-04-24 10:29:27 +08:00
    搞明白我类似代码的 bug 了
    aaronhua
        6
    aaronhua  
       2020-04-27 21:36:21 +08:00
    我也是这样搞的,只在入口的地方,通过读取配置调用函数。主要问题是调用不够直观,才一两个人写的项目这个问题不大。
    jin7
        7
    jin7  
    OP
       2020-04-28 10:58:43 +08:00
    @aaronhua #6 好的咯
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2619 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 15:21 · PVG 23:21 · LAX 08:21 · JFK 11:21
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.