Course contentsShow
← Python
Lesson 319 of 1,0605. Advanced Iteration and ComprehensionsFree lesson

Refactoring Iterative Code into Generator Coroutines

You will refactor imperative loops into clean, decoupled coroutine structures to improve the maintainability and scalability of your codebase.

In this lesson, you will learn how to transform rigid, imperative loops into flexible, decoupled generator coroutines that allow you to control data flow dynamically.

Moving Beyond the Loop

When you write a standard loop, your logic is tightly coupled. If you have a process that gathers data, filters it, and then acts on it, a single for loop forces all those steps to happen in one place. By refactoring this into a generator coroutine, you separate the collection of data from the processing of data.

A coroutine is essentially a generator that you use as a data sink. Instead of pulling values from a sequence, you "push" values into it using the .send() method.

Refactoring Example

Imagine you are filtering log messages. The imperative approach looks like this:

logs = ["INFO: start", "ERROR: crash", "INFO: end"]
for log in logs:
    if "ERROR" in log:
        print(f"Processing: {log}")

This works, but what if you want to reuse the filtering logic elsewhere or handle streaming data? Let’s refactor this into a coroutine:

def error_processor():
    while True:
        log = yield  # Wait for a value to be sent in
        if "ERROR" in log:
            print(f"Processing: {log}")

# Initialize the coroutine
processor = error_processor()
next(processor)  # Advance to the first 'yield'

# Send data into the pipeline
logs = ["INFO: start", "ERROR: crash", "INFO: end"]
for item in logs:
    processor.send(item)

Why Refactor?

By shifting to this structure, your error_processor becomes a self-contained component. It doesn't care where the logs come from—it could be a file, a network socket, or a list. Because the coroutine maintains its own internal state, you can pause execution, perform other tasks, and resume exactly where you left off. This decoupling makes your code significantly easier to test, modify, and scale as your application grows in complexity.

Key Takeaway: Refactoring iterative loops into coroutines transforms your code from a rigid execution sequence into a flexible, stateful pipeline where data is pushed into independent, reusable processing units.