Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get all objects in a module in python?

Tags:

python

module

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?

like image 549
NSP Avatar asked Apr 03 '11 03:04

NSP


People also ask

How do I get all the functions in a Python module?

We can list down all the functions present in a Python module by simply using the dir() method in the Python shell or in the command prompt shell.

How do I display the contents of a Python module?

We've then used the dir () function to display the attributes provided by the module. Here is a brief description of the attributes: Bye, Welcome – the functions provided by the module. __builtins__ – a listing of all the built-in attributes that are accessible from the module.

What is the use of __ all __ in Python?

In short, __all__ on package level does approximately the same thing as for modules, except it deals with modules within the package (in contrast to specifying names within the module). So __all__ specifies all modules that shall be loaded and imported into the current namespace when us use from package import * .

Can I have a list of objects in Python?

We can create list of object in Python by appending class instances to list. By this, every index in the list can point to instance attributes and methods of the class and can access them. If you observe it closely, a list of objects behaves like an array of structures in C.


2 Answers

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))
like image 124
Noufal Ibrahim Avatar answered Sep 20 '22 10:09

Noufal Ibrahim


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.

like image 28
ncoghlan Avatar answered Sep 23 '22 10:09

ncoghlan