Is it safe to yield from within a “with” block in Python (and why)?

前端 未结 5 1166
轻奢々
轻奢々 2021-01-31 02:29

The combination of coroutines and resource acquisition seems like it could have some unintended (or unintuitive) consequences.

The basic question is whether or not somet

5条回答
  •  春和景丽
    2021-01-31 02:54

    I don't think there is a real conflict. You just have to be aware that the generator is just like any other object that holds resources, so it is the creator's responsibility to make sure it is properly finalized (and to avoid conflicts/deadlock with the resources held by the object). The only (minor) problem I see here is that generators don't implement the context management protocol (at least as of Python 2.5), so you cannot just:

    with coroutine() as cr:
      doSomething(cr)
    

    but instead have to:

    cr = coroutine()
    try:
      doSomething(cr)
    finally:
      cr.close()
    

    The garbage collector does the close() anyway, but it's bad practice to rely on that for freeing resources.

提交回复
热议问题