[Python-ideas] PEP 572: Statement-Local Name Bindings, take three!
Steven D'Aprano
steve at pearwood.info
Sun Mar 25 06:31:03 EDT 2018
On Sun, Mar 25, 2018 at 05:00:37PM +1000, Nick Coghlan wrote:
> Given the existing namespace stack of
> builtin<-global<-nonlocal<-local, one potential short name would be
> "sublocal", to indicate that these references are even more local than
> locals (they're *so* local, they don't even appear in locals()!).
If we go down this track, +1 on the name "sublocal".
[...]
> And if we do end up going with the approach of defining a separate
> sublocal namespace, the fact that "n := ..." binds a sublocal, while
> "n = ..." and "... as n" both bind regular locals would be clearer
> than having the target scope of "as" be context dependent.
The scope issue is a good argument for avoiding "as" if we have sublocal
binding.
One thing I like about the (expression as name) syntax is that the
expression comes first. The Pascal-style := binding syntax reverses
that. While we're bike-shedding, here are some alternatives to compare:
target = default if (expression as name) is None else name
target = default if (name := expression) is None else name
target = default if (expression -> name) is None else name
target = default if (name <- expression) is None else name
The arrow assignment operators <- and -> are both used by R. A dedicated
non-ASCII forward arrow is also used by some programmable calculators,
including HP and TI. But let's not start using non-ASCII symbols yet.
If we don't like a symbolic operator, we could channel BASIC from the
1970s and write something like this:
target = default if (let expression = name) is None else name
Pros:
- requiring the keyword "let" prevents the "equals versus
assignment" class of errors;
- easier to search for a keyword than a symbolic operator;
Cons:
- more verbose;
- looks like BASIC;
- requires a new keyword.
--
Steve
More information about the Python-ideas
mailing list