Treading on Python - II - Book Summary
The following post contains a summary of the book titled Treading on Python II by Matt Harrison
Programming Styles
- Python supports three types of programming paradigms
- Imperative/Procedural
- Object Oriented
- Declarative/Functional
Iterator Protocol
iteris a global built-in function that calls the object’s dunder method__iter__- Writing a
forloop based on iterators
| |
- Each loop is converted in to byte code and this byte code is run by the interpreter
- The actual iterator is not the object that is being iterated.
listandstringhave separate iterator objects to iterate upon them StringIOclass implements the iterator protocol- Iterator protocol defines the process of iterating the objects in a container utilizing the methods
__iter__and__next__
Iterable vs. Iterator
- What is an iterable ? An iterable is any object that allows iteration
- This object must implement
__iter__method and must return an iterator object. This iterator object can be the same object or a completely different object - This object must also implement
__next__method
- This object must implement
- Iterators are good for one pass over the values. This means that iterators are stateful
range(10)returns anrangeiteratorobject that implements__iter__and__next__methods- A class is called a
self-iteratorif its__iter__method returns the same instance on which the dunder method has been invoked - Most iterable objects are not
self-iterators. They return a different object when their__iter__method is invoked - If the datatype is a self-iterator, then there could be problems in nested loops. Here is a nice example
| |
The above code does not work as desired as the iter returns the same instance and the inner loop goes through only once and never gets repeated. The solution to this problem is to make sure that the iter method returns a different object as compared to the original object on which the method was invoked

