views:

130

answers:

2

I have a package with a few modules, each module has a class (or a few classes) defined within it. I need to get the list of all modules within the package. Is there an API for this in python?

Here is the file structure:

\pkg\
\pkg\__init__.py
\pkg\module1.py -> defines Class1
\pkg\module2.py -> defines Class2
\pkg\module3.py -> defines Class3 and Class31

from within module1 I need to get the list of modules within pkg, and then import all the classes defined in these modules

Update 1: Ok, after considering the answers and comments below I figured, that it's not that's easy to achieve my need. In order to have the code I proposed below working, all the modules should be explicitly imported beforehand.

So now the new concept: How to get the list of modules within a package without loading the modules? Using python API, i.e. - without listing all the files in the package folder?

Thanks ak

A: 

One ad-hoc approach is list the files in the directory, import each file dynamically with __import__ and then list the classes of the resulting module.

Eli Bendersky
A: 

ok, this was actually pretty straightforward:

import pkg

sub_modules = (                                 
    pkg.__dict__.get(a) for a in dir(pkg) 
    if isinstance(                              
        pkg.__dict__.get(a), types.ModuleType
    )                                           
)               

for m in sub_modules:                                      
    for c in (                                             
        m.__dict__.get(a) for a in dir(m)                  
        if isinstance(m.__dict__.get(a), type(Base))
    ):          
        """ c is what I needed """
ak
Do note that the modules within the package are not added to the package's dictionary unless they are imported.
Ignacio Vazquez-Abrams
ah, so the following is also necessary, right? from pkg import *
ak
No, because `*` looks in the package's dict. Either import the modules explicitly, or have the package import them.
Ignacio Vazquez-Abrams
The number of modules grows with time and I wanted to have something automated for this purpose, so importing the modules explicitly is not the best solution. What do you mean - "to have the package import them?"
ak