简体   繁体   English

在 .py 文件之间定义全局变量的正确方法是什么

[英]What is the correct way to define global variables between .py files

I have a Python project with multiple .py files.我有一个包含多个 .py 文件的 Python 项目。 One file should be the "control" file, where parameters can be altered.一个文件应该是“控制”文件,可以在其中更改参数。 Other files should receive input from this control file, and return varying outputs.其他文件应该从这个控制文件接收输入,并返回不同的输出。

My code does as expected if I am using a fresh kernel (I am using Spyder in Anaconda), but after one run if I change a parameter in the control file, not all subsequent variables are updated.如果我使用的是新内核(我在 Anaconda 中使用 Spyder),我的代码会按预期运行,但是在运行一次后,如果我更改了控制文件中的参数,则不会更新所有后续变量。

I have searched stackoverflow and google but am struggling to find the "right way" to accomplish this.我已经搜索过 stackoverflow 和谷歌,但我正在努力寻找“正确的方法”来实现这一目标。 In the real case there are many more files with many more interdependencies, but I have boiled the problem down to the following simple example.在实际情况中,有更多文件具有更多的相互依赖性,但我将问题归结为以下简单示例。

For example, control.py:例如,control.py:

var = 42

file.py:文件.py:

import control.py as con
var2 = con.var
print(var2)

Running file.py the first time prints 42 , as expected.正如预期的那样,第一次运行 file.py 会打印42 But if within control.py I change to var = 43 , save, and then run file.py again, I receive 42但是如果在 control.py 中我更改为var = 43 ,保存,然后再次运行 file.py,我会收到42

I want file.py to give 43 in this instance.在这种情况下,我希望 file.py 给出43

Since the module is already imported, the change is not detected when you run the code again.由于模块已导入,因此再次运行代码时不会检测到更改。

To force python to reimport, you may use the following function:要强制python重新导入,您可以使用以下函数:

import importlib
importlib.reload(con)

# After that
var2 = con.var
print(var2)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM