Humus
Humus

Reputation: 95

Iterating Over Elements in Objects

Python iterating through object attributes

I found this question when trying to understand iteration over Objects, and found this response from Eric Leschinski:

class C:
    a = 5
    b = [1,2,3]
    def foobar():
        b = "hi"   

c = C

for attr, value in c.__dict__.iteritems():
    print "Attribute: " + str(attr or "")
    print "Value: " + str(value or "")

Which produced text that listed all attributes in class C, including functions and hidden attributes (surrounded by underscores) as seen below:

python test.py
Attribute: a
Value: 5
Attribute: foobar
Value: <function foobar at 0x7fe74f8bfc08>
Attribute: __module__
Value: __main__
Attribute: b
Value: [1, 2, 3]
Attribute: __doc__
Value:

Now, I understand how to filter out the 'hidden' attributes from my iteration, but is there a way to filter out all functions as well? Effectively, I'm looking for, in class C, only attributes a and b, listed sequentially, without the __module__ and __doc__ information and without any and all functions that happen to be in C.

Upvotes: 0

Views: 228

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121924

You'll have to filter on type; function objects are attributes just like the rest. You could use the inspect.isfunction() predicate function here:

import inspect

for name, value in vars(C).iteritems():
   if inspect.isfunction(value):
       continue
   if name[:2] + name[-2:] == '____':
       continue

You could use the inspect.getmembers() function with a custom predicate:

isnotfunction = lambda o: not inspect.isfunction(o)
for name, value in inspect.getmembers(C, isnotfunction):
   if name[:2] + name[-2:] == '____':
       continue

Upvotes: 2

Related Questions