introspection – Get all object attributes in Python?

The Question :

429 people think this question is useful

Is there a way to get all attributes/methods/fields/etc. of an object in Python?

vars() is close to what I want, but it doesn’t work unless an object has a __dict__, which isn’t always true (e.g. it’s not true for a list, a dict, etc.).

The Question Comments :

The Answer 1

586 people think this answer is useful

Use the built-in function dir().

The Answer 2

100 people think this answer is useful

What you probably want is dir().

The catch is that classes are able to override the special __dir__ method, which causes dir() to return whatever the class wants (though they are encouraged to return an accurate list, this is not enforced). Furthermore, some objects may implement dynamic attributes by overriding __getattr__, may be RPC proxy objects, or may be instances of C-extension classes. If your object is one these examples, they may not have a __dict__ or be able to provide a comprehensive list of attributes via __dir__: many of these objects may have so many dynamic attrs it doesn’t won’t actually know what it has until you try to access it.

In the short run, if dir() isn’t sufficient, you could write a function which traverses __dict__ for an object, then __dict__ for all the classes in obj.__class__.__mro__; though this will only work for normal python objects. In the long run, you may have to use duck typing + assumptions – if it looks like a duck, cross your fingers, and hope it has .feathers.

The Answer 3

92 people think this answer is useful

I use __dict__


class MyObj(object):
  def __init__(self): = 'Chuck Norris' = '+6661'

obj = MyObj()

# Output:  
# {'phone': '+6661', 'name': 'Chuck Norris'}

The Answer 4

49 people think this answer is useful

You can use dir(your_object) to get the attributes and getattr(your_object, your_object_attr) to get the values

usage :

for att in dir(your_object):
    print (att, getattr(your_object,att))

Add a Comment