25

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?

6 Answers 6

30

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)))
9

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.

2

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().

1
  • How do you use eval() or exec() to evaluate 'myThing'.x?
    – NSP
    Apr 3, 2011 at 15:10
0

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'>]
2
  • so this gives you the classes, but how do you get self.x from one of the classes?
    – NSP
    Apr 3, 2011 at 15:09
  • posted another answer, hope it helps.
    – Asterisk
    Apr 3, 2011 at 16:36
0
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}
0

A really simple way to list modules is:

from <module> import *
print dir(<module>)

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.