When is it useful to use imp.load_source() method for importing Python module? Has it some advantage in some scenario in opposite to normal importing with import keyword?
1 Answer
import always looks in the following order:
- already imported modules
- import hooks
- files in the locations in
sys.path - builtin modules
If you want to import a module which would not be found by any of these mechanisms, but you know the filename, then you could use imp.load_source(). Or if you want to import a module that would be shadowed by an earlier import mechanism, for example if you want to import foo from a directory in sys.path but there is a custom import hook that would find its own version of foo first, then you could use imp.load_source() for that too. Basically it lets you control the source of the module's code in a way that import does not.