I am trying to save functions into a csv file, with other description fields. I am currently saving a function using dill dumps, and then convert it into literal string and store in the file. When I load the csv file, I have a problem in converting this literal string back to the function. Is there a way to convert the string representation of binary string into the binary string? Currently I use exec to do so but I suppose it is not a good practice.
Or is there other better way to store a function or binary string into a csv file?
import dill
def add_one(a):
return a + 1
output_to_csv_file = str(dill.dumps(add_one)) # output_to_csv_file is the string representation of binary string of add_one
exec("tmp = " + output_to_csv_file) # Now I have tmp storing the binary string
loaded_add_one = dill.loads(tmp)
print(loaded_add_one(2))
I would suggest saving it as a hex string (below implementation assumes python 3.5+)
import dill
tmp = dill.dumps(lambda a: a + 1).hex()
loaded = dill.loads(bytes.fromhex(tmp))
print(loaded(2))