On 02/03/18 11:43, Chris Angelico wrote:
After dozens of posts and a wide variety of useful opinions and
concerns being raised, here is the newest version of PEP 572 for your
debating pleasure.


I haven't said this yet, so thanks Chris for putting this all together. Even if the result is a rejected PEP, at least we have everything in one place.

[snip]

     # Compound statements usually enclose everything...
     if (re.match(...) as m):
         print(m.groups(0))
     print(m) # NameError

This (and the equivalent in while loops) is the big win in the PEP, in my opinion. The number of ugly loops I've had to write in Python because I can't write "while (something_to_do() as event):"... +1 on this.

     # Using a statement-local name
     stuff = [[(f(x) as y), x/y] for x in range(5)]

As Paul said, the asymmetry of this bothers me a lot. It doesn't read naturally to me. -1 on this.

1. What happens if the name has already been used? ``(x, (1 as x), x)``
    Currently, prior usage functions as if the named expression did not
    exist (following the usual lookup rules); the new name binding will
    shadow the other name from the point where it is evaluated until the
    end of the statement.  Is this acceptable?  Should it raise a syntax
    error or warning?

I wouldn't worry too much about this case. Anyone gratuitously reusing names like that deserves all that will be coming to them.

Alternative proposals
=====================
3. ``with... as``::

        stuff = [(y, x/y) with f(x) as y for x in range(5)]

    As per option 2, but using ``as`` in place of the equals sign. Aligns
    syntactically with other uses of ``as`` for name binding, but a simple
    transformation to for-loop longhand would create drastically different
    semantics; the meaning of ``with`` inside a comprehension would be
    completely different from the meaning as a stand-alone statement.

Honestly I prefer this syntax for comprehensions. It doesn't read perfectly but it's good enough (though I am a mathematician by original training, so set notation works for me anyway), and the syntax is clear and limited.

I'm not sure the case for fully general statement-local variables has been made.

So, counter-proposal(s):

1. Allow "(f() as a)" in the conditions of "if" and "while" statements, after some arguing as to whether "a" is a special snowflake or just a normal local variable.

2. Add a "with" clause to comprehensions to make comprehension-local variables (presumably the same class of thing as the iteration variables).

--
Rhodri James *-* Kynesim Ltd
_______________________________________________
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