How to iterate over an instance object's data attributes in Python
To list the attributes of a Python instance object, I could use the built-in
dir() function, however, this will return the instance object's methods as well data attributes. To get just the data attributes, I can use the instance object's
class A(object): def __init__(self): self.myinstatt1 = 'one' self.myinstatt2 = 'two' def mymethod(self): pass a = A() for attr, value in a.__dict__.iteritems(): print attr, value
myinstatt2 two myinstatt1 one
12 Comments — Comments feed for this post
#1 Dave commented on 2010-07-30:
I just tried _ _ dict _ _ (take out spaces) on a Django entity and got an error "'str' object has no attribute '_meta'". Guess I'll keep looking for a way to iterate database fields only for my Django entity?
-- Trindaz/Python on Fedang
#2 John commented on 2011-01-19:
Thanks for this useful example you provided. I always find seeing simple examples to be the easiest way to learn.
#3 dan commented on 2011-09-18:
Suppose you have a class with class variables, e.g.
class Foo(object): one = 1 letter = "a"
How do you iterate over 'one' and 'letter'?
#4 Z commented on 2012-02-08:
There is a function that exposes the
__dict__ method. It's equivalent, but probably more pythonic.
The vars built-in function http://docs.python.org/library/functions.html#vars
for k, v in vars(a).items(): print k, v myinstatt2 two myinstatt1 one
#5 Dave commented on 2012-03-09:
When I use the vars(a) method illustrated by Z on a generic namespace, I get the data elements, but I also get a "trash" element akin to:
<__main__.Fragment instance at 0x009DE56C>
Is there any simple way to suppress this?
#6 Alvin Mites commented on 2012-06-20:
Find myself referencing this blog quite a bit. Thank you for the shares over the years, like to think I'll get back into the habit of writing to my bog sometime and think the regular examples here will help move that forward.
#7 Eliot commented on 2012-06-25:
Hi Alvin, Thanks! That would be great if you started writing more blog posts. There are a lot of people that have a lot of information that I wish would write blog posts.
#8 Eliot commented on 2012-06-25:
Z: Agree vars() is more pythonic. I just learned about that recently. Thanks for the tip!
#9 hangtwenty commented on 2012-11-03:
I always find myself forgetting this idiom, thanks for making it easy to find again.
#10 Paxwell commented on 2012-12-03:
Hey I really appreciate your blog. I have found no other place that answers so many of my Python questions so quickly. Just want to say thank you and keep it up.
#11 Brett commented on 2013-03-06:
This article was the last stop on a very long search for me. Thank you so much.
#12 random commented on 2013-04-02:
Many thanks for this concise and helpful post - had no idea I could get a free dict for my custom class. Lovely!