[Python-Dev] assignment expressions: an alternative proposal

Chris Angelico rosuav at gmail.com
Tue Apr 24 11:28:32 EDT 2018


On Wed, Apr 25, 2018 at 1:15 AM, Steven D'Aprano <steve at pearwood.info> wrote:
> By the way, the check for existing variables cannot help to be either
> incomplete or incorrect if you try to do it at compile time:
>
>
>     from module import *
>     (x = 2)  # allowed or not allowed?
>
>
> If you don't like wild-card imports, how about this:
>
>     if random.random() > 0.5:
>         spam = 1
>     else:
>         eggs = 1
>     (spam = 2)  # allowed or not? no way to tell at compile time
>
>
> But doing the rebinding/shadowing check at runtime will slow down
> binding expressions, and lead to even more arcane and confusing results:
>
>     it = iter("abc")
>     while (obj = next(it)):
>         print(obj)
>
>
> will print "a" on the first loop, but then raise an exception on
> the second time loop as obj now exists.

On re-thinking this, I think the distinction IS possible, but (a) only
in function/class scope, not at global; and (b) would be defined in
terms of lexical position, not run-time. For instance:

def f():
    (a = 1) # Legal; 'a' has not been used yet
    a = 2 # doesn't change that

def f(a):
    (a = 1) # Invalid - 'a' has been used already

def f():
    while (a = get_next()): # Legal
        ...

This could be handled in the symbol collection pass; if the name
already exists in the function's locals, it's disallowed. But I still
stand by my statement that this creates bizarre cases, and yes, I know
that that word is subjective (just like "readable", "intuitive", and
"sensible"). The rules as given sound like they would make great
linter rules and terrible syntax rules. They are closely aligned with
the OP's experience and usage patterns - which means that, as a
personal linter, they could marvellously assist in catching bugs. You
could have personal (or organization-wide) linter rules disallowing
"class foo:" with a lower-case name, and disallowing the rebinding of
any name in ALL_CAPS, but I would not want either rule codified into
language syntax.

ChrisA


More information about the Python-Dev mailing list