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

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

5 Comments

Do note that the modules within the package are not added to the package's dictionary unless they are imported.
ah, so the following is also necessary, right? from pkg import *
No, because * looks in the package's dict. Either import the modules explicitly, or have the package import them.
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?"
how about getattr(pkg, a, None) instead of pkg.__dict__.get(a)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.