Python: list of modules inside a package

I have a package with several modules, each module has a class (or several classes) defined inside it. I need to get a list of all the modules inside 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 inside the module1 I need to get a list of modules in pkg and then import all the classes defined in these modules

Update 1: Well, after reviewing the answers and comments below, I thought it was not so easy to reach my need. For the code below to work, all modules must be explicitly imported in advance.

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

Thanks ak

+1
2

ok, :

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 """
0

ad-hoc- , __import__, .

+1

All Articles