[Tutor] reading lines from a list of files

Oscar Benjamin oscar.j.benjamin at gmail.com
Wed May 13 15:20:50 CEST 2015


On 12 May 2015 at 19:08, Peter Otten <__peter__ at 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


More information about the Tutor mailing list