Iterating over a custom object in python

A coworker recently needed to iterate over a custom object in python. It’s pretty easy to do, you just need to implement the __iter__ method on your object.

Here’s some example code that shows you how to extend your object, returning everything in your objects local dictionary:

class IterableObject(object):
    def __iter__(self):
        for item in self.__dict__:
            yield self.__dict__[item]

Now for sample usage:

myObj = IterableObject()
myObj.name = "Johnny Hammersticks"
myObj.otherProperty = "Something Else"
myObj.testList = [1,2,3,4]
myObj.testDict = {1:'one', 2:'two'}
# Serialize the IterableObject into json
for x in myObj:
     print x, type(x)

which returns:

Something Else <type 'str'>
{1: 'one', 2: 'two'} <type 'dict'>
[1, 2, 3, 4] <type 'list'>
Johnny Hammersticks <type 'str'>

Oh and another handy feature of this dictionary style approach, you can do easy string formatting/printing of the object properties in this style.

print "Hi %(name)s, your list %(testList)s" % myObj.__dict__

Which prints:

Hi Johnny Hammersticks, your list: [1, 2, 3, 4]
Posted: October 22nd, 2008
Categories: Code, python
Tags:
Comments: 2 Comments.
Comments
Comment from lefthand - April 13, 2010 at 4:31 am

This may be 2 years later.But i really want to say thank you .The blog post really made me understand so concept i amwas battling with

Comment from Chris - January 22, 2011 at 9:08 pm

Thank you for the tutorial, this was very useful.

After implementing your solution, realized I couldn’t find a way to access the declared name of an object member using your code snippet, so I modified it slightly.

In case anyone else had the same question:

for k, v in myObj.__dict__.iteritems():
print k, v, type(v).__name__