How to get all objects in a module in python?

If you have the name of an attribute in a string, you should use getattr to fetch it out.

Given a module X, you can get a list of all it's attributes and (for example) their types with something like this.

for i in dir(X):
   print i,"  ",type(getattr(X,i))

If you actually want the members of a class, instance or module, just use the vars() builtin: http://docs.python.org/library/functions.html#vars (it works as advertised)

If you want the members of the current module from within a function or class (where vars() will do the wrong thing) then you should use globals() instead.

However, the code and the words in your question don't match. You say you want access to the objects "within" myClass, but then you post code that is apparently looking for the subclasses of myClass rather than its contents.

To supplement Asterisk's answers with some more examples of playing with this at the interactive prompt:

>>> class Example:
...   def method(): pass
...
>>> class SubExample(Example):
...   pass
...
>>> class OverrideExample(Example):
...   def method():
...     pass
...
>>> globals()
{'OverrideExample': <class '__main__.OverrideExample'>, '__builtins__': <module
'builtins' (built-in)>, 'Example': <class '__main__.Example'>, '__name__': '__ma
in__', '__package__': None, '__doc__': None, 'SubExample': <class '__main__.SubE
xample'>}
>>> Example.__subclasses__()
[<class '__main__.SubExample'>, <class '__main__.OverrideExample'>]
>>> vars(Example)
dict_proxy({'__dict__': <attribute '__dict__' of 'Example' objects>, '__module__
': '__main__', '__weakref__': <attribute '__weakref__' of 'Example' objects>, 'm
ethod': <function method at 0x00BF6F18>, '__doc__': None})
>>> vars(SubExample)
dict_proxy({'__module__': '__main__', '__doc__': None})
>>> vars(OverrideExample)
dict_proxy({'__module__': '__main__', 'method': <function method at 0x00C10030>,
 '__doc__': None})
>>> vars(Example())
{}
>>> vars(SubExample())
{}
>>> vars(OverrideExample())
{}

Note the differences between what is visible at the module level, on each class object and on each class instance.

Also note that, for a given class definition, vars() won't tell you about any inherited methods. It also won't tell you about methods that are available via a class instance. To correctly see both of those, your best bet is to do as Noufal suggests and walk dir(), calling getattr() for each attribute.

Tags:

Python

Module