Search code examples
evalpicklepython-3.5

Python - Store function definition for later use


I have an app running with many visualisations which are using bokeh. I have defined a function for each visualisation.

For new visualisations, is there a way that -

  • I write the visusalisation function somewhere else e.g. jupyter notebook
  • Store this function somehow in database or files, like we can do in javascript
  • Use eval() to run this function later

Can you please point me a direction? I tried lambda functions but that's single line while my functions can be more complex.

In case you need something, please put in comments :)

Thanks in advance.


Solution

  • Okay, I got the answer. Python Pickles - https://docs.python.org/3/library/pickle.html

    No Need to use eval().

    A very basic and simple example of it.

    import pickle
    
    def calculations(a, b):
        c = a + b
        print('Addition is ', c)
        return c
    
    fun_def_str = pickle.dumps(calculations)
    
    cal = pickle.loads(fun_def_str)
    
    result = cal(5,6) # Prints - Addition is 11
    
    print(result) # Outputs: 11
    

    I hope this helps someone :)