Skamah One
Skamah One

Reputation: 2456

Importing all modules in a package?

Here's my file hierarchy:

|--main.py
|--package/
   |--__init__.py
   |--a.py
   |--b.py

Now what I'd like to do is something like this:

# main.py
from package import *
print(package.a.MyClass)
print(package.b.my_function)

So basically I want it to automatically import everything that's inside the package package. Is this possible? I would rather not have to write the imports manually, as I want it to be "drag&drop your files here and you're done" kind of system.

Upvotes: 2

Views: 57

Answers (1)

James Mills
James Mills

Reputation: 19050

I recommend using Python's pkgutil.iter_modules

Example:

import pkgutil


for module_loader, name, ispkg in pkgutil.iter_modules(["/path/to/module"]):
    ...

What you do with the iterated sub-modules is up to the user.

An alternative and commonly used approach is to use pkg_resources which you can also look into and I believe comes as part of setuptools

Update: The naive approach to this is to use __import__ and os.lsitdir():

import os

def load_modules(pkg):
    for filename in os.listdir(os.path.dirname(pkg.__file__)):
        if filename.endswith(".py"):
            m = __import__("{}.{}".format(pkg.__name__, os.path.splitext(filename)[0]))

NB: This is not tested but should give you a rough idea.

Upvotes: 2

Related Questions