首页 > 解决方案 > 如何在python中重建局部变量环境?

问题描述

我正在重新格式化一堆数据处理代码。原始代码首先声明了几个函数,它们具有一定的拓扑依赖性(这意味着某些函数依赖于其他函数的结果),然后依次调用它们(使用正确的拓扑排序):

def func_1(df):
    return df.apply(...)

def func_2(df):
    return pd.concat([df, ...])

def func_3(df_1, df_2):
    return pd.merge(df_1, df_2)

if __name__ == "__main__":
    df=...
    df_1 = func_1(df)
    df_2 = func_2(df)
    result = func_3(df_1, df_2)# the func_3 rely on the result of func_1 & func_2

问题是我无法检索中间数据。假设我只想应用 func_1 & func_2,我需要更改一些代码。当拓扑依赖变得复杂时,它就会变得复杂。

所以我想改成类似于 makefile 的递归配方:

def recipe_1(df):
    return df.apply(...)

def recipe_2(df):
    return pd.concat([df, ...])

def recipe_3(df):
    df_1 = recipe_1(df)
    df_2 = recipe_2(df)
    #some process here.
    return 

if __name__ == '__main__':
    df = ...
    recipe_3(df) #Just call the intermediate node I need.

这种方法的问题是我需要从recipe_1recipe_2in收集很多变量recipe_3,所以我认为如果我能够从中检索变量会很好locals(),这将使其他代码#some process here.保持不变。

现在我在想这样的事情,但它看起来很丑:

def func_to_be_reconstructed():
    a = 3
    return locals()

local_variables = func_to_be_reconstructed()
for key in local_variables.keys():
    exec(str(key) + '= local_variables[\'' + str(key) + '\']')

更好的解决方案?

标签: pythonpython-3.xeval

解决方案


globals()而且locals()只是听写...

因此,exec与其以这种可疑的方式使用,不如使用updatedict:

def func_to_be_reconstructed():
    a = 3
    return locals()

globals().update(func_to_be_reconstructed())

推荐阅读