Search⌘ K
AI Features

Sending and Receiving

Explore how to send and receive data within Python generators using yield and send. Understand generator execution suspension, noop operations to advance execution, and how to use loops for sending values effectively in asynchronous programming.

We'll cover the following...

Sending & Receiving

Consider the snippet below:

def generate_numbers():
    i = 0
    while True:
        i += 1
        yield i
        k = yield
        print(k)

You may be surprised how this snippet behaves when we send and receive data.

  1. First we create the generator object as follows:

       generator = generate_numbers()
    

    Remember creating the generator object doesn't run the generator function.

  2. Next, we start the generator by invoking next(). We'll receive a value from the generator function since the first ...