python - 为什么导入文件的顺序会解决 NameError?
问题描述
我有三个文件,一个是需要运行的主文件,另外两个是实用函数,如下。所有文件都在同一个目录中,我在 PyCharm 上运行它。
# delta_plots.py - This is the main file
...
from delta_plots_utility_1 import *
from delta_plots_utility_2 import *
...
def print_parameter_header(params, flag):
batch_size, epochs, lr = params[0], params[1], params[2]
print("{} - Batch size: {}, Epochs: {}, Learning rate: {}".
format(flag.upper(), batch_size, epochs, lr))
...
if __name__ == '__main__':
# call the utility functions based on a condition
if (condition1):
utility_function_1()
elif (condition2):
utility_function_2()
# delta_plots_utility_1.py - Utility file 1
# this import statement is to import the print_parameter_header() function
# from the main file
from plot_delta_mp import *
def utility_function_1():
# this function makes a call to the print_parameter_header() function
...
print_parameter_header(params, flag)
...
# delta_plots_utility_2.py - Utility file 2
from plot_delta_mp import *
def utility_function_2():
# this function also makes a call to the print_parameter_header() function
...
print_parameter_header(params, flag)
...
问题是在主文件中,如果条件1 为真,那么我被迫将实用程序文件 1 的导入语句放在实用程序文件 2 的导入语句之前,反之亦然。
否则,我会收到以下错误:
NameError: name 'print_parameter_header' is not defined
我也尝试将文件作为模块导入,然后访问函数 as module.print_parameter_header()
,但这也无济于事。
我对此有以下疑问:
- 据我了解,导入语句的顺序并不重要。那么为什么会这样呢?为什么更改顺序可以解决错误?
- 这可能是因为类似循环的导入吗?因为我也在实用程序函数中导入主文件。
- 如果是,那么可以
print_parameter_header()
在实用程序文件中定义吗?虽然这会是多余的,但这是一个好习惯吗?
解决方案
似乎您所有的问题都来自最初的误解:“据我了解,导入语句的顺序并不重要。”
在python中,一个import语句
- 可能发生在代码中的任何地方(不一定在开头),因此如果您遇到循环依赖问题,如果您没有其他设计选择,则导入最新的可能是个好主意
- 在代码中创建符号。所以
from xxx import a
会在本地创建变量a
,就像写a = 0
. 完全一样。
因此,也许对您来说一个好的解决方案是停止使用from <xxx> import *
or import <xxx>
,它们都从另一个模块导入所有符号,而是在精确控制的位置导入选定的符号。比如from <xxx> import a, b
在你的代码之后from <xxx> import c
。
很抱歉没有花时间将上述答案调整为您的精确代码示例,但希望您能明白这一点。
推荐阅读
- python - 通过 pytorch 中的视图将索引转换回来
- typescript - 打字稿 - 空检查后对象可能是'null'.ts(2531)
- node.js - MongoDB 在插入之前检查对象属性,否则创建新对象
- oracle - ef core db-migraions 在表空间中创建表
- python - 如何在数据框的每一列中查找特定字符串的 value_count
- reactjs - 如何根据另一个数字输入中的数字动态创建多个字段?
- pytorch - 记录 jit 编译的 PyTorch 类方法 (Sphinx)
- math - 了解 Gram-Schmidt Process 是如何翻译成这段代码作为实现的
- java - Hackerrank:内部类Solution.Result中的非法静态声明
- python - 从 python 字典中删除值