为什么该功能似乎只导入一次?

Why the function seems to import once?

我有三个文件 file_a.pyfile_b.pyfunc.py:

func.py中,我有:

import datetime

def a_simple_function():
    print("hello from simple function")
    return datetime.datetime.now()

global_variable = a_simple_function()

file_b.py中,我有:

from func import global_variable  # second time import

def func_in_b():
    print("print from file b:", global_variable)

file_a.py中,我有:

from func import global_variable  # first time import 
from file_b import func_in_b

print("print from file a:", global_variable)
func_in_b()

file_a 的 运行 时,我看到以下输出:

hello from simple function
print from file a: 2019-06-17 14:14:42.293202
print from file b: 2019-06-17 14:14:42.293202

为什么 hello from simple function 出现一次而不是两次?我想我已经在不同的文件中导入了两次。

基本上我试图设置一个 global_variablefile_a.pyfile_b.py 中使用,global_variable 是由文件 func.py 中的函数生成的.

Python 在 sys.modules 中缓存导入。所以即使你多次导入同一个模块,它也会使用缓存的版本,而不是重复导入。

阅读有关 module cache 的更多信息。

这就是导入的工作方式,如文档所述:https://docs.python.org/3/tutorial/modules.html#more-on-modules。具体来说:

A module can contain executable statements as well as function definitions. These statements are intended to initialize the module. They are executed only the first time the module name is encountered in an import statement.

基本上,import 语句首先检查 sys.modules 是否已经包含您的模块。如果是,则返回现有引用,如第二种情况。如果不是,则创建一个空模块对象,添加到 sys.modules,然后才由 运行 .py 文件填充。这样做的原因是为了避免循环导入的循环:模块不会在这样的循环中重新加载,即使它的对象仍然是空的。

所有三个文件中对 global_variable 的引用指向完全相同的对象。您可以通过将以下代码添加到现有代码来签入 file_a

import func
import file_b
import sys

print(func.global_variable is file_b.global_variable is global_variable is sys.modules['func'].global_variable)

要记住的一个警告是 运行 作为脚本的模块会将其放置在 sys.modules 中,名称为 __main__。任何试图以其常用名称导入它的代码都会加载不同的模块对象,有时会导致意想不到的后果。

这是因为当您在文件file_a.py中导入global_variable时,函数a_simple_function()在内存中定义并保存在python缓存中。 下次您在文件 file_b.py 中导入 global_variable 时,函数 a_simple_function() 已在缓存中,因此不会再次定义它,而是取 global_variable 的值从那里开始。