The new operator will be available in the new version of Python.
It’s called “walrus operator” because it’s like someone cosplayed a walrus: “:=”.
This is similar to the normal ” =” assignment, but returns the value of the statement.
So this is a C-like assignment. For eaxmple, we can use it for a one-line regexp matching:
if (match := pattern.search(data)) is not None:
# Do something with match
We can write it as two lines:
match = pattern.search(data)
if match is not None:
# Do something with match
but it’s easier to write one simple thought in the one line.
And as we did it in C-based languages, we can do read-while expressions:
while chunk := file.read(8192):
process(chunk)
But it can be hard to understand list comprehensions (warning!):
filtered_data = [y for x in data if (y := f(x)) is not None]
– it seems that it is not follow Zen Python (see “import this”).
See https://www.python.org/dev/peps/pep-0572/ for more information (and motivation). But overall it will help you write simpler code:
