Use the Walrus Operator to Assign and Print in One Line

My new favorite use of the walrus operator in Python

Use the Walrus Operator to Assign and Print in One Line
Photo by Mr Cup / Fabien Barral on Unsplash

In Python 3.8, the assignment-expression operator, walrus operator, was released. The convention has been met with a mixed reception as some claim the syntax goes against the “simple is better” vision of Python.

I previously published a set of three techniques to use the operator; however, I’ve found myself using the operator most frequently to print the value assigned to a variable.


When Do I Print an Assigned Value?

This scenario comes about most frequently when making requests to external APIs that return a response.

For example, say I am making a request to an API to create a new object and the ID of that object is returned in the response. I need to do two things here:

  • Print the ID so I know it was successful.
  • Store the ID so I can use it downstream.

How the Code Looked Before

I frequently have pairs of statements like the following below:result = apiRequest()
print(result)resultTwo = apiRequestTwo(result)

Notice how I print the result but then use it later on in a subsequent call.

The code starts to get convoluted when I need to print a message preceding the API request. I’d prefer to write it this way:print("Creating record...", apiRequest())

But, in this scenario, I cannot do the assignment. Thus, I have to do this:print("Creating record...")
result = apiRequest()
print(result)

Sandwiching the request and assignment between print statements has been less than ideal for me.


Enter the Walrus Operator

With the walrus operator, I can take what used to be three lines and condense them into one.print("Creating record...", result := apiRequest())

What is happening here?

The walrus operator is going to assign the response from my API request to result and then use that value as the passed value to the print() statement.


Conclusion

This has been the highest return on my mental investment to adopt new practices so far.

Please share if you find other creative uses for the operator. It’s an exciting time when we get something new to play with and learn how to leverage it.

Subscribe to Dreams of Fortunes and Cookies

Sign up now to get access to the library of members-only issues.
Jamie Larson
Subscribe