Store Python function in JSON

后端 未结 4 649
北海茫月
北海茫月 2021-01-13 06:14

Say I have a JSON file as such:

{
  \"x\":5,
  \"y\":4,
  \"func\" : def multiplier(a,b):
               return a*d
}

This over-simplif

4条回答
  •  太阳男子
    2021-01-13 07:01

    I have tried out and combined solutions from ethan-kulla and eatmeimadanish

    The following code works:

    my_func = '''
    def function(a,b):
       constant = {input_var}
       return a*b + constant
    '''
    
    exec(my_func.format(input_var=5), globals())
    # For Python 3.x, use globals() to change global context
    function(2,2)
    

提交回复
热议问题