What would be the best (read: cleanest) way to tell Python to import all modules from some folder?
I want to allow people to put their “mods” (modules) in a folder in my app which my code should check on each startup and import any module put there.
I also don’t want an extra scope added to the imported stuff (not “myfolder.mymodule.something”, but “something”)
If transforming the folder itself in a module, through the use of a
__init__.pyfile and usingfrom <foldername> import *suits you, you can iterate over the folder contentswith “os.listdir” or “glob.glob”, and import each file ending in “.py” with the
__import__built-in function:The benefit of this approach is: it allows you to dynamically pass the module names to
__import__– while the ìmport statement needs the module names to be hardcoded, and it allows you to check other things about the files – maybe size, or if they import certain required modules, before importing them.