outsmarting context managers with coroutines

Burak Arslan burak.arslan at arskom.com.tr
Sat Dec 28 19:35:07 EST 2013


On 12/29/13 00:13, Burak Arslan wrote:
> Hi,
>
> Have a look at the following code snippets:
> https://gist.github.com/plq/8164035
>
> Observations:
>
> 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.

It doesn't, my mistake. Python 3 yield from case does the right thing, I
updated the gist. The other two cases still seem weird to me though. I
also added a possible fix for python 2 behaviour in a separate script,
though I'm not sure that the best way of implementing poor man's yield from.

Sorry for the noise.

Best,
Burak

> 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.
>
> Best,
> Burak
>
> ps: I have:
>
> $ python -V; python3 -V
> Python 2.7.5
> Python 3.3.2




More information about the Python-list mailing list