capture change of global variable value in python

守給你的承諾、 提交于 2020-01-21 12:16:48

问题


How do i detect or capture change of value of a global variable in python

variable = 10
print(variable)
variable = 20 
# Detect changes to the value using a signal to trigger a function

UPDATE AST docs - GOOD INTRO https://greentreesnakes.readthedocs.io/en/latest/


回答1:


To my knowledge, it is not possible to generically capture the assignment of a global symbol in Python (At least in CPython where globals are stored in a dict in the module object, both are C types that cannot be monkey patched).

Here's a simple workaround that's a bit of a compromise. Use a wrapper object to store your monitored variables, and define __setattr__ to do whatever you want to do before (or after) setting an attribute.

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()

The compromise of course is that now instead of writing something like:

monitored_global = value

You must now write:

wrapper_object.monitored_attribute = value


来源:https://stackoverflow.com/questions/59675250/capture-change-of-global-variable-value-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!