[Python-Dev] (name := expression) doesn't fit the narrative of PEP 20

Stephen J. Turnbull turnbull.stephen.fw at u.tsukuba.ac.jp
Thu Apr 26 07:27:26 EDT 2018


Łukasz Langa writes:
 > > On 25 Apr, 2018, at 5:20 PM, Chris Angelico <rosuav at gmail.com> wrote:

 > You're claiming that `:=` is nicer in this situation because it's less
 > prominent than regular assignment and thus doesn't suggest that the name
 > stays visible later.

FWIW, I read what he wrote as "*assuming* buf is not going to be used
later", and thus took a more nuanced idea from it: Use a separate
statement when you do use it later, and use a binding expression when
its scope is *in fact* only that line.

BTW, I don't find the "it could be misused, so it will be misused"
argument persuasive.  I agree it's true, but don't think it matters,
per the "consenting adults" principle, since binding expressions have
other, important, use cases.

We could add a statement to PEP 8 mildly deprecating this particular
use.  How about this:

    In some examples, the binding expression is used in function
    arguments where one argument depends on an earlier one, such as

    foo(buffer=(buf := [None]*get_size()), size=len(buf))

    In examples like this one, it is preferable where possible to
    refactor the function to calculate the dependent variable itself,
    or to use an assignment statement to define the bound variable.
    The latter style is *strongly* preferred when the bound variable
    will be used later in the scope.

Steve



More information about the Python-Dev mailing list