In this tutorial, we are going to see how to create an Iterable class in Python.
Python Iterable Class:
An iterator is an object that can be iterated through all the values in the object. In python Lists, tuples, dictionaries, and sets are all iterable objects, these are all can be iterate over the values.
The iter() is a method used to get the iterator from List, tuple, dictionary and set objects, through which the items are get iterated.
How to create Python Iterable class?
By default, all python classes are not iterable so that we can not traverse/iterate the values of the python class. To make a class as iterable, you have to implement the
__next__() methods in that class.
__iter__() method allows us to make operations on the items or initializing the items and returns an iterator object.
__next__() method allows us to do operations and it should return the next value of the sequence.
Iterable class in Python Example:
To make the example as simple, I am taking a simple use-case – Creating a class that allows iterating over a range of provided dates, and it always produces one day at a time on every loop.
from datetime import timedelta, date class DateIterable: def __init__(self, start_date, end_date): # initilizing the start and end dates self.start_date = start_date self.end_date = end_date self._present_day = start_date def __iter__(self): #returning __iter__ object return self def __next__(self): #comparing present_day with end_date, #if present_day greater then end_date stoping the iteration if self._present_day >= self.end_date: raise StopIteration today = self._present_day self._present_day += timedelta(days=1) return today if __name__ == '__main__': for day in DateIterable(date(2020, 1, 1), date(2020, 1, 6)): print(day)
2020-01-01 2020-01-02 2020-01-03 2020-01-04 2020-01-05
The above example iterates the days between the start and end days. The for loop creates an iterator object and executes the
next() method for each loop, that’s why we see them each day in a separate line.
StopItertion is used to prevent the iteration, usually, we prevent the iteration on a specific condition.