Tag Archives: Python3

Python 3 – Assignment Expressions

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

Python 3: An Intro to Enumerations

Python added the enum module to the standard library in version 3.4. The Python documentation describes an enum like this:

An enumeration is a set of symbolic names (members) bound to unique, constant values. Within an enumeration, the members can be compared by identity, and the enumeration itself can be iterated over.

Let’s look at how you might create an Enum object:

>>> from enum import Enum
>>> class AnimalEnum(Enum):
        HORSE = 1
        COW = 2
        CHICKEN = 3
        DOG = 4
>>> print(AnimalEnum.CHICKEN)
>>> print(repr(AnimalEnum.CHICKEN))

Here we create an Enumeration class called AnimalEnum. Inside the class, we create class attributes called enumeration members, which are constants. When you try to print out an enum member, you will just get back the same string. But if you print out the repr of the enum member, you will get the enum member and its value.

If you try to modify an enum member, Python will raise an AttributeError:

>>> AnimalEnum.CHICKEN = 5
Traceback (most recent call last):
  Python Shell, prompt 5, line 1
  File "C:\Users\mike\AppData\Local\Programs\PYTHON\PYTHON36-32\Lib\enum.py", line 361, in __setattr__
    raise AttributeError('Cannot reassign members.')
builtins.AttributeError: Cannot reassign members.

Continue reading Python 3: An Intro to Enumerations