looping over all member variables of a class in python

Viewed 129942

How do you get a list of all variables in a class thats iteratable? Kind of like locals(), but for a class

class Example(object):
    bool143 = True
    bool2 = True
    blah = False
    foo = True
    foobar2000 = False

    def as_list(self)
       ret = []
       for field in XXX:
           if getattr(self, field):
               ret.append(field)
       return ",".join(ret)

this should return

>>> e = Example()
>>> e.as_list()
bool143, bool2, foo
9 Answers

@truppo: your answer is almost correct, but callable will always return false since you're just passing in a string. You need something like the following:

[attr for attr in dir(obj()) if not callable(getattr(obj(),attr)) and not attr.startswith("__")]

which will filter out functions

Similar to vars(), one can use the below code to list all class attributes. It is equivalent to vars(example).keys().

example.__dict__.keys()
ClassName.__dict__["__doc__"]

This will filter out functions, in-built variables etc. and give you just the fields that you need!

row2dict = lambda r: {c.name: str(getattr(r, c.name)) for c in r.__table__.columns} if r else {}

Use this.

Related