I have a directory structure as follows:
| main.py
| scripts
|--| __init__.py
| script1.py
| script2.py
| script3.py
From main.py
, the module scripts
is imported. I tried using pkgutils.walk_packages
in combination with __all__
, but using that, I can only import all the submodules directly under main
using from scripts import *
. I would like to get them all under scripts
. What would be the cleanest way to import all the submodules of scripts
so that I could access scripts.script1
from main
?
EDIT: I am sorry that I was a bit vague. I would like to import the submodules on run-time without specifying them explicitly in __init__.py
. I can use pkgutils.walk_packages
to get the submodule names (unless someone knows of a better way), but I am not sure of the cleanest way to use these names (or maybe the ImpImporters that walk_packages
returns?) to import them.
Simply works, and allows relative import inside packages:
Usage:
Not nearly as clean as I would like, but none of the cleaner methods worked for me. This achieves the specified behaviour:
Directory structure:
Where
pkg/scripts/__init__.py
is empty, andpkg/__init__.py
contains:Although it's messy, it should be portable. I've used this code for several different packages.
This works nicely for me in Python 3.3. Note that this works only for submodules which are in files in the same directory as the
__init__.py
. With some work however it can be enhanced for supporting submodules in directories too.