3

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 1

2

import always looks in the following order:

  1. already imported modules
  2. import hooks
  3. files in the locations in sys.path
  4. 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.

Sign up to request clarification or add additional context in comments.

2 Comments

May I ask, what does hooks mean?
If you meant to ask about the import hooks I mentioned, it's a way of allowing Python to find modules in places or ways that it wouldn't ordinarily look. See PEP 302.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.