Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why there is a need for dedicated syntax (:=, the Walrus operator) for named expressions in Python?

I genuinely do not understand why there was a need to introduce a dedicated syntax (the := operator) for named expressions, described in PEP572. E.g. one is supposed to write:

if (match := pattern.search(data)) is not None:
    # Do something with match

why not simply if (match = pattern.search(data))? If it is because of backward compatibility, then note that the following expression: (x = 1) raises SyntaxError: invalid syntax, thus it would be enough to allow for it and start interpreting it as a named expression, instead of introducing the new := operator, which btw will in probably most cases be surrounded by parentheses anyway.

I feel like I don't see something obvious that everyone else gets ;-)

like image 701
Maciek Avatar asked Oct 18 '25 22:10

Maciek


1 Answers

It’s because explicit is better than implicit, and := makes your intentions of performing assignment clear; whereas using = could easily be the result of a typo, which is the reason why = intentionally does not work in an expression in Python.

In fact, accidentally using = instead of == inside a comparison is a frequent source of error in languages that support it.

like image 122
Konrad Rudolph Avatar answered Oct 21 '25 13:10

Konrad Rudolph