Search code examples
pythonintrospection

Get class and object attributes of class without methods and builtins


Say I have this class:

class MyClass(object):
  my_attrib = 'foo'
  my_other_attrib = 'bar'

  def mymethod():
    pass

Now how can I get ONLY the attributes of the class MyClass, WITHOUT methods and builtins like __dict__ and so on?

I want to get a dictionary like {'my_attrib':'foo', 'my_other_attrib':'bar'}, when applied to the class above.


Solution

  • You can filter out everything you don't need from __dict__:

    def getAttributes(clazz):
        return {name: attr for name, attr in clazz.__dict__.items()
                if not name.startswith("__") 
                and not callable(attr)
                and not type(attr) is staticmethod}
    

    Edit: An alternative that behaves slightly differently for class properties and descriptors:

    def getAttributes2(clazz):
        attrs = {}
        for name in vars(clazz):
            if name.startswith("__"):
                continue
            attr = getattr(clazz, name)
            if callable(attr):
                continue
            attrs[name] = attr
        return attrs
    

    (In practice, this should be rarely different from the first version.)