This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

Author neologix
Recipients bquinlan, glangford, neologix, pitrou, vstinner
Date 2014-02-08.13:16:13
SpamBayes Score -1.0
Marked as misclassified Yes
Message-id <CAH_1eM1-X20=Uaf9hvzsOkgfZDHB+bT6HZ3LinV-vqUmR7c5xA@mail.gmail.com>
In-reply-to <1391862777.7.0.435411143425.issue20516@psf.upfronthosting.co.za>
Content
> 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.
History
Date User Action Args
2014-02-08 13:16:13neologixsetrecipients: + neologix, bquinlan, pitrou, vstinner, glangford
2014-02-08 13:16:13neologixlinkissue20516 messages
2014-02-08 13:16:13neologixcreate