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

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

    Because yield can execute arbitrary code, I'd be very wary of holding a lock over a yield statement. You can get a similar effect in lots of other ways, though, including calling a method or functions which might be have been overridden or otherwise modified.

    Generators, however, are always (nearly always) "closed", either with an explicit close() call, or just by being garbage-collected. Closing a generator throws a GeneratorExit exception inside the generator and hence runs finally clauses, with statement cleanup, etc. You can catch the exception, but you must throw or exit the function (i.e. throw a StopIteration exception), rather than yield. It's probably poor practice to rely on the garbage collector to close the generator in cases like you've written, because that could happen later than you might want, and if someone calls sys._exit(), then your cleanup might not happen at all.

提交回复
热议问题