What is := operator?
In simple terms := is a expression + assignment operator.
it executes an expression and assigns the result of that expression in a single variable.
Why is := operator needed?
simple useful case will be to reduce function calls in comprehensions while maintaining the redability.
lets consider a list comprehension to add one and filter if result is grater than 0 without a := operator. Here we need to call the add_one function twice.
[add_one(num) for num in numbers if add_one(num) > 0]
Case 1:
def add_one(num):
return num + 1
numbers = [1,2,3,4,-2,45,6]
result1 = [value for num in numbers if (value := add_one(num)) > 0]
>>> result1
[2, 3, 4, 5, 46, 7]
The result is as expected and we don't need to call the add_one function to call twice which shows the advantage of := operator
be cautious with walarus := operator while using list comprehension
below cases might help you better understand the use of := operator
Case 2:
def add_one(num):
return num + 1
numbers = [1,2,3,4,-2,45,6]
>>> result2 = [(value := add_one(num)) for num in numbers if value > 0]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 1, in <listcomp>
NameError: name 'value' is not defined
Case 3: when a global variable is set to positive
def add_one(num):
return num + 1
numbers = [1,2,3,4,-2,45,6]
value = 1
result3 = [(value := add_one(num)) for num in numbers if value > 0]
>>> result3
[2, 3, 4, 5, -1]
Case 4: when a global variable is set to negitive
def add_one(num):
return num + 1
numbers = [1,2,3,4,-2,45,6]
value = -1
result4 = [(value := add_one(num)) for num in numbers if value > 0]
>>> result4
[]
as
syntax as in PEP 379. Although there was a lot of discussion and a huge amount of work done on the PEP, it was only about four and a half months from proposal to acceptance - some other PEPs have taken years. – Aronoff