python: list modules within the package

2019-07-27 09:26发布

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

2条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-07-27 10:18

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.

查看更多
在下西门庆
3楼-- · 2019-07-27 10:30

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 """
查看更多
登录 后发表回答