Store Python function in JSON

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

提交回复
热议问题