Chris Angelico wrote:
> On Sun, Mar 25, 2018 at 8:31 PM, Christoph Groth
> <christ...@grothesque.org> wrote:
> > That's indeed a bit strange, and I would consider it somewhat of a wart
> > of the language.  But as far as I can tell remaining compatible with the
> > above behavior does not force us to leak assignments from the outermost
> > scope of a comprehension.  I.e. there's nothing in the language
> > currently that forces
> >
> > listcomp = [x for x in (r := sequence)]
> >
> > to leak the name "r".
> 
> It seems fine in a simple example, but remember, an assignment
> expression can be used ANYWHERE in an expression. Consider:
> 
> listcomp = [x for x in obj[r := f()][x + r] ]
> 
> Which parts happen in the inner scope and which in the outer scope? If
> 'r' is created in a subscope, it has to be a subscope of the outer
> scope; if it's not subscoped, it has to be directly in the outer
> scope. It can't sanely be in the inner scope.

The example you give is indeed difficult to understand, but all
programming languages, even Python, allow to write confusing code.
Already today we can have

listcomp = [x for x in obj[f()][x + r]]

and, while valid, that's hardly an example worthy of emulation.

Compared to this, the example that you give is indeed even more
treacherous, because innocent people could assume that the 'r' in '[x +
r]' is the one set just before with ':='.  But is this obscure behavior
really a problem?  A bug can only happen if 'r' is also defined in the
surrounding scope, otherwise there will be an error.

And if this is indeed considered a problem, such confusing situations
could be detected and flagged as an error by the Python compiler until
the underlying inconsistency in the language is fixed.

I think that it's a helpful guideline to imagine what the ideal behavior
should be if we were not constrained by backwards compatibility, and
then try to follow it.  In the case at hand, we all seem to agree that
the fact that the outermost iterator of a comprehension is evaluated in
the surrounding scope is somewhat of a wart, although one that is rarely
visible.  The existence of a wart shouldn't pull us further into the
wrong direction.
_______________________________________________
Python-ideas mailing list
Python-ideas@python.org
https://mail.python.org/mailman/listinfo/python-ideas
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to