Reputation: 29
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.
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?
Upvotes: 1
Views: 36
Reputation: 29
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
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.
Upvotes: 0