gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 06:53:49 24 4
gpt4 key购买 nike

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

我的问题主要是因为我有一个 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.

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

关于python - "from-import"是否执行整个模块?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1114787/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com