[BangPypers] Importing modules automatically

Phil for Banpypers phil.nabble at hanjinet.org
Mon Jun 4 13:16:56 CEST 2012


I'm wondering if someone has a nice solution for the following problem.

I'd like to be able to import all the modules in a directory, such that 
developers can simply add a *.py file somewhere (or a directory), and 
let the framework import them automatically for doing something with 

For example, let's take the following directory structure:

   / modules
     / __init__.py
     / module1.py
     / module2.py
     / module3
       / __init__.py

So we can end up with something like that pseudo code in the 

__all__ = [module_path for dir_path in 
            if module_path.endswith('.py')
            or (os.path.isdir(module_path)
	       and os.path.exists(os.path.join(module_path, "__init__.py")))

The framework is then be able to use:

import modules
for module_path in modules.__all__:
   the_module = __import__(module_path, fromlist=[''])
   ## Do additional checks and process ...

[As a side note, i never really understood the fromlist argument, maybe 
it's worth another thread?]

This solution works but has at least 2 flaws:

- won't work with eggs or zip files out of the box
- is not pythonic (not sure it'll even pass python 3)

Any suggestion?


More information about the BangPypers mailing list