简体   繁体   中英

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.

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM