[issue20516] Concurrent.futures base concurrency improvement (with patch)

Charles-François Natali report at bugs.python.org
Sat Feb 8 14:16:13 CET 2014


Charles-François Natali added the comment:

> Note that the context manager will be called in this case to release the
lock before f is yielded to the caller.
>
> class MiniContext():
>     def __init__(self):
>         pass
>
>     def __enter__(self):
>         print('Hello')
>
>     def __exit__(self, *args):
>         print('Goodbye')
>
> def gen():
>         with MiniContext():
>                 yield 1
>
> print(next(gen()))
>
> prints:
>
> Hello
> Goodbye
> 1

Actually, I think what you're seeing here is the context manager being
garbage collected right after the call to next(), and therefore before the
call to print(), because no reference to it is kept. So __exit__() is
called right away.

But if you rewrite it like this:

"""
for e in gen():
    print(e)
"""

You see:
"""
Hello
1
Goodbye
"""

It would be suprising if __exit__() got called before exit of the syntactic
block, just imagine what would happen with the following code:
"""
def read_file(path):
    with open(path) as f:
        for line in f:
            yield line
"""

if the file was closed before yielding.

----------

_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue20516>
_______________________________________


More information about the Python-bugs-list mailing list