I have a directory structure as follows:
| main.py
| scripts
|--| __init__.py
| script1.py
| script2.py
| script3.py
In main.py, if I import scripts, this apparently does not allow me to use scripts.script1. I know I can use from scripts import * to access the modules in the scripts package, but then I can only use them directly as scripts1, scripts2 etc.
How can I write the code so that I can refer to scripts.script1 inside main.py?
I tried using pkgutils.walk_packages, as well as the __all__ attribute of the package, to get the submodule names, but I couldn’t figure out a way to use those strings to do the import.
Edit: Here’s one way to recursively import everything at runtime…
(Contents of
__init__.pyin top package directory)I’m not using
__import__(__path__+'.'+module_name)here, as it’s difficult to properly recursively import packages using it. If you don’t have nested sub-packages, and wanted to avoid usingglobals()[module_name], though, it’s one way to do it.There’s probably a better way, but this is the best I can do, anyway.
Original Answer (For context, ignore othwerwise. I misunderstood the question initially):
What does your
scripts/__init__.pylook like? It should be something like:You could even do without defining
__all__, but things (pydoc, if nothing else) will work more cleanly if you define it, even if it’s just a list of what you imported.