SaltyCrane Blog — Notes on JavaScript and web development

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 __dict__ attribute:

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
Results:
myinstatt2 two
myinstatt1 one

Comments


#1 Dave commented on :

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 :

Thanks for this useful example you provided. I always find seeing simple examples to be the easiest way to learn.


#3 dan commented on :

Nice example.

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 :

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 :

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 :

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 :

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 :

Z: Agree vars() is more pythonic. I just learned about that recently. Thanks for the tip!


#9 hangtwenty commented on :

I always find myself forgetting this idiom, thanks for making it easy to find again.


#10 Paxwell commented on :

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.

Merry Christmas,

-Paxwell


#11 Brett commented on :

This article was the last stop on a very long search for me. Thank you so much.


#12 random commented on :

Many thanks for this concise and helpful post - had no idea I could get a free dict for my custom class. Lovely!