Simple Iterable Objects in Python

Sometimes the python documentation can give too many details such that its difficult to get answers to simple questions. One that I’ve just worked through is “[iterable objects][0].” For example, if you have an object called Family and you want to display a list of all the members of that family, you might use this code:

family = Family(‘Nuzums’)
for person in family:
print person['first_name']

Shouldn’t be hard, right? Its not, once you figure it out. You start out with your usual class definition, then you need to add the following methods:

* **`next(self)`**: returns the next item from the list
* **`__getitem__(self, item)`**: returns a specific item from the list
* **`__iter__(self)`**: returns `self` assuming you’ve added the above two methods

Here’s an example:

class Family:
def __init__(self, last_name):
if last_name == ‘Nuzums’:
self.members = (
{‘first_name’: ‘mommy’},
{‘first_name’: ‘daddy’},
{‘first_name’: ‘son’},
{‘first_name’: ‘daughter’},
)
self.count = 0
def next(self):
if self.count >= len(self.members):
self.count = 0
raise StopIteration
else:
c = self.count
self.count = c + 1
return self.members[c]
def __getitem__(self, item):
return self.members[item]
def __iter__(self):
return self

That should do it. Note there’s nothing magical about the use of the word ‘members’ above. As long as `next` and `__getitem__` know what to do, the magic is done. This example is extremely simple. If you have some enhancements to suggest, please post them as a comment.

[0]: http://docs.python.org/lib/typeiter.html