如何为Python函数设置自定义局部变量?

2024-09-30 06:17:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图调用一个函数,但监视该函数中的所有局部变量访问。我想我需要做的是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'>

也就是说,全局访问被重定向到我的自定义dict,而本地分配则不是。你甚至可以在最后一行打印的两个对象的类型中看到这一点

我的直觉是,由于我使用的是函数__code__成员,因此我最终执行的是预编译字节码,而预编译字节码中已经包含了关于局部dict的假设

如果我是对的(或者即使我不是),那么实现我的目标的正确方法是什么:将本地作业重定向到提供的词典

谢谢


Tags: keyfromselfvaluedeftypetableglobal

热门问题