问题描述
我正在尝试调用一个函数,但是监视该函数内的所有局部变量访问。我认为我需要做的是使用自定义exec
字典locals
来实现该功能。下面的代码试图做到这一点。
class MySymbolTable(dict):
def set_type(self,t):
self.type = t
def __getitem__(self,key):
print(f"Requesting key {key} from {self.type} table")
return super().__getitem__(key)
def __setitem__(self,key,value):
print(f"Setting key {key} from {self.type} table to value {value}")
return super().__setitem__(key,value)
def mylocals(func):
def wrapper(*args,**kwargs):
loc = MySymbolTable()
glob = MySymbolTable(globals())
loc.set_type("local")
glob.set_type("global")
exec(func.__code__,glob,loc)
return wrapper
@mylocals
def fun1():
print(f"fun1 with locals: {type(locals())} and globals: {type(globals())}")
a = 1
b = 2
c = 3
a = b
c = 5
fun1()
但是,当我运行它时,会得到以下输出:
Requesting key print from global table
Requesting key type from global table
Requesting key locals from global table
Requesting key type from global table
Requesting key globals from global table
fun1 with locals: <class 'dict'> and globals: <class '__main__.MySymbolTable'>
这就是说,全局访问被重定向到我的自定义字典,而本地分配没有。您甚至可以在最后一行打印的两个对象的类型中看到这一点。
我的直觉是,由于我使用的是函数__code__
成员,所以我最终执行了预先编译的字节码,该字节码已经对内置的本地字典作出了假设。
如果我是对的(或者即使我不对),那么实现我的目标的正确方法是:将本地作业重定向到提供的词典?
谢谢!
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)