【发布时间】:2021-01-03 10:07:50
【问题描述】:
我正在重新格式化一堆数据处理代码。原代码首先声明了几个函数,它们具有一定的拓扑依赖关系(即某些函数依赖于其他函数的结果),然后依次调用它们(使用正确的拓扑排序):
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_3中的recipe_1和recipe_2收集很多变量,所以我认为如果我能够从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) + '\']')
更好的解决方案?
【问题讨论】:
-
您到底想完成什么?你的用例是什么?
-
这能回答你的问题吗? How do I create variable variables? TL;DR - 不要使用
exec创建新变量,只需使用loacals()作为字典... -
这真的没有多大意义。
标签: python python-3.x eval