Course contentsShow
← Python
Lesson 636 of 1,06010. Advanced Language FeaturesFree lesson

Creating Custom Iteration Wrappers for Existing Objects

You will wrap standard collection types with custom iteration logic to provide specialized views or filtered access to existing data structures.

In this lesson, you will learn how to build specialized "views" over existing data structures by wrapping them in custom iteration logic.

Often, you might have a standard collection, like a list or dict, but you need to iterate over it in a specific way—perhaps skipping certain elements, transforming values on the fly, or filtering data without modifying the original object. Instead of creating a whole new copy of the data, you can create a wrapper class that implements the Iterator Protocol (__iter__ and __next__) to provide a custom perspective on the underlying data.

The Wrapper Pattern

The core idea is to hold a reference to the existing object inside your class and manage the iteration state internally. This approach is highly memory-efficient because you aren't duplicating the collection; you are simply defining a new "pathway" to access its contents.

Consider a case where you want to iterate over a list of numbers but only return the squares of even values:

class EvenSquareIterator:
    def __init__(self, data):
        self.data = data
        self.index = 0

    def __iter__(self):
        return self

    def __next__(self):
        while self.index < len(self.data):
            val = self.data[self.index]
            self.index += 1
            if val % 2 == 0:
                return val ** 2
        raise StopIteration

By wrapping the data list, you gain control over the iteration lifecycle. When you pass a list to EvenSquareIterator, the logic inside __next__ handles the filtering and calculation lazily. The original list remains untouched, and the wrapper behaves exactly like any other iterable in a for loop.

This technique is powerful because it keeps your business logic separate from your data storage. You can create multiple wrappers for the same object—one for filtering, one for transformation, and one for batching—allowing for a highly modular architecture where the underlying data source doesn't need to know how it is being consumed.

Key Takeaway: By implementing the Iterator Protocol in a wrapper class, you can provide specialized, memory-efficient views of existing data structures without altering the original objects.