June 12th, 2018

Mike Driscoll: Python 3 – Assignment Expressions

Python, by admin.

I recently came across PEP 572, which is a proposal for adding assignment expressions to Python 3.8 from Chris Angelico, Tim Peters and Guido van Rossum himself! I decided to check it out and see what an assignment expression was. The idea is actually quite simple. The Python core developers want a way to assign variables within an expression using the following notation:

NAME := expr

This topic has had a LOT of arguments about it and you can read the details on the Python-Dev Google group if you want to. I personally found that reading through the various pros and cons put forth by Python’s core development community to be very insightful.

Regardless, let’s look at some of the examples from PEP 572 to see if we can figure out how you might use an assignment expression yourself.

# Handle a matched regex
if (match := pattern.search(data)) is not None:
    ...
 
# A more explicit alternative to the 2-arg form of iter() invocation
while (value := read_next_item()) is not None:
    ...
 
# Share a subexpression between a comprehension filter clause and its output
filtered_data = [y for x in data if (y := f(x)) is not None]

In these 3 examples, we are creating a variable in the expression statement itself. The first example creates the variable, match, by assigning it the result of the regex pattern search. The second example assigns the variable, value, to the result of calling a function in the while loop’s expression. Finally we assign the result of calling f(x) to the variable y inside of a list comprehension.

One of the most interesting features of assignment expressions (to me at least), is that they can be used in contexts that an assignment statement cannot, such as in a lambda or the previously mentioned comprehension. However they also do NOT support some things that assignment statements can do. For example, you cannot to multiple target assignment:

x = y = z = 0  # Equivalent: (x := (y := (z := 0)))

You can see a full list of differences in the PEP

There is a lot more information in the PEP that covers a few other examples, talks about rejected alternatives and scope.


Related Reading

Back Top

Comments are closed.