How to get all objects in a module in python?

Question:

I need to get a list of all the objects within a module — not a list of just their names. So, for instance, I have:

class myClass:  
    def __init__(self):  
        # here be code
        pass

class thing1(myClass):  
    def __init__(self):  
        self.x = 1

class thing2(myClass):  
    def __init__(self):
        self.x = 2

and so on.

What I want is something that will give me a list of the objects in myClass (thing1, thing2) from which I can call methods / get attributes. I’m trying to do something like this:

for myThing in dir(myClass):  
    print myThing.x

But the dir function only gives a list of the names of the classes, and I can’t get the attribute from that.

How can I do this?

Asked By: NSP

||

Answers:

Not sure if that helps:

class myClass(object):

    def init(self):
        pass


class thing1(myClass):
    def init(self):
        self.x = 1

class thing2(myClass):
    def init(self):
        self.x = 2

myClass.__subclasses__()
[<class '__main__.thing1'>, <class '__main__.thing2'>]
Answered By: Asterisk

I believe locals() gives you a dictionary of all the local variables and the objects they are pointing to.

You could also try using the eval() or exec() functions to evaluate the names as raw python code. Then you could directly use the results from dir().

Answered By: Garrett Berg

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)))
Answered By: Noufal Ibrahim
class myClass(object):

    def init(self):
        pass


class thing1(myClass):
    def __init__(self):
        self.x = 1

class thing2(myClass):
    def __init__(self):
        self.x = 2

print myClass.__subclasses__()
print vars(thing1())
print vars(thing2())

[<class '__main__.thing1'>, <class '__main__.thing2'>]
{'x': 1}
{'x': 2}
Answered By: Asterisk

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.

Answered By: ncoghlan

A really simple way to list modules is:

from <module> import *
print dir(<module>)
Answered By: Jonathan
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.