I tried to pickle a python function and restore it
--The function of the module you are importing can be called correctly from another module. --Functions in the same module are called functions with the same name
test1.py
This is test1.func()
This is test2.func()
test2.py
This is test2.func()
This is test2.func()
As mentioned above, test2.py will read func () with the same name. If func () is not in test2.py, an error will occur with "Name Error: name'func' is not defined".
If you import test1.py with test1.py and save test1.func as pickle, it will be read correctly.
I put the following two files in the same directory and ran each.
test1.py
import pickle
import test2
def save_pickle(obj, path):
with open(path, mode='wb') as f:
pickle.dump(obj, f)
def load_pickle(path):
with open(path, mode='rb') as f:
obj = pickle.load(f)
return obj
def func():
print('This is test1.func()')
def main():
func()
test2.func()
path = 'test1_func.pickle'
save_pickle(func, path)
func_from_pickle = load_pickle(path)
func_from_pickle()
path = 'test2_func.pickle'
save_pickle(test2.func, path)
func_from_pickle = load_pickle(path)
func_from_pickle()
if __name__ == '__main__':
main()
test2.py
import pickle
def load_pickle(path):
with open(path, mode='rb') as f:
obj = pickle.load(f)
return obj
def func():
print('This is test2.func()')
def main():
path = 'test1_func.pickle'
func_from_pickle = load_pickle(path)
func_from_pickle()
path = 'test2_func.pickle'
func_from_pickle = load_pickle(path)
func_from_pickle()
if __name__ == '__main__':
main()
Recommended Posts