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

前端 未结 5 1260
轻奢々
轻奢々 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:48

    That would be how I expected things to work. Yes, the block will not release its resources until it completes, so in that sense the resource has escaped it's lexical nesting. However but this is no different to making a function call that tried to use the same resource within a with block - nothing helps you in the case where the block has not yet terminated, for whatever reason. It's not really anything specific to generators.

    One thing that might be worth worrying about though is the behaviour if the generator is never resumed. I would have expected the with block to act like a finally block and call the __exit__ part on termination, but that doesn't seem to be the case.

提交回复
热议问题