outsmarting context managers with coroutines
burak.arslan at arskom.com.tr
Sat Dec 28 23:13:56 CET 2013
Have a look at the following code snippets:
output2: I can break out of outer context without closing the inner one
in Python 2
output3: Breaking out of outer context closes the inner one, but the
closing order is wrong.
output3-yf: With yield from, the closing order is fine but yield returns
None before throwing.
All of the above seem buggy in their own way. And actually, Python 2
seems to leak memory when generators and context managers are used this way.
Are these behaviours intentional? How much of it is
implementation-dependent? Are they documented somewhere? Neither PEP-342
nor PEP-380 talk about context managers and PEP-343 talks about
generators but not coroutines.
My humble opinion:
1) All three should behave in the exact same way.
2) Throwing into a generator should not yield None before throwing.
ps: I have:
$ python -V; python3 -V
More information about the Python-list