[Python-Dev] PEP 572: Assignment Expressions (original) (raw)
Chris Angelico rosuav at gmail.com
Wed Apr 18 10:35:05 EDT 2018
- Previous message (by thread): [Python-Dev] PEP 572: Assignment Expressions
- Next message (by thread): [Python-Dev] PEP 572: Assignment Expressions
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
On Wed, Apr 18, 2018 at 11:58 PM, Guido van Rossum <guido at python.org> wrote:
I can't tell from this what the PEP actually says should happen in that example. When I first saw it I thought "Gaah! What a horrible piece of code." But it works today, and people's code will break if we change its meaning.
However we won't have to break that. Suppose the code is (perversely) t = range(3) a = [t for t in t if t] If we translate this to t = range(3) def listcomp(t=t): a = [] for t in t: if t: a.append(t) return a a = listcomp() Then it will still work. The trick will be to recognize "imported" names that are also assigned and capture those (as well as other captures as already described in the PEP).
That can be done. However, this form of importing will have one of two consequences:
- Referencing an unbound name will scan to outer scopes at run time, changing the semantics of Python name lookups
- Genexps will eagerly evaluate a lookup if it happens to be the same name as an internal iteration variable.
Of the two, #2 is definitely my preference, but it does mean more eager binding. While this won't make a difference in the outermost iterable (since that's already eagerly bound), it might make a difference with others:
t = range(3) gen = (t for _ in range(1) for t in t if t) t = [4, 5, 6] print(next(gen)) print(next(gen))
Current semantics: UnboundLocalError on first next() call.
PEP 572 semantics: Either UnboundLocalError (with current reference implementation) or it yields 1 and 2 (with eager lookups).
So either we change things for the outermost iterable, or we change things for everything BUT the outermost iterable. Either way, I'm happy to eliminate the special-casing of the outermost iterable. Yes, it's a change in semantics, but a change that removes special cases is generally better than one that creates them.
ChrisA
- Previous message (by thread): [Python-Dev] PEP 572: Assignment Expressions
- Next message (by thread): [Python-Dev] PEP 572: Assignment Expressions
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]