惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

酷 壳 – CoolShell
酷 壳 – CoolShell
P
Privacy & Cybersecurity Law Blog
G
GRAHAM CLULEY
T
The Exploit Database - CXSecurity.com
www.infosecurity-magazine.com
www.infosecurity-magazine.com
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
Project Zero
Project Zero
S
Security @ Cisco Blogs
TaoSecurity Blog
TaoSecurity Blog
A
Arctic Wolf
Webroot Blog
Webroot Blog
Hacker News - Newest:
Hacker News - Newest: "LLM"
Security Latest
Security Latest
H
Heimdal Security Blog
N
News and Events Feed by Topic
N
News | PayPal Newsroom
T
Tor Project blog
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
GbyAI
GbyAI
The Last Watchdog
The Last Watchdog
Y
Y Combinator Blog
宝玉的分享
宝玉的分享
Scott Helme
Scott Helme
A
About on SuperTechFans
M
MIT News - Artificial intelligence
V
V2EX
V
Visual Studio Blog
Recorded Future
Recorded Future
博客园 - 叶小钗
F
Fortinet All Blogs
L
Lohrmann on Cybersecurity
The GitHub Blog
The GitHub Blog
博客园 - Franky
P
Proofpoint News Feed
MyScale Blog
MyScale Blog
D
Darknet – Hacking Tools, Hacker News & Cyber Security
S
Secure Thoughts
D
DataBreaches.Net
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
博客园 - 三生石上(FineUI控件)
I
InfoQ
SecWiki News
SecWiki News
Blog — PlanetScale
Blog — PlanetScale
Engineering at Meta
Engineering at Meta
J
Java Code Geeks
B
Blog RSS Feed
AWS News Blog
AWS News Blog
Know Your Adversary
Know Your Adversary
V
Vulnerabilities – Threatpost
H
Help Net Security

Martin Heinz's Blog

A Guide to Python's Weak References Using weakref Module Recent Docker BuildKit Features You're Missing Out On Modern Git Commands and Features You Should Be Using Everything You Can Do with Python's textwrap Module Monitoring Indoor Air Quality with Prometheus, Grafana and a CO2 Sensor Everything You Can Do with Python's bisect Module You Don't Need a Dedicated Cache Service - PostgreSQL as a Cache A Collection of Docker Images To Solve All Your Debugging Needs Weird Python "Features" That Might Catch You By Surprise Lessons Learned From Writing 100 Articles Debugging Crashes and Deadlocks in Python using PyStack Goodbye etcd, Hello PostgreSQL: Running Kubernetes with an SQL Database Remote Interactive Debugging of Python Applications Running in Kubernetes The Right Way to Run Shell Commands From Python Real Multithreading is Coming to Python - Learn How You Can Use It Now Python's Missing Batteries: Essential Libraries You're Missing Out On Kubernetes-Native Synthetic Monitoring with Kuberhealthy Make Your CLI Demos a Breeze with Zero Stress and Zero Mistakes Reduce - The Power of a Single Python Function Why I Will Never Use Alpine Linux Ever Again Cgroups - Deep Dive into Resource Management in Kubernetes Dictionary Dispatch Pattern in Python Boost Your Python Application Performance using Continuous Profiling Lazy Evaluation Using Recursive Python Generators Python Magic Methods You Haven't Heard About Getting Started with Mastodon API in Python Backup-and-Restore of Containers with Kubernetes Checkpointing API Getting Started with Google APIs in Python Python CLI Tricks That Don't Require Any Code Whatsoever All The Ways To Introspect Python Objects at Runtime What is Python's "self" Argument, Anyway? Python List Comprehensions Are More Powerful Than You Might Think Recipes and Tricks for Effective Structural Pattern Matching in Python It's Time to Say Goodbye to These Obsolete Python Libraries Advanced Features of Kubernetes' Horizontal Pod Autoscaler Data and System Visualization Tools That Will Boost Your Productivity Stop Messing with Kubernetes Finalizers Automate All the Boring Kubernetes Operations with Python End-to-End Monitoring with Grafana Cloud with Minimal Effort Bitly | bit.ly/3JLmSgA Bitly | bit.ly/3uETfbi Bitly | bit.ly/3MI4Iz0 Bitly | bit.ly/3M30D82 Bitly | bit.ly/3oMJ6qR Bitly | bit.ly/3IRD7IK Bitly | bit.ly/3A3B69t Bitly | bit.ly/31lKCYA Bitly | bit.ly/30uviIM Bitly | bit.ly/3E1X2mw Bitly | bit.ly/3Dv7JxP Bitly | bit.ly/3GG1BEz Bitly | bit.ly/3lLavs4 Bitly | bit.ly/39TqP3m Bitly | bit.ly/3A5Mpx8 Bitly | bit.ly/3kGwPl4 Bitly | bit.ly/3iHtulU Bitly | bit.ly/3xGjtKS Bitly | bit.ly/3h8DZg0 Bitly | bit.ly/2RQn1dG Bitly | bit.ly/3p2B5wW The Easiest Way to Debug Kubernetes Workloads Bitly | bit.ly/2PHVudx Cloud Native CI/CD with Tekton - Building Custom Tasks Bitly | bit.ly/3dg3QR9 Bitly | bit.ly/3qHtSkZ Deep Dive into Docker Internals - Union Filesystem Bitly | bit.ly/3qlRAUN Bitly | bit.ly/3pCUJ26 Bitly | bit.ly/3ifZxYr Bitly | bit.ly/34ZhIMt Bitly | bit.ly/3qSO7h0 Bitly | bit.ly/3muGLOk Bitly | bit.ly/35xN79v Bitly | bit.ly/3mLGshK Bitly | bit.ly/2IvkGQl Bitly | bit.ly/2Sk1KFK Bitly | bit.ly/3iCNIL6 Bitly | bit.ly/3beQPpy Saving Your Linux Machine from Certain Death New Features in Python 3.9 You Should Know About Deploy Any Python Project to Kubernetes Analyzing Docker Image Security Recursive SQL Queries with PostgreSQL Automating Every Aspect of Your Python Project Tour of Python Itertools Implementing 2D Physics in Javascript Ultimate Setup for Your Next Python Project Making Python Programs Blazingly Fast Security and Cryptography Mistakes You Are Probably Doing All The Time Going Serverless with OpenFaaS and Golang - Building Optimized Templates Going Serverless with OpenFaaS and Golang - The Ultimate Setup and Workflow Setting Up Swagger Docs for Golang API Building RESTful APIs in Golang Pytest Features, That You Need in Your (Testing) Life Setting up GitHub Package Registry with Docker and Golang Ultimate Setup for Your Next Golang Project Python Tips and Trick, You Haven't Already Seen, Part 2. Tricks for Postgres and Docker that will make your life easier Getting The Most Out of Reading Books - Reading The "Professional Way" Python Tips and Trick, You Haven't Already Seen
You Should Be Using Python's Walrus Operator - Here's Why
Martin · 2022-08-16 · via Martin Heinz's Blog

