Assignment expressions perform the assignment and also return the value of the assignment. So you can assign and test a conditional at the same time. It's quite an elegant alternative to some quite verbose repetitive code you would otherwise have to write in some scenarios.
f-strings was another Python 3 idea that was pre-dated by an implementation in C# [1] ($-interpolation) and it was a popular idea in that language too.
I don't want to proffer an opinion on PEP 572 since I haven't followed the discussions, but these things have been "bench-tested" in other languages and not been found wanting, so I do wonder a little bit about the true cause of the controversy.
[1] https://docs.microsoft.com/en-us/dotnet/csharp/language-refe...
I'm sick and tired of writing stuff like
m = f( <...> )
if m:
# do stuff with m
Trivial as it may be, I for one welcome this. if m := re.match(...):
...
elif m := re.match(...):
...
The world is not coming to an end, as some detractors of the PEP might think. The new syntax is a win in a number of cases. Otherwise, you don't need to use it. The concern for abuse is way overblown. I could live without it (voted -1 on the idea originally) but now that it is in, think it is fine. case f <...> of
Nothing -> -- Handles the problem values
Just m -> -- do stuff with m
This is, honestly, much better than an assignment expression. Side-effect expressions always bring problematic cases.Will `with` start using this syntax instead of `b as a`: `with open('foo') as a:` == `with a := open('foo'):`?
Update: found my answer on the pep. `with EXPR as VAR` actually calls `EXPR.__enter__()` so it's not the same.
Seems very unnecessary to have both options.
That's not it at all. The PEP even acknowledges that while `(a := b)` would be valid, it would not be recommended.
Naturally people went to the barricades for it, in a classic example of bikeshedding and Wadler's Law (programmers will fight to the death over trivial syntax disagreements and just shrug at profound changes to semantics and architecture)