I have some class which take a function as on of its init arguments:
class A(object):
def __init__(self, some_var, some_function):
self.some_function = some_function
self.x = self.some_function(some_var)
I can create a function, pass it to an instance of the object, and save it using pickle:
import pickle as pcl
def some_function(x):
return x*x
a = A(some_var=2, some_function=some_function)
pcl.dump(a, open('a_obj.p', 'wb'))
Now I want to open this object in some other code. However, I don't want to include the def some_function(x):
code in each file which uses this specific saved object.
So, what's the best python practice to pass external function as an argument to a python object and then save the object, such that the external function is "implemented" inside the object instance, so it doesn't have to be written in every file which uses the saved object?
Edit: Let me clarify, I don't want to save the function. I want to save only the object. I there's any elegant way to "combine" the external function inside the object so I can pass it as an argument and then it "becomes" part of this object's instance?