[Python-ideas] Make "yield" inside a with statement a SyntaxError

Peter Otten __peter__ at web.de
Wed Aug 8 12:13:41 EDT 2018


Ronald Oussoren via Python-ideas wrote:

> It is also possible to fix the particular issue by using another with
> statement, that is use:
> 
> with contextlib.closing(read_multiple(…)) as chunks:
>    for contents in chunks:
>> 
> Automatically closing the generator at the end of the for loop would be
> nice, but getting the semantics right without breaking existing valid code
> is not trivial.

How about providing a decorator that turns the generator into a context 
manager

def close_gen(f):
    @contextmanager
    @wraps(f)
    def g(*args, **kw):
        with closing(f(*args, **kw)) as h:
            yield h
    return g

@close_gen
def read_multiple(...):
    ...

?

A more radical approach would be to add __enter__ and __exit__ methods so 
that for every generator function f

with f() as g:
   pass

would call g.close()



More information about the Python-ideas mailing list