Store Python function in JSON

后端 未结 4 648
北海茫月
北海茫月 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

    Something that is worth trying is just saving it as a string.

    You can do stuff like

    my_func = "
    def function(a,b):
       constant = {input_var}
       return a*b + constant
    "
    my_func.format(input_var = 5)
    
    exec(my_func)
    function(1,2) # will return 7
    

    This will create object of the function that you can call. Not really sure what you are trying to do but creating a json file like below should give you what you want to do: (I added the 'func' wrapper because I am assuming you will have multiple functions in one JSON)

    function_json = {
    'func': {
        'x':5
        'y':4
        'multiplier':
    'def multiplier(a,b):
        return a*b'
    }
    
    x=function_json['func']['x']
    y=function_json['func']['y']
    exec(function_json['func']['multiplier'])
    multiplier(x,y) # will return 20
    

    hope this helps

提交回复
热议问题