DEV Community

Somenath Mukhopadhyay
Somenath Mukhopadhyay

Posted on

Iterator Design Pattern in Python...

Iterator design pattern is a behavioral design pattern that lets you access the element of a complex data structure - a collection class - without the knowledge of the internal structure of the elements it is accessing.

To create an iterator in Python, there are two abstract classes from the built-in collections module - Iterable, and Iterator. We need to implement the

__iter__() method in the iterated object (collection), and the __next__ () method in the iterator.

The concrete class that implements the Iterator class provides various means of different ways of iteration through the collection class.

In our example, AlphabeticalOrderIterator is such a class that has provided forward and reverse ways of iteration. In this example, the WordsCollection class represents a collection of words and implements the Iterable interface.

The source code is as follows:

from collections.abc import Iterator, Iterable
from typing import Any, List

class WordsCollection(Iterable):
    """
    A collection class that can be iterated upon.
    """
    def __init__(self, collection: List[Any] = []):
        self._collection = collection

    def __iter__(self) -> Iterator:
        """
        Returns an iterator for the collection.
        """
        return AlphabeticalOrderIterator(self._collection)

    def get_reverse_iterator(self) -> Iterator:
        """
        Returns a reverse iterator for the collection.
        """
        return AlphabeticalOrderIterator(self._collection, True)

    def add_item(self, item: Any):
        """
        Adds an item to the collection.
        """
        self._collection.append(item)

class AlphabeticalOrderIterator(Iterator):
    """
    An iterator for a collection that traverses in alphabetical order.
    """
    _position: int = 0
    _reverse: bool = False

    def __init__(self, collection: List[Any], reverse: bool = False):
        self._collection = sorted(collection)  # Sort the collection for alphabetical order
        self._reverse = reverse
        self._position = len(self._collection) - 1 if self._reverse else 0

    def __next__(self) -> Any:
        """
        Returns the next item in the collection.
        """
        try:
            value = self._collection[self._position]
            self._position += -1 if self._reverse else 1
            return value
        except IndexError:
            raise StopIteration()

if __name__ == '__main__':
    wordsCollection = WordsCollection()
    wordsCollection.add_item("Som")
    wordsCollection.add_item("Reema")
    wordsCollection.add_item("Ridit")

    print("Forward traversal:")
    # The default iterator will be used here, which is set to return items in alphabetical order
    print("\n".join(iter(wordsCollection)))
    print("")

    print("Reverse traversal:")
    print("\n".join(wordsCollection.get_reverse_iterator()), end="")
Enter fullscreen mode Exit fullscreen mode

If we run the above program the output will be as follows:

Forward traversal:

Som

Reema

Ridit

Reverse traversal:

Ridit

Reema

Som

Top comments (0)