imp.load_source 方法的第一个参数有什么作用?

What does the first argument of the imp.load_source method do?

我正在阅读 this 关于从绝对路径导入模块的问题。答案建议使用以下代码:

import imp
foo = imp.load_source('module.name', '/path/to/file.py')
foo.MyClass()

我想从具有以下结构的目录导入文件(它是包):

__int__.py
model_params.py

我这样做过:

import01 = imp.load_source('module.name', '/home/wakatana/experiments/model_params/model_params.py')

现在我可以通过 import01.VARIABLE_NAME 访问 model_params.py 中的变量。好像等同于import numpy as np。其中 model_params.py 类似于 numpyimport01 类似于 np.

请问load_source方法的第一个参数是做什么的? help(imp) 几乎没有提到 load_source 方法,例如关注 help(imp.load_source) returns load_source(...)

谢谢

根据 behzad.nouri 评论进行编辑

load_source 的文档页面上说:

The name argument is used to create or access a module object.

但是当我尝试访问 module.name 时,我收到有关未定义模块的错误。还有为什么没有 help 可以访问的文档,我能以某种方式安装它吗?我希望文档是 python 中代码本身的一部分,或者不将其内置而是在线提供是一种常见的做法吗?

From documentation

imp.load_source(name, pathname[, file]):

Load and initialize a module implemented as a Python source file and return its module object. If the module was already initialized, it will be initialized again. The name argument is used to create or access a module object. The pathname argument points to the source file. The file argument is the source file, open for reading as text, from the beginning. It must currently be a real file object, not a user-defined class emulating a file. Note that if a properly matching byte-compiled file (with suffix .pyc or .pyo) exists, it will be used instead of parsing the given source file

official documentation 有更多关于该主题的信息。

基本上,您加载模块所用的名称将用于导入该模块的其他文件。即使 python 路径中的任何地方都不存在 module.name 模块,如果您加载某个模块并为其命名,则使用该名称执行常规 import 的其他模块将不会引发错误并且按预期工作。也许一个小例子可以更好地说明这一点:

/tmp/test/foo.py

value = 1337

/tmp/test/bar.py

from foo.bar import value

def print_val():
    print value

/tmp/test/run.py

import imp
foo = imp.load_source('foo.bar', '/tmp/test/foo.py')

import bar

bar.print_val()

正如预期的那样,您将 1337 打印到屏幕上。如果名称不是 foo.bar,导入将在 bar.py 中失败,因为实际上不存在这样的模块。

这个方法实际上可以用于猴子补丁,因为它会覆盖第 3 方模块中的导入。