Python Iterator Protocol

Python Iterator protocol

 

Any object in Python can be made to hold multiple values and those values can be retrieved in a uniform manner. An object that is designed to hold multiple values is generally called a container.

 

for element in CustomList:

    print(element)

   

The above for loop with the pattern,

 

        for <element> in <container>

 

is the standard way of retrieving values from any container in Python -  be it a container like list, dict from Python Standard Library or a user defined container like CustomList.

 

Iterable Object:

  • If a developer wants to design containers whose values are accessible in the same python way as above,  then such container classes need to implement __iter__() method.

 

  • The __iter__() method returns an iterator object.

 

  • Thus any container with an __iter__() method is an Iterable Object in Python.

 

Iterator Object:

  • The iterator object in python is an object that has the __next__() method implemented.
  • On each call, the __next__() method returns a value from the iterable object.

 

__next__() method:

 

  • On each invocation __next__() returns one value from the iterable/collection.

 

  • A StopIteration exception is raised when there are no more elements to be retrieved in the iterable object.

Example Container that implements python iterator protocol:

# Hashlist is both an iterable and an iterator in this example

class HashList:

    myData = []

    myPos  = 0

 

    def __init__(self, aData_in):

        self.myData = aData_in

   

    # Makes HashList an iterable 

    def __iter__(self):

        return self

 

    # Makes HashList an iterator

    def __next__(self):

        #hash the value before it is returned

        if self.myPos >= len(self.myData):

            raise StopIteration

 

        hashValue = hash(self.myData[self.myPos])

        self.myPos = self.myPos + 1

        return hashValue

       

       

HashListObject = HashList(["Two","Three","Five","Seven","Eleven"])

 

# print the hash list

for elem in HashListObject:

    print(elem)

 

Output:

-2240371794396141377

-4748626163865712805

-4847935018717398736

6822123111827422468

-52656924795627100

 


Copyright 2019 © pythontic.com