Store Python function in JSON

后端 未结 4 645
北海茫月
北海茫月 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 06:42

    If you really need to store a function in an external JSON file, one solution could be to store a lambda function as a value and use the eval function to evaluate it from your script.

    But be aware that using eval in your code could be dangerous, please consider the security implications before using it (see this article from realpython.com).

    config.json

    {
      "x": 5,
      "y": 4,
      "function": "lambda x, y : x * y"
    }
    

    Your Python file (test.py)

    import json
    
    
    def run():
        """Run function from JSON config."""
    
        with open("config.json") as f:
            data = json.load(f)
    
        x, y = data["x"], data["y"]
        multiplier = eval(data["function"])
        return multiplier(x, y)
    
    
    if __name__ == "__main__":
       result = run()
       print(result)
    

    Demo

    In[2]: ls
    test.py
    config.json
    
    In[3]: import json
    
    In[4]: def run():
      ...:     """Run function from JSON config."""
      ...: 
      ...:     with open("config.json") as f:
      ...:         data = json.load(f)
      ...: 
      ...:     x, y = data["x"], data["y"]
      ...:     multiplier = eval(data["func"])
      ...:     return(multiplier(x, y))
      ...:    
    
    In[5]: run()
    20
    
    0 讨论(0)
  • 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

    0 讨论(0)
  • 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)
    
    0 讨论(0)
  • 2021-01-13 07:07

    Python has a built in module name marshal that can handle this.

    import marshal, ujson as json
    
    def multiplier(a, b):
        return a * b
    
    x = {
      "x":5,
      "y":4,
      "func" : marshal.dumps(multiplier.func_code)
    }
    
    x = json.dumps(x)
    print(x)
    

    And to get it back...

    x = json.loads(x)
    x = marshal.loads(x['func'])
    # maybe save the function name in dict
    func = types.FunctionType(x, globals(), "some_func_name") 
    
    print(func(2,4))
    
    0 讨论(0)
提交回复
热议问题