The assignment operator - or walrus operator as we all know it - is a feature that's been in Python for a while now (since 3.8), yet it's still somewhat controversial and many people have unfounded hate for it.

In this article I will try to convince you that the walrus operator really is a good addition to the language and that if you use it properly, then it can help you make your code more concise and readable.

Basics/Essentials

In case you're not yet familiar with the :=, let's first review some of the basic use cases that might persuade you to give this Python feature a shot.

First example I want to show you is how you can use walrus operator to reduce number of function invocations. Let's imagine a function called func() that performs some very expensive computations. It takes a long time to compute results, so we don't want to call it many times:


# "func" called 3 times
result = [func(x), func(x)**2, func(x)**3]

# Reuse result of "func" without splitting the code into multiple lines
result = [y := func(x), y**2, y**3]

In the first list declaration above, the func(x) is called 3 times, everytime returning same result, which wastes time and compute resources. When rewritten using walrus operator, func() is invoked only once, assigning its result to y and reusing it for remaining 2 list values. You might say, "I can just add y = func(x) before the list declaration and I don't need the walrus!", you can, but that's one extra, unnecessary line of code and at first glance - without knowing that func(x) is super slow - it might not be clear why the extra y variable needs to exist.

If you're not convinced by the above, I have another one. Consider the following list comprehensions with the same expensive func():


result = [func(x) for x in data if func(x)]

result = [y for x in data if (y := func(x))]

In the first line, func(x) is called twice in every loop. Instead - using walrus operator - we compute it once in the if statement and then reuse it. The code length is same, both lines are equally readable, but the second one is twice as efficient. You could avoid using walrus operator while keeping the performance by changing it to full for loop, but that would require 5 lines of code.

One of the most common use cases for walrus operator is reducing nested conditionals, such as when using RegEx matching:


import re

test = "Something to match"

pattern1 = r"^.*(thing).*"
pattern2 = r"^.*(not present).*"

m = re.match(pattern1, test)
if m:
    print(f"Matched the 1st pattern: {m.group(1)}")
