<div dir="ltr">Hi everyone,<div><br></div><div>Here is a simplification of a problem that's been happening in my code:</div><div><br></div><div><blockquote style="margin:0px 0px 0px 40px;border:none;padding:0px"><div><div>import contextlib</div><div><br></div><div>@contextlib.contextmanager</div><div>def f():</div><div>    print('1')</div><div>    try:</div><div>        yield</div><div>    finally:</div><div>        print('2')</div><div>        </div></div></blockquote><blockquote style="margin:0px 0px 0px 40px;border:none;padding:0px">g = f()<br>g.__enter__()<br><br></blockquote><div><br></div>This code prints 1 and then 2, not just 1 like you might expect. This is because when the generator is garbage-collected, it gets `GeneratorExit` sent to it. </div><div><br></div><div>This has been a problem in my code since in some instances, I tell a context manager not to do its `__exit__` function. (I do this by using `ExitStack.pop_all()`. However the `__exit__` is still called here.</div><div><br></div><div>I worked around this problem by adding `except GeneratorExit: raise` in my context manager, but that's an ugly solution.</div><div><br></div><div>Do you think that something could be done so I won't have to add  `except GeneratorExit: raise` to each context manager to get the desired behavior?</div><div><br></div><div><br></div><div>Thanks,</div><div>Ram.</div></div>