如何在 python 包中使用全局变量

How to use global variables within python package

我试图将几个 python 函数创建到一个包中。每个函数都存在于它自己的 python 文件中,并使用全局变量将一些对象 return 返回到全局环境,其中一些被其他 python 函数使用。

当这些函数是在 python 控制台中定义的独立函数时,它们工作得很好,但是当我将它们全部放在一个 python 包中时,全局变量就不行了不再被 return 编辑为全局变量。

为什么用包文件定义的函数不是 return 全局变量/我怎样才能绕过这个?

一个非常简单的例子:

python_function1.py

def function1(x):
    global new_table
    new_table = x

python_function2.py

def function2(new_table):
    global new_table2
    new_table2 = new_table

根据文档说明:

The canonical way to share information across modules within a single program is to create a special module (often called config or cfg). Just import the config module in all modules of your application; the module then becomes available as a global name. Because there is only one instance of each module, any changes made to the module object get reflected everywhere.

您可以查看此文档以获取示例代码:

https://docs.python.org/3/faq/programming.html#how-do-i-share-global-variables-across-modules