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

推荐订阅源

U
Unit 42
T
Threatpost
C
CERT Recently Published Vulnerability Notes
Recent Commits to openclaw:main
Recent Commits to openclaw:main
Security Archives - TechRepublic
Security Archives - TechRepublic
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
K
Kaspersky official blog
Application and Cybersecurity Blog
Application and Cybersecurity Blog
Attack and Defense Labs
Attack and Defense Labs
N
News and Events Feed by Topic
Project Zero
Project Zero
H
Heimdal Security Blog
C
Cybersecurity and Infrastructure Security Agency CISA
Know Your Adversary
Know Your Adversary
Google Online Security Blog
Google Online Security Blog
W
WeLiveSecurity
D
Darknet – Hacking Tools, Hacker News & Cyber Security
Schneier on Security
Schneier on Security
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
N
News | PayPal Newsroom
Hacker News - Newest:
Hacker News - Newest: "LLM"
H
Hacker News: Front Page
L
LINUX DO - 热门话题
Spread Privacy
Spread Privacy
T
Threat Research - Cisco Blogs
Cloudbric
Cloudbric
V
Vulnerabilities – Threatpost
Hacker News: Ask HN
Hacker News: Ask HN
S
Securelist
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
TaoSecurity Blog
TaoSecurity Blog
NISL@THU
NISL@THU
N
News and Events Feed by Topic
S
Security Affairs
The Last Watchdog
The Last Watchdog
T
Tor Project blog
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
T
The Exploit Database - CXSecurity.com
Simon Willison's Weblog
Simon Willison's Weblog
P
Palo Alto Networks Blog
AWS News Blog
AWS News Blog
P
Proofpoint News Feed
C
Cisco Blogs
C
Cyber Attacks, Cyber Crime and Cyber Security
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
L
LINUX DO - 最新话题
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
T
Tenable Blog
C
CXSECURITY Database RSS Feed - CXSecurity.com
S
Schneier on 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 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 You Should Be Using Python's Walrus Operator - Here's Why 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
Lazy Evaluation Using Recursive Python Generators
Martin · 2023-01-05 · via Martin Heinz's Blog

We all are familiar with Python's generators and all their benefits. But, what if I told you that we can make them even better by combining them with recursion? So, let's see how we can use them to implement "lazy recursion" and supercharge what we already do with generators in Python!

Why Even Bother?

Before we get into the code, let's first ask ourselves "Why even bother? Do we really need recursive generators?". And the answer is... it depends. Naturally, a recursive generator will share both pros and cons of both generators as well as normal recursive functions.

For the generators, the number one reason why one would use them is "lazy" evaluation - that is - computing elements one at the time rather than all at once. As for the recursion, it simply makes sense for certain algorithms or problems which it can solve elegantly and succinctly, such as tree traversal.

Therefore, a situations where recursive generators would make sense are naturally recursive algorithms that might process large amount of data or elements, and therefore consume a lot of memory if run "eagerly".

The Basic Example

Now that we know why we would use a recursive generator, let's take a look at a "simple" example to understand how we can write one:


def binary_counter():
    yield "1"
    for prefix in binary_counter():
        yield prefix + "0"
        yield prefix + "1"

This short function - as the name suggests - yields successive numbers in binary. When called, it first simply yields "1" and after which comes the recursive call. The recursive call also yields "1", but that's given to the previous, non-recursive call as a prefix. With the prefix computed, the non-recursive call yields 2 values "10" and "11". After that, the recursive call continues execution by making another recursive call, going a level deeper and so the loop continues - prefixes bubble upwards so the outer frame is always yielding some result ending first with "0" and then "1".

Now, if we were to run it, we would get:


for value in binary_counter():
    print(f"value: {value}")
    if value == "1000":
        break

# value: 1
# value: 10
# value: 11
# value: 100
# value: 101
# value: 110
# value: 111
# value: 1000

When it comes to recursion, explaining the code isn't always sufficient for really understanding what's happening. So, if you're not sure how the binary_counter actually works, then let's try working out individual steps:


def _binary_counter(depth=0):
    print(f'First "yield" at depth {depth}.')
    yield "1", depth
    for prefix, d in _binary_counter(depth+1):
        print(f'First recursive "yield" at depth {depth}.')
        yield prefix + "0", d
        print(f'Second recursive "yield" at depth {depth}.')
        yield prefix + "1", d

for value, depth in _binary_counter():
    print(f"value: {value}, depth: {depth}")
    if value == "1000":
        break

The above, modified version adds a depth parameter and a couple of prints to help demonstrate what the code does. If we now call this code, we will get the following:


# First "yield" at depth 0.
# value: 1, depth: 0
# First "yield" at depth 1.
# First recursive "yield" at depth 0.
# value: 10, depth: 1
# Second recursive "yield" at depth 0.
# value: 11, depth: 1
# First "yield" at depth 2.
# First recursive "yield" at depth 1.
# First recursive "yield" at depth 0.
# value: 100, depth: 2
# Second recursive "yield" at depth 0.
# value: 101, depth: 2
# Second recursive "yield" at depth 1.
# First recursive "yield" at depth 0.
# value: 110, depth: 2
# Second recursive "yield" at depth 0.
# value: 111, depth: 2
# First "yield" at depth 3.
# First recursive "yield" at depth 2.
# First recursive "yield" at depth 1.
# First recursive "yield" at depth 0.
# value: 1000, depth: 3

I hope this makes it a bit clearer, if not, consider manually working out the steps, or maybe using debugger in your IDE of choice, so that you can see the stack frames and variables in realtime.

You might be also asking, "What's the point of computing binary numbers this way?" - and the answer is, well, there's no good reason. There are definitely better and more readable ways to do that, but I think it demonstrates the concept fairly well. With that said, let's now look at more useful examples of how we can use recursive generators...

Putting It To Good Use

When it comes to recursion, the obvious candidates for examples are various mathematical functions or - as shown here - combinatorics, more specifically power-set:


def powerset(sequence):
    if len(sequence) == 1:
        yield sequence
        yield []
    else:
        for item in powerset(sequence[1:]):
            yield [sequence[0]] + item
            yield item

for s in powerset(list(range(4))):
    print(s)

# [0, 1, 2, 3]
# [1, 2, 3]
# [0, 2, 3]
# [2, 3]
# [0, 1, 3]
# [1, 3]
# [0, 3]
# [3]
# ...

The function here uses similar flow as the binary counter earlier. To better understand it, we can translate the recursive part as:

  • For every result in a smaller power-set (sequence[1:]) ...
  • ... Return the not used value ([sequence[0]]) + the result (item)
  • ... Then return result alone (item)

While mathematical functions can be nicely implemented using recursion, they aren't really something we use on daily basis, so let's now take a look at something different:


def accumulate(values):
    yield values[0]
    if len(values) > 1:
        values[1] += values[0]
        yield from accumulate(values[1:])

for val in accumulate([1, 2, 3, 4]):
    print(val)

The above accumulate function computes a running total (sum) of elements of its list parameter. While the above code works, I don't recommend using it in practice, because you can and should use the following instead:


from itertools import accumulate

print(list(accumulate([1, 2, 3, 4])))

While on the topic of itertools, let's also see how we can re-implement other common function:


def flatten(nested):
    try:
        for sublist in nested:
            yield from flatten(sublist)
    except TypeError:
        yield nested

print(list(flatten([[1, 2], 3])))

The flatten function can be used to un-nest a nested list (or other iterable). I show this one here because it uses a bit of a different flow than the earlier ones - it leverages try/except to separate the base/non-recursive part and the recursive code.

It can however, be rewritten without try/expect if desired:


from collections.abc import Iterable

def flatten(nested):
    if not isinstance(nested, Iterable):
        yield nested
    else:
        for sublist in nested:
            yield from flatten(sublist)

