Monday, August 9, 2021

Real Python: The Walrus Operator: Python 3.8 Assignment Expressions

Each new version of Python adds new features to the language. For Python 3.8, the biggest change is the addition of assignment expressions. Specifically, the := operator gives you a new syntax for assigning variables in the middle of expressions. This operator is colloquially known as the walrus operator.

This tutorial is an in-depth introduction to the walrus operator. You will learn some of the motivations for the syntax update and explore some examples where assignment expressions can be useful.

In this tutorial, you’ll learn how to:

  • Identify the walrus operator and understand its meaning
  • Understand use cases for the walrus operator
  • Avoid repetitive code by using the walrus operator
  • Convert between code using the walrus operator and code using other assignment methods
  • Understand the impacts on backward compatibility when using the walrus operator
  • Use appropriate style in your assignment expressions

Note that all walrus operator examples in this tutorial require Python 3.8 or later to work.

Free Download: Get a sample chapter from Python Tricks: The Book that shows you Python’s best practices with simple examples you can apply instantly to write more beautiful + Pythonic code.

Walrus Operator Fundamentals

Let’s start with some different terms that programmers use to refer to this new syntax. You’ve already seen a few in this tutorial.

The := operator is officially known as the assignment expression operator. During early discussions, it was dubbed the walrus operator because the := syntax resembles the eyes and tusks of a sideways walrus. You may also see the := operator referred to as the colon equals operator. Yet another term used for assignment expressions is named expressions.

Hello, Walrus!

To get a first impression of what assignment expressions are all about, start your REPL and play around with the following code:

>>>
 1>>> walrus = False
 2>>> walrus
 3False
 4
 5>>> (walrus := True)
 6True
 7>>> walrus
 8True

Line 1 shows a traditional assignment statement where the value False is assigned to walrus. Next, on line 5, you use an assignment expression to assign the value True to walrus. After both lines 1 and 5, you can refer to the assigned values by using the variable name walrus.

You might be wondering why you’re using parentheses on line 5, and you’ll learn why the parentheses are needed later on in this tutorial.

Note: A statement in Python is a unit of code. An expression is a special statement that can be evaluated to some value.

For example, 1 + 2 is an expression that evaluates to the value 3, while number = 1 + 2 is an assignment statement that doesn’t evaluate to a value. Although running the statement number = 1 + 2 doesn’t evaluate to 3, it does assign the value 3 to number.

In Python, you often see simple statements like return statements and import statements, as well as compound statements like if statements and function definitions. These are all statements, not expressions.

There’s a subtle—but important—difference between the two types of assignments seen earlier with the walrus variable. An assignment expression returns the value, while a traditional assignment doesn’t. You can see this in action when the REPL doesn’t print any value after walrus = False on line 1, while it prints out True after the assignment expression on line 5.

You can see another important aspect about walrus operators in this example. Though it might look new, the := operator does not do anything that isn’t possible without it. It only makes certain constructs more convenient and can sometimes communicate the intent of your code more clearly.

Note: You need at least Python 3.8 to try out the examples in this tutorial. If you don’t already have Python 3.8 installed and you have Docker available, a quick way to start working with Python 3.8 is to run one of the official Docker images:

$ docker container run -it --rm python:3.8-slim

This will download and run the latest stable version of Python 3.8. For more information, see Run Python Versions in Docker: How to Try the Latest Python Release.

Now you have a basic idea of what the := operator is and what it can do. It’s an operator used in assignment expressions, which can return the value being assigned, unlike traditional assignment statements. To get deeper and really learn about the walrus operator, continue reading to see where you should and shouldn’t use it.

Implementation

Like most new features in Python, assignment expressions were introduced through a Python Enhancement Proposal (PEP). PEP 572 describes the motivation for introducing the walrus operator, the details of the syntax, as well as examples where the := operator can be used to improve your code.

This PEP was originally written by Chris Angelico in February 2018. Following some heated discussion, PEP 572 was accepted by Guido van Rossum in July 2018. Since then, Guido announced that he was stepping down from his role as benevolent dictator for life (BDFL). Starting in early 2019, Python has been governed by an elected steering council instead.

The walrus operator was implemented by Emily Morehouse, and made available in the first alpha release of Python 3.8.

Motivation

In many languages, including C and its derivatives, assignment statements function as expressions. This can be both very powerful and also a source of confusing bugs. For example, the following code is valid C but doesn’t execute as intended:

Read the full article at https://realpython.com/python-walrus-operator/ »


[ Improve Your Python With 🐍 Python Tricks 💌 – Get a short & sweet Python Trick delivered to your inbox every couple of days. >> Click here to learn more and see examples ]



from Planet Python
via read more

No comments:

Post a Comment

TestDriven.io: Working with Static and Media Files in Django

This article looks at how to work with static and media files in a Django project, locally and in production. from Planet Python via read...