如何检测或捕获 python 中全局变量值的变化
variable = 10
print(variable)
variable = 20
# Detect changes to the value using a signal to trigger a function
更新 AST 文档 - 很好的介绍 https://greentreesnakes.readthedocs.io/en/latest/
最佳答案
据我所知,在 Python 中一般捕获全局符号的赋值是不可能的(至少在 CPython 中,全局变量存储在 dict
对象的 module
中,两者都是 C 类型,不能被monkey patched)。
这里有一个简单的解决方法,但有一点妥协。使用包装器对象来存储监视的变量,并定义 __setattr__
在设置属性之前(或之后)执行您想要执行的任何操作。
class CaptureOnSetAttribute:
def __setattr__(self, attr, value):
# our hook to do something
print(f'set value of {attr} to {value}')
# actually set the attribute the normal way after
super().__setattr__(attr, value)
wrapper_object = CaptureOnSetAttribute()
当然,妥协的办法是现在不要写这样的东西:
monitored_global = value
您现在必须写:
wrapper_object.monitored_attribute = value
关于python - 捕获python中全局变量值的变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59675250/