Store Python function in JSON

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

提交回复
热议问题