On 12 May 2015 at 19:08, Peter Otten <__pete...@web.de> wrote: >> >> A generator cannot guarantee that execution continues after a yield so >> any context manager used around a yield is dependent on __del__. I >> think a good rule of thumb is "don't yield from a with block". > > Uh-oh, I am afraid I did this quite a few times. Most instances seem to be > context managers though. Is something like > > @contextmanager > def my_open(filename): > if filename == "-": > yield sys.stdin > else: > with open(filename) as f: > yield f > > > OK?
Yeah that's fine. A generator cannot guarantee that execution continues after a yield since the controller of the generator decides that. In this case the only controller that has access to your generator is the contextmanager decorator which guarantees to do next(gen) or gen.throw(). You can see the code for that here: https://hg.python.org/cpython/file/4b5461dcd190/Lib/contextlib.py#l63 -- Oscar _______________________________________________ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor