8

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

  • possible duplicate of [Loading all modules in a folder in Python](http://stackoverflow.com/questions/1057431/loading-all-modules-in-a-folder-in-python) – Fred Foo Apr 06 '12 at 12:31
  • Check a similar thread and its answer here: http://stackoverflow.com/questions/279237/python-import-a-module-from-a-folder – vaisakh Apr 06 '12 at 12:33

3 Answers3

7

If transforming the folder itself in a module, through the use of a __init__.py file and using from <foldername> import * suits you, you can iterate over the folder contents with "os.listdir" or "glob.glob", and import each file ending in ".py" with the __import__ built-in function:

import os
for name in os.listdir("plugins"):
    if name.endswith(".py"):
          #strip the extension
         module = name[:-3]
         # set the module name in the current global name space:
         globals()[module] = __import__(os.path.join("plugins", name)

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.

jxh
  • 69,070
  • 8
  • 110
  • 193
jsbueno
  • 99,910
  • 10
  • 151
  • 209
  • This still works in Python3.6, but the last line is changed to: `import importlib; importlib.import_module("plugins" + "." + module)` – Jason Wheeler Feb 13 '18 at 09:04
  • Thanks - they have deprecated the use of filenames in `__import__`. The funcion still works as well, one just have to use "." there instead of `os.path.join` – jsbueno Feb 13 '18 at 10:52
2

Create a file named

 __init__.py

inside the folder and import the folder name like this:

>>> from <folder_name> import * #Try to avoid importing everything when you can
>>> from <folder_name> import module1,module2,module3 #And so on
luke14free
  • 2,529
  • 1
  • 17
  • 25
0

You might want to try that project: https://gitlab.com/aurelien-lourot/importdir

With this module, you only need to write two lines to import all plugins from your directory and you don't need an extra __init__.py (or any other other extra file):

import importdir
importdir.do("plugins/", globals())
Aurélien
  • 1,742
  • 1
  • 19
  • 30