Python walrus operator is weird...
I am software developer based on Kathmandu, Nepal.
Python walrus operator (:=) was introduced in Python 3.8. This operator helps most of the developers to assign variables in the middle of an expression.
Let's have a quick look, how walrus operator comes into hand.
def add(x):
return x + 1
# before using walrus operator
if add(x) > 5:
return add(x)
# using walrus operator
if (res := add(x)) > 5:
return res
Before using the walrus operator we are calling the add function twice, but using the walrus operator we don't have to call the walrus operator twice.
So, What is weird about walrus operator (actually its a fact)
1. Operator Precedence
def add(x):
return x + 1
# using walrus operator
if res := add(x) > 5:
return res
So, what do you think after removing the parenthesis, what it will be going to return (a number)?? Actually, it will return a Boolean (False or True) because of operator precedence. Since the Comparison operator has higher precedence it will be going to execute first and Boolean value will be assigned to res and it will return Boolean.
2. Direct Assignment
Walrus operators come into hand during the execution of valid expressions, Like if or for statements.
a := add(x) # gives error
(a := add(x)) # doesn't give error
print(a)
So, these two things I found weird (but actually it's not weird it's a fact) in the Python walrus operator, if you are familiar with other weird things about python walrus please add a comment below.