python - 如何在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_1
和recipe_2
in收集很多变量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) + '\']')
更好的解决方案?
解决方案
推荐阅读
- android - 需要通过传递访问令牌在 android webview 中访问托管在 Azure MSAL 中的 Web 应用程序
- python-3.x - 将 LinMot 电机的 .NET DLL 导入 python 并使用其功能
- json - 在 JQ 查询中使用变量
- hadoop - ssh 连接到主机端口 22 连接被拒绝
- swift - Xcode 12、工作区和新的“XCFrameworks”不能一起工作
- html - 是否可以将 ui-kit offcanves 添加为下拉菜单?
- reactjs - 如何通过反应获取天蓝色广告刷新令牌
- ios - iPhone12 mini中,状态栏高度是44,为什么tableView的frame.y = 50?
- python - 使用请求和 BeautifulSoup 登录以抓取页面
- android - 按下时如何更改本机TouchableOpacity颜色