简体   繁体   中英

imp.load_source() in Python

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM