[Python-Dev] PEP 550 v4

Greg Ewing greg.ewing at canterbury.ac.nz
Tue Aug 29 17:45:08 EDT 2017


Yury Selivanov wrote:
> Consider the following generator:
> 
>       def gen():
>          with decimal.context(...):
>             yield
> 
> We don't want gen's context to leak to the outer scope

That's understandable, but fixing that problem shouldn't come
at the expense of breaking the ability to refactor generator
code or async code without changing its semantics.

I'm not convinced that it has to, either. In this example,
the with-statement is the thing that should be establishing
a new nested context. Yielding and re-entering the generator
should only be swapping around between existing contexts.

> Not, let's consider a "broken" generator:
> 
>      def gen():
>           decimal.context(...)
>           yield

The following non-generator code is "broken" in exactly
the same way:

    def foo():
       decimal.context(...)
       do_some_decimal_calculations()
       # Context has now been changed for the caller

> I simply want consistency.

So do I! We just have different ideas about what consistency
means here.

> It's easier for everybody to say that
> generators never leaked their context changes to the outer scope,
> rather than saying that "generators can sometimes leak their context".

No, generators should *always* leak their context changes
to exactly the same extent that normal functions do. If you
don't want to leak a context change, you should use a with
statement.

What you seem to be suggesting is that generators shouldn't
leak context changes even when you *don't* use a with-statement.
If you're going to to that, you'd better make sure that the
same thing applies to regular functions, otherwise you've
introduced an inconsistency.

-- 
Greg



More information about the Python-Dev mailing list