else:
    m = re.match(pattern2, test)
    if m:
        print(f"Matched the 2nd pattern: {m.group(1)}")

# ---------------------
# Cleaner
if m := (re.match(pattern1, test)):
    print(f"Matched 1st pattern: '{m.group(1)}'")
elif m := (re.match(pattern2, test)):
    print(f"Matched 2nd pattern: '{m.group(1)}'")

By using walrus, we reduced the matching code from 7 to 4 lines, while making it more readable by removing the nested if.

Next one on the list so-called "loop-and-half" idiom:


while True:  # Loop
    command = input("> ")
    if command == 'exit':  # And a half
        break
    print("Your command was:", command)

# ---------------------
# Cleaner
while (command := input("> ")) != "exit":
    print("Your command was:", command)

The usual solution is to use dummy infinite while loop, with control flow is delegated to the break statement. Instead, we can use walrus operator to reassign the value of command and then use it in while loop's conditional all on the same line, making the code much cleaner and shorter.

Similar simplification can be applied to other while loops as well, for example when reading files line by line or when receiving data from socket.

Accumulate Data In-Place

Moving on to some little more advanced use cases of walrus operator. This one being possibility to accumulate data in-place:


data = [5, 4, 3, 2]
c = 0; print([(c := c + x) for x in data])  # c = 14
# [5, 9, 12, 14]

from itertools import accumulate
print(list(accumulate(data)))

# ---------------------
data = [5, 4, 3, 2]
print(list(accumulate(data, lambda a, b: a*b)))
# [5, 20, 60, 120]

a = 1; print([(a := a*b) for b in data])
# [5, 20, 60, 120]

The first 2 lines show how you can leverage walrus operator to compute running total. For such a simple case, functions from itertools, such as accumulate are a better fit as you can see on the next 2 lines. For more complex scenarios however, using itertools becomes unreadable quite quickly and - in my opinion - version with := is much nicer than the one with lambda.

If you're still not convinced check out the accumulate examples in docs (e.g. the accumulating interest or logistic map example), which aren't really readable. Try rewriting them to use the assignment expression, they will look much nicer.

Naming Values Inside f-string

This example showcases possibilities and limits or the := rather than the best practices.

If you really wanted to, you could use the walrus operator inside f-strings:


from datetime import datetime

print(f"Today is: {(today:=datetime.today()):%Y-%m-%d}, which is {today:%A}")
# Today is: 2022-07-01, which is Friday

from math import radians, sin, cos
angle = 60
print(f'{angle=}\N{degree sign} {(theta := radians(angle)) =: .2f}, {sin(theta) =: .2f}, {cos(theta) =: .2f}')
# angle=60° (theta := radians(angle)) = 1.05, sin(theta) = 0.87, cos(theta) = 0.50

In the first print statement above, we use := to define variable today which is then reused on the same line saving us a repeated call to datetime.today().

Similarly, in the second example, we declare theta variable, which is then reused to compute sin(theta) and cos(theta). In this case we also use it in conjunction with what looks like a "reverse walrus" operator - this really is just = which forces the expression to be printed along its value, plus the : used for formatting the expression.

Notice also that the walrus expressions have to be surrounded by parentheses for f-string to interpret it correctly.

Any and All

You can use Python's any() and all() functions to verify whether any or all values in some iterable satisfy certain condition. What if you however want to also capture the value that caused any() to return True (so-called "witness") or the value that caused all() to fail (so-called "counterexample")?


numbers = [1, 4, 6, 2, 12, 4, 15]

# Only returns boolean, not the values
print(any(number > 10 for number in numbers))  # True
print(all(number < 10 for number in numbers))  # False

# ---------------------
any((value := number) > 10 for number in numbers)  # True
print(value)  # 12

all((counter_example := number) < 10 for number in numbers)  # False
print(counter_example)  # 12

Both any() and all() use short-circuiting to evaluate the expression. This means that they stop the evaluation as soon as they find the first "witness" or "counterexample" respectively. Therefore, with this trick the variable created by walrus operator will always give us the first "witness"/"counterexample".

Gotchas & Limitations

While I tried to motivate you to use walrus operator in previous sections, I think it's also important to warn you about some of its shortcomings and limitations. Following are the gotchas you might run into when using the walrus operator:

In the previous example you saw that short-circuiting can be useful for capturing values in any()/all(), but in some cases it might produce unexpected results:


for i in range(1, 100):
    if (two := i % 2 == 0) and (three := i % 3 == 0):
        print(f"{i} is divisible by 6.")
    elif two:
        print(f"{i} is divisible by 2.")
    elif three:
        print(f"{i} is divisible by 3.")

# NameError: name 'three' is not defined

In the above snippet, we've created a conditional with 2 assignments joined by and which check whether a number is divisible by 2, 3, or 6 based on whether first, second or both conditions are satisfied. At first glance it might seem like a nice trick, but due to short-circuiting, if the expression (two := i % 2 == 0) fails, the second part will be skipped and therefore three will be undefined or will have stale value from previous loop.

Short-circuiting can be beneficial/intended too though. We can use it with regular expressions to search for multiple patterns in a string:


import re

tests = ["Something to match", "Second one is present"]

pattern1 = r"^.*(thing).*"
pattern2 = r"^.*(present).*"

for test in tests:
    m = re.match(pattern1, test)
    if m:
        print(f"Matched the 1st pattern: {m.group(1)}")
    else:
        m = re.match(pattern2, test)
        if m:
            print(f"Matched the 2nd pattern: {m.group(1)}")

# Matched the 1st pattern: thing
# Matched the 2nd pattern: present

for test in tests:
    if m := (re.match(pattern1, test) or re.match(pattern2, test)):
        print(f"Matched: '{m.group(1)}'")
        # Matched: 'thing'
        # Matched: 'present'

We've already seen version of this snippet in the first section where we used if/elif in conjunction with walrus operator. Here we're simplifying it even further by reducing the conditional into single if.

If you're just getting familiar with walrus operator, you might notice that it causes variable scopes to behave differently in comprehensions:


values = [3, 5, 2, 6, 12, 7, 15]

tmp = "unmodified"
dummy = [tmp for tmp in values]
print(tmp)  # As expected, "tmp" was not clobbered - it's still bound to "unmodified"

total = 0
partial_sums = [total := total + v for v in values]
print(total)  # Prints: 50

With normal list/dict/set comprehensions, the loop variable does not leak into the surrounding scope and therefore any existing variables with same name will be unmodified. With walrus operator however, the variable from comprehension (total in the above code) remains accessible after comprehension returns, taking the value from inside comprehension.

When you become more comfortable using walrus in your code, you might try using it in more situations. One place where you should never use it though is with statement:


class ContextManager:
    def __enter__(self):
        print("Entering the context...")

    def __exit__(self, exc_type, exc_val, exc_tb):
        print("Leaving the context...")

with ContextManager() as context:
    print(context)  # None

with (context := ContextManager()):
    print(context)  # <__main__.ContextManager object at 0x7fb551cdb9d0>

When using the normal syntax with ContextManager() as context: ..., the context is bound to the return value of context.__enter__(), while if you use the version with :=, then it's bound to the result of ContextManager() itself. This oftentimes doesn't really matter because context.__enter__() usually returns self, but in case it doesn't it will create very hard to debug issues.

For a more practical example see below what happens when you use walrus operator with closing context manager:


from contextlib import closing
from urllib.request import urlopen

with closing(urlopen('https://www.python.org')) as page:
    for line in page:
        print(line)  # Prints website HTML

with (page := closing(urlopen('https://www.python.org'))):
    for line in page:
        print(line)  # TypeError: 'closing' object is not iterable

Another issue you might run into is the relative precedence of :=, which is lower than that of logical operators:


text = "Something to match."
flag = True

if match := re.match(r"^.*(thing).*", text) and flag:
    print(match.groups())  # AttributeError: 'bool' object has no attribute 'group'

if (match := re.match(r"^.*(thing).*", text)) and flag:
    print(match.groups())  # ('thing',)

Here we see that we need to wrap the assignment in parentheses to make sure that result of re.match(...) is assigned to the variable. If we don't, the and expression is evaluated first and boolean result will be assigned instead.

Finally, this really isn't a gotcha, but rather slight limitation. You currently cannot use inline type hints with walrus operator. Therefore, if you want to specify type of the variable, then you need to split it into 2 lines:


from typing import Optional

value: Optional[int] = None
while value := some_func():
    ...  # Do stuff

Closing Thoughts

Like every single other syntax feature, walrus operator can be abused and can decrease clarity and readability. You don't need to shove into you code wherever possible. Treat it as a tool - be aware of its advantages and disadvantages and use it where appropriate.

If you want to see more practical, good usages of walrus operator, check out how it got introduced to the CPython's standard library - all those changes can be found in this PR. Apart from that, I also recommend reading through the PEP 572 which has even more examples as well as rationale for the introduction of the operator.