New syntax for Python 3.8 [assignment formula]

Introduction

I would like to read Effective Python 2nd Edition and summarize the functions that impressed me as a memorandum. Please note that the choice is personally subjective. ..

What is an assignment expression?

Simply put, it is ** a short description of variable declarations used in if statements **. Specifically, **: = (walrus operator) ** is used in the conditional expression of if to evaluate the expression and assign it to a variable at once.

For example, suppose you have a dictionary that shows your fruit inventory.

fruits = {
  'apple': 10,
  'banana': 8,
  'lemon': 5,
}

If you need at least four apples to make apple juice, you can conditionally branch whether you can actually make juice as shown below.

n_apple = fruits.get('apple', 0)
if n_apple >= 4:
  # n_Make juice with apple apples
  make_juice(n_apple
else:
  #Do not make juice due to lack of stock
  out_of_stock()

If you write a similar operation using the ** walrus operator **,

#Evaluate the number of apples and assign to variables at the same time
if (n_apple := fruits.get('apple', 0)) >= 4: 
  make_juice(n_apple)
else:
  out_of_stock()

At first glance, the code may seem like a single line, but by writing it this way, you can clearly express that n_apple is used only for the first block of if. ..

Application example

I don't think I can understand the goodness with this alone, so I will take a better example. Suppose you want to prioritize bananas, apples, and lemons in that order to digest your inventory. In addition, the minimum number of fruits required to make juice is 2 bananas, 4 apples, and 1 lemon. Perhaps you would create a ** nested if-else block ** like this:

n_banana = fruits.get('banana', 0)
if n_banana >= 2:
  #If you have 2 or more bananas, make banana juice
  make_juice(n_banana)
else:
  n_apple = fruits.get('apple', 0)
  if n_apple >= 4:
    #Make apple juice if you have 4 or more apples
    make_juice(n_apple)
  else:
    n_lemon = fruits.get('lemon', 0)
    if n_lemon:
      #Make lemon juice if you have more than one lemon
      make_juice(n_lemon)
    else:
      #Do not make juice due to lack of stock
      out_of_stock()

This sounds pretty verbose, doesn't it? Using the walrus operator:

if (n_banana := fruits.get('banana', 0)) >= 2:
  #If you have 2 or more bananas, make banana juice
  make_juice(n_banana)
elif (n_apple := fruits.get('apple', 0)) >= 4:
  #Make apple juice if you have 4 or more apples
  make_juice(n_apple)
elif n_lemon = fruits.get('lemon', 0):
  #Make lemon juice if you have more than one lemon
  make_juice(n_lemon)
else:
  #Do not make juice due to lack of stock
  out_of_stock()

Oita is easier to read. how is it? I think I wanted to use this (laughs). However, note that you must ** enclose the assignment expression in parentheses ** if you want to use the assigned variable for comparison.

do-while statement usage

I will introduce a little more applied usage. ** Python doesn't have a do/while loop **, but you can implement similar logic in a while block and a break statement. For example, consider the process of repeatedly replenishing inventory and bottling juice. The process ends when the inventory is no longer replenished. Suppose the make_juice () function is modified to take the type and number of fruits and return the appropriate number of bottled juices.

#Case for storing bottles
bottles = []
while True:
  #Replenish fruit
  fruits = pick_fruit() 
  if not fruits:
    #End if there is no replenishment
    break
  for fruit, count in fruits.items():
    #Bottled to the appropriate number for each fruit
    batch = make_juice(fruit, count)
    #Add bottle to case
    bottles.extend(batch)

Such processing can also be written short with an assignment expression.

bottles = []
#Assign the replenished fruit to the fruits variable&Evaluate if empty
while fruits := pick_fruit():
  for fruit, count in fruits.items():
    batch = make_juice(fruit, count)
    bottles.extend(batch)

I'm happy that the if block for the assignment statement and break is no longer needed.

in conclusion

The walrus operator is quite convenient. I don't use python3.8 at work, but I hope this feature is also in 3.7.

References

Effective Python 2nd Edition-90 Items to Improve Python Programs

Recommended Posts

New syntax for Python 3.8 [assignment formula]
SublimeText2 and SublimeLinter --Syntax check for Python3--
2016-10-30 else for Python3> for:
python [for myself]
with syntax (Python)
Python syntax-control syntax
For new students (Recommended efforts for Python beginners Part 1)
[Updating] Python Syntax cheat sheet for Java shop
About Python for loops
Python basics ② for statement
Python variable length assignment?
[Python] Multi-line string assignment
About Python, for ~ (range)
python textbook for beginners
Refactoring tools for Python
python for android Toolchain
Python control syntax (memories)
What's new in Python 3.5
New in Python 3.4.0 (1)-pathlib
[Python of Hikari-] Chapter 05-05 Control syntax (for statement-multiple loops-)
OpenCV for Python beginners
What's new in Python 3.6
Install Python (for Windows)
[Python] for statement error
Python environment for projects
[Python of Hikari-] Chapter 05-04 Control syntax (for statement-use of range function-)
Python memo (for myself): Array
About Fabric's support for Python 3
Python for Data Analysis Chapter 4
Modern Python for intermediate users
Learning flow for Python beginners
Python 3.6 installation procedure [for Windows]
What's new in Python 3.10 (Summary)
BigQuery integration for Python users
Python learning plan for AI learning
Set Up for Mac (Python)
Read Euler's formula in Python
Search for strings in Python
Python Tkinter notes (for myself)
Scraping using Python 3.5 Async syntax
OpenCV3 installation for Python3 @macOS
Python code memo for yourself
[Python] xmp tag for photos
Python environment construction For Mac
Techniques for sorting in Python
pp4 (python power for anything)
Python3 environment construction (for beginners)
Roadmap for publishing Python packages
Python 3 series installation for mac
Python #function 2 for super beginners
Ruby and Python syntax ~ branch ~
Python template for Codeforces-manual test-
#python Python Japanese syntax error avoidance
Basic Python grammar for beginners
3 months note for starting Python
Qt for Python app self-update
Python for Data Analysis Chapter 2
100 Pandas knocks for Python beginners
Checkio's recommendation for learning Python
Keyword arguments for Python functions
[For organizing] Python development environment