DEV Community

Kaushit
Kaushit

Posted on

πŸ“š Understanding the Iterator Pattern in Python! πŸπŸ’‘

The Iterator Pattern is a behavioural design pattern that provides a way to access elements of a collection (or aggregate) sequentially without exposing the underlying representation of the collection. It decouples the algorithm for traversing the collection from the actual collection implementation, promoting a more flexible and generic approach to iteration.

Python already provides built-in support for the Iterator Pattern through its iterables and iterators. Many objects in Python, such as lists, tuples, dictionaries, and strings, are iterables, meaning they can be used in a for loop directly. Behind the scenes, these objects use iterators to enable sequential access to their elements.

In Python, the Iterator Pattern is applied implicitly through two protocols:

  1. Iterable Protocol: An object is considered iterable if it defines the __iter__() method, which returns an iterator object.

  2. Iterator Protocol: An iterator is an object that defines the __next__() method, which returns the next element in the collection. Additionally, it must raise the StopIteration exception when there are no more elements to be returned.

Let's see a simple example of how the Iterator Pattern is used in Python:


class NonIterable:

  pass



class IterableWithNonIterator(NonIterable):

  def __iter__(self):

    class NonIterator:

      pass

    return NonIterator()



class IterableWithIterator(NonIterable):

  def __iter__(self):

    class Iterator:

      def __next__(self):

        return None

    return Iterator()



try:

  iter(NonIterable()) # Raises TypeError as NonIterable is not iterable

except TypeError as e:

  pass



try:

  not_iterator = iter(IterableWithNonIterator())

  next(not_iterator) # Raises TypeError as IterableWithNonIterator's iterator is not defined

except TypeError as e:

  pass



iterator = iter(IterableWithIterator())

next(iterator) # Returns None as IterableWithIterator provides a valid iterator



Enter fullscreen mode Exit fullscreen mode

Overall, the Iterator Pattern is an essential concept in Python, enabling you to easily iterate over various collections in a consistent and flexible manner. It provides an elegant way to handle iteration, promoting separation of concerns and a clear distinction between the iteration logic and the collection's implementation details.

Top comments (0)