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
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.ok, this was actually pretty straightforward: