[Python-ideas] PEP 572: Assignment Expressions (post #4)

Paul Moore p.f.moore at gmail.com
Wed Apr 11 04:55:13 EDT 2018


On 11 April 2018 at 06:32, Chris Angelico <rosuav at gmail.com> wrote:
> When a class scope is involved, a naive transformation into a function would
> prevent name lookups (as the function would behave like a method).
>
>     class X:
>         names = ["Fred", "Barney", "Joe"]
>         prefix = "> "
>         prefixed_names = [prefix + name for name in names]
>
> With Python 3.7 semantics, this will evaluate the outermost iterable at class
> scope, which will succeed; but it will evaluate everything else in a function::
>
>     class X:
>         names = ["Fred", "Barney", "Joe"]
>         prefix = "> "
>         def <listcomp>(iterator):
>             result = []
>             for name in iterator:
>                 result.append(prefix + name)
>             return result
>         prefixed_names = <listcomp>(iter(names))
>
> The name ``prefix`` is thus searched for at global scope, ignoring the class
> name. Under the proposed semantics, this name will be eagerly bound, being
> approximately equivalent to::
>
>     class X:
>         names = ["Fred", "Barney", "Joe"]
>         prefix = "> "
>         def <listcomp>(prefix=prefix):
>             result = []
>             for name in names:
>                 result.append(prefix + name)
>             return result
>         prefixed_names = <listcomp>()

Surely "names" would also be eagerly bound, for use in the "for" loop?

[...]
>
> This could be used to create ugly code!
> ---------------------------------------
>
> So can anything else.  This is a tool, and it is up to the programmer to use it
> where it makes sense, and not use it where superior constructs can be used.

Related objection - when used to name subexpressions in a
comprehension (one of the original motivating use cases for this
proposal), this introduces an asymmetry which actually makes the
comprehension harder to read. As a result, it's quite possible that
people won't want to use assignment expressions in this case, and the
use case of precalculating expensive but multiply used results in
comprehensions will remain unanswered.

I think the response here is basically the same as the above - if you
don't like them, don't use them. But I do think the additional nuance
of "we might not have solved the original motivating use case" is
worth a specific response.

Overall, I like this much better than the previous proposal. I'm now
+1 on the semantic changes to comprehensions, and barely +0 on the
assignment expression itself (I still don't think assignment
expressions are worth it, and I worry about the confusion they may
cause for beginners in particular).

Paul


More information about the Python-ideas mailing list