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.
5
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.)
2
This should get you close:
import inspect
class MyClass(object):
my_attrib = 'foo'
my_other_attrib = 'bar'
def mymethod():
pass
for name, value in inspect.getmembers(MyClass):
if not inspect.ismethod(value) and not name.startswith('__'):
print name
This outputs:
my_attrib
my_other_attrib
NOTE – There may be a better / more-official way to do this, but this should point you in the right direction.
__dict__
gives you all that but you could use a C
extension maybe to get what you want. Not sure why you would do that though.
You can use types
(doc) to distinguish between members of __dict__
.
You can use the builtin dir()
to get everything, then filter. You will not need the inspect
module.
def get_attrs_without_methods(klass):
attrs = dir(klass)
d = {}
for x in attrs:
if x.startswith('__'): continue
value = getattr(self,x)
if not callable(value):
d[x] = value
return d
Sometimes, you may want to get ONLY class variables instead of class variables AND instance variable.
You can filter out instance variables by relying on __dict__
. Or you can get the attributes using __class__
and filter out the methods. __class__
does not return instance variables.
#after collecting your attributes using the above example...
for attr, value in vars(obj).items():
d.pop(attr) #remove instance variables from the dict
#both vars(obj).items() and obj.__dict__.items() return similar iterable.
Note that if the object implementation overrides __dict__
and returns None, vars(obj)
and obj.__dict__.items()
will not return a dictionary.