外包 python 模块不更新全局变量

Outsourced python module doesn't update globals

我正在 class 中添加一些全局变量。以下工作正常:

class AssignGlobal():

    @staticmethod
    def assign():
        code = 'xyz'
        index = 2
        globals()[code] = index

AssignGlobal.assign()

xyz  ## returns 2

但是如果我将 AssignGlobal class 外包出去,全局变量就不会再更新了。我实际上不确定这个导入到底做了什么。为什么它不更新我的全局变量?

from backtester.outsourced import AssignGlobal as ag
## assume I created a file outsourced.py in the backtested subdirectory from where I am. It contains the AssignGlobal class above

ag.assign()

xyz

NameError                                 Traceback (most recent call last)
<ipython-input-3-8714e0ef31ed> in <module>
----> 1 xyz

NameError: name 'xyz' is not defined

Python 全局变量本质上是在定义它们的模块范围内。

当您在模块内声明全局变量时,它们会添加到模块中 __dict__ 并且可以作为属性从另一个模块访问。

在您的情况下,您导入 outsourced 模块的模块在其 __dict__ 中不会有 xyz ,而 outsourced 模块对象将有一个调用 AssignGlobal.assign().

后设置属性 xyz

下面的代码会输出2:

import outsourced

outsourced.AssignGlobal.assign()

print(outsourced.xyz)

原因是,当调用 assign 时,xyz 是在 outsourced 模块的范围内定义的,而不是在导入时定义的,因为全局变量不共享。

要获取 xyz 值,您需要将其作为属性从 outsourced 模块对象中获取。

docs 展示了如何跨模块共享变量。