print(list(flatten([[1, 2], 3])))

When talking about recursion, we obviously have to show an examples of recursive data structures, in this case a binary tree:


from typing import Optional
from dataclasses import dataclass

@dataclass
class Node:
    data: int
    left: Optional[Node] = None
    right: Optional[Node] = None

    def __iter__(self):
        if self.left:
            yield from self.left
        yield self.data
        if self.right:
            yield from self.right

def inorder(node):
    if node:
        yield from inorder(node.left)
        yield node.data
        yield from inorder(node.right)

The above code implements a binary tree, including the recursive generator in a form of the __iter__ method. The same is also implemented in the inorder function, which makes the recursive calls a little clearer.

To demonstrate the usage of the above code, let's create a simple tree:


t3 = Node(data=5)
t5 = Node(data=32)
t4 = Node(data=10)
t1 = Node(data=8, left=t3, right=t4)
t2 = Node(data=35, right=t5)
tree = Node(left=t1, right=t2, data=20)

#      tree
#     /    \
#    t1    t2
#   /  \     \
#  t3  t4    t5

for node in tree:
    print(node)

# 5
# 8
# 10
# 20
# 35
# 32

Similar to the traversal of (binary) trees, we can use recursive generators also for examples when traversing JSON:


def traverse_json(parent, data, depth=0):
    for key, value in data.items():
        if not isinstance(value, dict):
            print(f"{' ': <{depth*2}}{parent}: {key} -> {value}")
            yield key, value
        else:
            yield from traverse_json(key, value, depth + 1)

Traversing JSON this way might be practical if you're working with very large data that would consume a lot of memory if loaded all at once.

By now, you might be getting the hang of how these weird generators work, but let's anyway look at what happens when we call the above code:


nested_dict = {
    "A": {
        "A1": "data",
        "C": {"C1": "some value"}
    },
    "B": {
        "B1": "more data",
        "D": {
            "D1": "another value",
            "E": {"E1": "data", "E2": "even more data"}
        }
    }
}

print(list(traverse_json(None, nested_dict)))

#   A: A1 -> data
#     C: C1 -> some value
#   B: B1 -> more data
#     D: D1 -> another value
#       E: E1 -> data
#       E: E2 -> even more data

# [
# ('A1', 'data'), ('C1', 'some value'), ('B1', 'more data'),
# ('D1', 'another value'), ('E1', 'data'), ('E2', 'even more data')
# ]

And finally, another tree-like data structure which is commonly traversed recursively is a file-tree:


# Pointless, but recursive:
from pathlib import Path

def get_paths(path):
    if path.is_file():
        yield path
    elif path.is_dir():
        for subpath in path.glob("*"):
            yield from get_paths(subpath)

for p in get_paths(Path("/some/path")):
    ...  # Do something with path

# Realistic solution:
path = Path("/some/path")
for p in path.rglob("*"):
    ...  # Do something with path

Here we implement get_paths function that recursively yields all files in specified path. With that said, you're better off using the builtin path.rglob("*") for this task as it also returns generator.

Also, while not useful in this instance, it's good to note that send() function can be also used with recursive generators. So, an alternative implementation of above function:


def get_paths(path):
    if path.is_file():
        yield path
    elif path.is_dir():
        for subpath in path.glob("*"):
            walker = get_paths(subpath)

            while True:
                try:
                    x = walker.send(None)
                except StopIteration:
                    break
                yield x

for p in get_paths(Path("/some/path")):
    print(p)

This style of generator can be useful in case you need to control the recursion or if you need to communicate with the coroutine.

Conclusion

The examples in this article - in my opinion - show an elegant solutions to many problems that can be expressed recursively. However, elegant doesn't always mean better. Oftentimes, using less "elegant" or succinct solution will produce much more readable and generally better code.

So, let's not try to "shoehorn" recursive generators into code wherever possible and only use it where appropriate - that is - when implementing a recursive function that would benefit from lazy evaluation.