135

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
priestc
  • 33,060
  • 24
  • 83
  • 117
  • Why can't use use `for field in [ self.bool143, self.bool2, self.blah, self.foo, self.foobar2000 ]`? How does it happen that you don't know the instance variables of the class? – S.Lott Sep 09 '09 at 11:52
  • 4
    S.Lott: thats what I ended up doing anyways. In my real code, I have like 40 variables, and I thought it'd be better and more DRY to not have to manually make the iteration list. – priestc Sep 10 '09 at 01:43
  • 3
    Possible duplicate of [Iterate over object attributes in python](https://stackoverflow.com/questions/11637293/iterate-over-object-attributes-in-python) – Trevor Boyd Smith Nov 09 '17 at 16:09
  • Related: [python - Is there a built-in function to print all the current properties and values of an object? - Stack Overflow](https://stackoverflow.com/questions/192109/is-there-a-built-in-function-to-print-all-the-current-properties-and-values-of-a) – user202729 Feb 04 '21 at 00:11

8 Answers8

205
dir(obj)

gives you all attributes of the object. You need to filter out the members from methods etc yourself:

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

example = Example()
members = [attr for attr in dir(example) if not callable(getattr(example, attr)) and not attr.startswith("__")]
print members   

Will give you:

['blah', 'bool143', 'bool2', 'foo', 'foobar2000']
mthurlin
  • 26,247
  • 4
  • 39
  • 46
  • 13
    why instantiate an object: dir(Example()) instead of just the class type dir(Example) – Erdal Apr 30 '11 at 22:53
  • 2
    because I'm guessing the OP is looking for instance variables (which might not be present in the class). – mthurlin May 15 '11 at 17:57
  • 9
    and how do you get the values? – knutole Jan 18 '13 at 08:20
  • 8
    @knutole: getattr(object, attr) – opello Jan 13 '14 at 15:36
  • 8
    How does `callable(attr)` work? Isn't `attr` a string? – cubuspl42 Jul 08 '14 at 10:37
  • 7
    you should have used `vars(Example).items()` or `vars(instance.__class__).items()` instead of `dir()` if you want to check if its callable or not because dir will only return '`string`s as names.. – rrw Mar 26 '16 at 16:44
  • 1
    truppo, please update your answer, see below answer about why callable(attr) doesn't work – ikku100 Jan 26 '17 at 13:41
  • `ClassName.__dict__["__doc__"]` This will filter out functions, in-built variables etc. and give you just the fields that you need! – Hyuga Hinata Aug 24 '21 at 02:04
  • @Hyuga Hinata. ClassName.\_\_dict_\_\_["\_\_doc\_\_"] is not guaranteed to contain anything. It just contains the DocString at the top of the class. Checking instance.\_\_dict\_\_ can show all instance level attributes (including those not defined in the Class itself, but added to the instance.) However, it will return an AttributeError if the class is defined as using \_\_slots\_\_, and you don't add \_\_dict\_\_ as one of the slots. – nigh_anxiety Jun 08 '22 at 15:18
156

If you want only the variables (without functions) use:

vars(your_object)
Nimo
  • 7,984
  • 5
  • 39
  • 41
  • 5
    You still need to filter __vars__ but this is the correct answer – gaborous Aug 10 '14 at 20:16
  • 3
    really like this approach gonna use it to find out what to serialise before sending states over network for instance... – Thom Apr 13 '15 at 11:17
  • 18
    `vars` does *not* include the class variables, only the instance variables. – DilithiumMatrix Apr 10 '16 at 20:24
  • To add to your answer, specifying `vars(self)['_data']` should give you only the variables back. – MikeyE Feb 07 '17 at 08:01
  • 2
    @DilithiumMatrix you need to use vars(THECLASSITSELF) on the class itself to get class variables. Check my answer below. – Amir Hossein Baghernezad Aug 23 '17 at 08:15
  • Thank you for this! I like readability and the pprint() version I found here: https://stackoverflow.com/a/193539/1896134 – JayRizzo Oct 19 '18 at 02:29
  • 2
    Using this method to specifically answer the OP's question: `members = list(vars(example).keys())` as (at least in python3) `vars` returns a `dict` mapping the name of the member variable to it's value. – Michael Hall Aug 21 '19 at 10:59
  • `ClassName.__dict__["__doc__"]` This will filter out functions, in-built variables etc. and give you just the fields that you need! – Hyuga Hinata Aug 24 '21 at 02:04
33

@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

Trent
  • 2,328
  • 3
  • 33
  • 51
user235925
  • 838
  • 1
  • 8
  • 11
  • `ClassName.__dict__["__doc__"]` This will filter out functions, in-built variables etc. and give you just the fields that you need! – Hyuga Hinata Aug 24 '21 at 02:05
7
>>> a = Example()
>>> dir(a)
['__class__', '__delattr__', '__doc__', '__format__', '__getattribute__', '__hash__',
'__init__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__',
'__sizeof__', '__str__', '__subclasshook__', 'bool143', 'bool2', 'blah',
'foo', 'foobar2000', 'as_list']

—as you see, that gives you all attributes, so you'll have to filter out a little bit. But basically, dir() is what you're looking for.

balpha
  • 50,022
  • 18
  • 110
  • 131
  • `ClassName.__dict__["__doc__"]` This will filter out functions, in-built variables etc. and give you just the fields that you need! – Hyuga Hinata Aug 24 '21 at 02:05
2

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

example.__dict__.keys()
Mehdi
  • 999
  • 13
  • 11
  • 1
    `ClassName.__dict__["__doc__"]` This will filter out functions, in-built variables etc. and give you just the fields that you need! – Hyuga Hinata Aug 24 '21 at 02:05
-1
row2dict = lambda r: {c.name: str(getattr(r, c.name)) for c in r.__table__.columns} if r else {}

Use this.

4b0
  • 21,981
  • 30
  • 95
  • 142
-1
ClassName.__dict__["__doc__"]

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

-4

The easy way to do this is to save all instances of the class in a list.

a = Example()
b = Example()
all_examples = [ a, b ]

Objects don't spring into existence spontaneously. Some part of your program created them for a reason. The creation is done for a reason. Collecting them in a list can also be done for a reason.

If you use a factory, you can do this.

class ExampleFactory( object ):
    def __init__( self ):
        self.all_examples= []
    def __call__( self, *args, **kw ):
        e = Example( *args, **kw )
        self.all_examples.append( e )
        return e
    def all( self ):
        return all_examples

makeExample= ExampleFactory()
a = makeExample()
b = makeExample()
for i in makeExample.all():
    print i
S.Lott
  • 384,516
  • 81
  • 508
  • 779
  • I like the idea (I might actually use that in a current project). It's not an answer to the question, though: The OP wants to list the attributes, not the instances themselves. – balpha Sep 09 '09 at 10:51
  • @balpha: Ooops. Didn't read the question. 90% of the time, it's a duplicate of "how do I find all instances of a class." The actual question (now that you point it out) isn't sensible. You know the instance variables, just make a list. – S.Lott Sep 09 '09 at 11:51
  • `ClassName.__dict__["__doc__"]` This will filter out functions, in-built variables etc. and give you just the fields that you need! – Hyuga Hinata Aug 24 '21 at 02:06