Tuesday, April 19, 2011

Python: Class to dict including and excluding methods

>>> class Foo(object):
...     bar = 'hello'
...     baz = 'world'
...
>>> f = Foo()
>>> [name for name in dir(f) if not name.startswith('__')]
[ 'bar', 'baz' ]
>>> dict((name, getattr(f, name)) for name in dir(f) if not name.startswith('__')) 
{ 'bar': 'hello', 'baz': 'world' }

Now, if you have a class with methods and you need to get the resulting dict excluding the methods, you can use the isfunction() method from inspect module

>>> from inspect import isfunction
>>> class Foo(object):
...     bar = 'hello'
...     baz = 'world'
...     def calculate(self):
...         return 0
...     def calculate1(self):
...         return 1
...
>>> f = Foo()
>>> dict((name, getattr(f, name)) for name in dir(f) if not isfunction(getattr(f, name)) and not name.startswith('__')) 

{ 'bar': 'hello', 'baz': 'world' }

Source:
http://stackoverflow.com/questions/61517/python-dictionary-from-an-objects-fields
http://stackoverflow.com/questions/624926/how-to-detect-whether-a-python-variable-is-a-function

No comments: