[英]Python3. Create list of dynamically generated functions
I am building simple reporting tool based on pandas and I want report developer will be able to transform dataframe by using functions.我正在构建基于熊猫的简单报告工具,我希望报告开发人员能够通过使用函数来转换数据框。 The way I see it report developer creates in the UI DB connection, sql query and bunch of python functions in a string format which then will be executing.我看到它的方式报告开发人员在 UI 数据库连接、sql 查询和一堆 python 函数中以字符串格式创建,然后将执行这些函数。
My class will look like this我的课看起来像这样
class ReportSQLDataset:
def __init__(self, connection, sql, transforming_functions:list):
self.connection = connection
self.sql = sql
self.dataframe = None
self.transforming_functions = transforming_functions
def load_dataframe(self):
self.dataframe = pd.read_sql(self.sql, self.connection)
def run_transforming_functions(self):
for code in self.transforming_functions:
# Here I want execute code from strings provided by user
Example of transforming function变换函数的例子
def some_transformation(df):
# Do something
return df
Is there any idea how to implement this without putting those functions in global scope?有没有想法如何在不将这些功能放在全球范围内的情况下实现这一目标?
For now I've come up with this solution现在我想出了这个解决方案
def function_builder(code):
co = compile(code, 'f', 'exec')
fname = co.co_names[0]
eval(co)
return locals()[fname]
And in my run_transforming_functions method it would be look like this在我的run_transforming_functions方法中它看起来像这样
def run_transforming_functions(self):
for code in self.transforming_functions:
self.dataframe = function_builder(code)(self.dataframe)
Not sure if it is the best solution, but it does what I need.不确定这是否是最佳解决方案,但它可以满足我的需要。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.