python: list modules within the package

落花浮王杯 提交于 2019-12-11 06:14:24

问题


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


回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/2536610/python-list-modules-within-the-package

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!