Join my Laravel for REST API's course on Udemy 👀

The Python walrus operator

April 9, 2021  ‐ 1 min read

Since the release of Python 3.8 we can assign values to variables within an expression using the walrus operator(:=), also more formally known as the assignment expressions.

An advantage of being able to assign a variable in an if-statement that you only use within the scope of that if statement. This often allows you to write shorter code. For example you could write:

if (exit_code := command.run()) > 0:
    print(f'exited with non-zero status ({exit_code})')

Instead of this:

exit_code = command.run()
if exit_code > 0:
    print(f'exited with non-zero status ({exit_code})')

The same logic can be useful in while structures too. The following for example is a while loop that requires user input, and quits the while loop when "exit" is entered.

while (line := input()) != 'exit':
    f.write(line)