Mastering Python Generators: Understanding the send() Method for Advanced Control

Explore how the send() method empowers generators with two-way communication, enhancing flexibility and control in your Python programs

Max N
2 min readApr 11, 2024

Generators in Python offer a convenient way to lazily produce values, but did you know they also support bidirectional communication? In this article, we’ll delve into the powerful ‘send()’ method, unlocking new possibilities for controlling and interacting with generators.

Introducing the send() Method

The ‘send()’ method allows you to send data into a generator and control its execution from the outside. It complements the ‘yield’ statement by enabling communication between the caller and the generator.

Basic Usage

Let’s start with a simple example to illustrate how the ‘send()’ method works:

def echo():
while True:
received = yield
print("Received:", received)

# Creating a generator
gen = echo()

# Starting the generator
next(gen)

# Sending data into the generator
gen.send("Hello, world!")

In this code snippet, the ‘echo()’ generator echoes back whatever data it receives via the…

--

--

Max N
Max N

Written by Max N

A writer that writes about JavaScript and Python to beginners. If you find my articles helpful, feel free to follow.