Python 存储在代码块内部读取的变量

Python 存储在代码块内部读取的变量,python,locals,Python,Locals,我正在尝试存储在exec()函数中运行的代码中读取或写入的变量,我不知道最好的方法是什么 我能想到的唯一方法是这样做: class newDict(dict): def __init__(self, *args): dict.__init__(self, args) self.accessed_variables = set() def __getitem__(self, key): val = dict.__getitem

我正在尝试存储在exec()函数中运行的代码中读取或写入的变量,我不知道最好的方法是什么

我能想到的唯一方法是这样做:

class newDict(dict):
    def __init__(self, *args):
         dict.__init__(self, args)
         self.accessed_variables = set()

    def __getitem__(self, key):
         val = dict.__getitem__(self, key)
         self.accessed_variables.add(key)
         return val

    def __setitem__(self, key, value):
         self.accessed_variables.add(key)
         dict.__setitem__(self, key,value)

    def get_variables(self):
         return self.accessed_variables

local_env = newDict()
global_env = newDict()
code = """ """
exec(code, global_env, local_env)
print(local_env.get_variables)

我认为没有理由否决这个问题。任务是明确的,显示了自己的努力,在我看来,这可能是最明智的方式。这是为了一些调试/评测吗?它用于捕获解释器在给定时刻的状态。我认为没有理由否决这个问题。任务是明确的,显示了自己的努力,在我看来,这可能是最明智的方式。这是用于某些调试/评测吗?它用于捕获解释器在给定时刻的状态。