Suppose o
is a Python object, and I want all of the fields of o
, without any methods or __stuff__
. How can this be done?
I've tried things like:
[f for f in dir(o) if not callable(f)]
[f for f in dir(o) if not inspect.ismethod(f)]
but these return the same as dir(o)
, presumably because dir
gives a list of strings. Also, things like __class__
would be returned here, even if I get this to work.
You can get it via the __dict__
attribute, or the built-in vars
function, which is just a shortcut:
>>> class A(object):
... foobar = 42
... def __init__(self):
... self.foo = 'baz'
... self.bar = 3
... def method(self, arg):
... return True
...
>>> a = A()
>>> a.__dict__
{'foo': 'baz', 'bar': 3}
>>> vars(a)
{'foo': 'baz', 'bar': 3}
There's only attributes of the object. Methods and class attributes aren't present.