Using the Python walrus operator
A pattern I often encounter is iterating through a range of values, computing an operation on those values and assigning them to a variable. For example, imagine you are saving files and you don't want to over write them, I create an index and keep increasing it until I get a filename which is available. Something like this:
Python
(I believe 3.8) has introduced a new operator called
Walrus
, which greatly simplifies the code above:
The
walrus
operator allows to assign variables to expressions within another expression. In this case, we assigned
filename.format(i)
to
file
and check its existence.
If you want to see a real-world example of when I would use the walrus, check this few lines of code or these ones , in which I search for an appropriate filename.
A caveat : parenthesis play an important role in order resolution:
Outputs
True
, while:
Outputs
4
. In the example with the filename it was not an issue because I was using already another function with the output of the walrus.
I am still hesitant about adding this syntax, since it only works on latest versions of Python which are still not the default on Linux.