[Python-Dev] PEP 572: intended scope of assignment expression (original) (raw)

Gustavo Carneiro gjcarneiro at gmail.com
Thu Jul 5 09:14:35 EDT 2018


On Thu, 5 Jul 2018 at 13:43, Victor Stinner <vstinner at redhat.com> wrote:

Hi,

My work (*) in the "Assignment expression and coding style: the while True case" thread helped me to understand something about the intended scope. While technically, assignment expressions keep the same scoping rules than assignment statements, writing "if (x := func()): ..." or "while (x := func()): ..." shows the "intented" scope of the variable. Even if, as explained properly in the PEP, the scope is wider (for good reasons) as "for line in file: ..." keeps line alive after the loop (nothing new under the sun). It's something subtle that I missed at the first read (of the code and the PEP), the difference is not obvious. x = func() if x: ... # obviously use x # do we still plan to use x here? # it's non obvious just by reading the if versus if (x := func()): ... # obviously use x # ":=" in the if "announces" that usually x is no longer used # here, even if technically x is still defined

I don't know if you're trying to propose something clever here, like "if (x := func()):" would assign to 'x' only inside the "then" body of the if, but IMHO that would be a terrible idea:

  1. it makes AE harder to explain. Right now you can simply say AE works just like any regular assignment, except that you can use in an expression. If you start adding exceptions to the rule, things get harder and harder to explain;
  2. it would probably have a cost in terms of performance: you'd have to create another scope for every "then" body of any if statement that contains an AE. And, again, more scopes = things harder to understand.

-- Gustavo J. A. M. Carneiro Gambit Research "The universe is always one step beyond logic." -- Frank Herbert -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-dev/attachments/20180705/5f8250ff/attachment.html>



More information about the Python-Dev mailing list