Skip to main content
 首页 » 编程设计

python之"from-import"是否执行整个模块

2025年05月04日11tintown

好的,所以我知道 from-import 与 import“完全”相同,除了它显然不是因为命名空间的填充方式不同。

我的问题主要是因为我有一个 utils 模块,它有一个或两个功能,我的应用程序中的每个其他模块都使用这些功能,我正在努力合并标准库 logging 模块,据我所知我需要做这样的事情:

import logging 
logging.basicConfig(filename="/var/log")  # I want file logging 
 
baselogger = logging.getLogger("mine") 
#do some customizations to baselogger 

然后为了在不同的模块中使用它,我将再次导入日志记录:

import logging 
logger = logging.getlogger("mine") 
 
# log stuff 

但我想知道的是,如果我执行 from utils import awesome_func,我的记录器是否一定会被设置,日志模块是否会按照我想要的方式设置?

这也适用于其他通用设置。

请您参考如下方法:

您的问题的答案是肯定的。

有关导入过程的详细说明,请参阅 Frederik Lundh 的“Importing Python Modules”。

特别是,我会引用回答您查询的部分。

What Does Python Do to Import a Module?

[...]

  1. Create a new, empty module object (this is essentially a dictionary)
  2. Insert that module object in the sys.modules dictionary
  3. Load the module code object (if necessary, compile the module first)
  4. Execute the module code object in the new module’s namespace. All variables assigned by the code will be available via the module object.

关于 from-import 的使用:

There are Many Ways to Import a Module

[...]

from X import a, b, c imports the module X, and creates references in the current namespace to the given objects. Or in other words, you can now use a and b and c in your program.

请注意,我省略了一些内容。值得阅读整个文档,它实际上很短。