Possible Duplicate:
Inspect python class attributes
I need to get a clean list of the names of all attributes defined my me in a class. Lets say I have the next class:
class MyClass(object):
attr1 = None
attr2 = 2
attr3 = "Hello world"
I would like to know if there is something that allows me to do:
>>> some_method(MyClass) # <- check class
['attr1', 'attr2', 'attr3']
>>> my_class = MyClass()
>>> some_method(my_class) # <- check instance of MyClass
['attr1', 'attr2', 'attr3']
I can’t rely on the built-in method dir since it also returns attributes like __class__, __getattr__ and any method the class has. I mean, I need to get ONLY the attributes defined in the class, not the built-in ones too, neither the methods.
Is that even possible? or is there any way to know what attributes are built-in and which ones are defined by me so that I can loop over the list dir returns and make some filtering?
Thanks in advance for any help!!
You can use the inspect module to do this.
Here’s an example:
The basic idea is to run
inspect.getmembersto get all the members of some object. This supports both objects as well as classes. Methods and builtins are filtered using the predicate lambda expression supplied as optional argument toinspect.getmembers. Then, list comprehension is used to get just the names of each of the members, and lastly__dict__etc is filtered out using the Python filter function.The filtering for
__dict__etc is not very “scientific”, but I think it should do for most cases 🙂