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

yield 空是什么用法?

  •  
  •   shyrock · 2021-03-26 17:58:24 +08:00 · 960 次点击
    这是一个创建于 1098 天前的主题,其中的信息可能已经有所发展或是发生改变。

    关于 yield 的使用,网上能搜到的都是生成器的用法,都以 yield n 的形式返回一个值。 但是我在 odoo 中看到一段代码:

        @classmethod
        @contextmanager
        def manage(cls):
            """ Context manager for a set of environments. """
            if hasattr(cls._local, 'environments'):
                yield
            else:
                try:
                    cls._local.environments = Environments()
                    yield
                finally:
                    release_local(cls._local)
    

    调用语法:

            with odoo.api.Environment.manage():
                with registry.cursor() as cr:
                    odoo.tools.trans_export(config["language"],
                        config["translate_modules"] or ["all"], buf, fileformat, cr)
    

    有大佬能指点一下这个 yield 什么用处吗?

    SjwNo1
        1
    SjwNo1  
       2021-03-26 22:32:00 +08:00
    因为是 contextmanager,所以 yield 之前的部分相当于__enter__, 之后的逻辑相当于__exit__,这里 yield 返回 None 是因为上下文不需要 as obj
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   4670 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 34ms · UTC 01:08 · PVG 09:08 · LAX 18:08 · JFK 21:08
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.