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 <rep...@bugs.python.org> <http://bugs.python.org/issue20516> _______________________________________ _______________________________________________ Python-bugs-list mailing list Unsubscribe: https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com