Skip to Content
Clean Code in Python
book

Clean Code in Python

by Mariano Anaya
August 2018
Intermediate to advanced
332 pages
9h 12m
English
Packt Publishing
Content preview from Clean Code in Python

Creating iterable objects

When we try to iterate an object, Python will call the iter() function over it. One of the first things this function checks for is the presence of the __iter__ method on that object, which, if present, will be executed.

The following code creates an object that allows iterating over a range of dates, producing one day at a time on every round of the loop:

from datetime import timedeltaclass DateRangeIterable:    """An iterable that contains its own iterator object."""    def __init__(self, start_date, end_date):        self.start_date = start_date        self.end_date = end_date        self._present_day = start_date    def __iter__(self):        return self    def __next__(self):        if self._present_day >= self.end_date:            raise StopIteration today = self._present_day ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Clean Code in Python - Second Edition

Clean Code in Python - Second Edition

Mariano Anaya
Python for Programmers

Python for Programmers

Paul Deitel, Harvey Deitel

Publisher Resources

ISBN: 9781788835831Supplemental Content