I define a python funciton that expects an argument that is a sympy expression. If I save it using pickle and read it back in a different session it will not load.
The error message is “Can’t Get Attribute …”, which usually means that I failed to save something that is referenced by the think I did save. I don’t know that this is the problem in this case, but it seems likely that there are some ‘global’ variables in the syppy package that need to be saved. Especially, since it works within the same session, but not across sessions.
Trouble is there is no hint about what they might be.
# This script tests pickle and for a function that uses sympy. The test only tests within a
# single session.
import pickle
from sympy import Symbol
def SymSqr(xExp):
return xExp * xExp
if __name__ == "__main__":
# constants
fileName = 'temp.pickle'
xSym = Symbol('x')
# test session defined function
result = SymSqr(2*xSym)
print(f'result = {result}')
# save funciton and load it back under a different name
with open(fileName, 'wb') as outFle:
pickle.dump(SymSqr, outFle)
with open(fileName, 'rb') as inFile:
atlFunc = pickle.load(inFile)
# test session defined function
altResult = atlFunc(2 * xSym)
print(f'altResult = {altResult}')
> F:Users...intra_session.py
result = 4*x**2
altResult = 4*x**2
# This script tests pickle and for a function that uses sympy. The test reads the funciton in a
# different session than the one in which it was saved.
import pickle
from sympy import Symbol
if __name__ == "__main__":
# constants
fileName = 'temp.pickle'
xSym = Symbol('x')
# load the functon
with open(fileName, 'rb') as inFile:
SymSqr = pickle.load(inFile)
# test session defined function
result = SymSqr(2 * xSym)
print(f'result = {result}')
F:Users...python.exe F:Users...inter_session.py
Traceback (most recent call last):
File "F:Users...inter_session.py", line 15, in <module>
SymSqr = pickle.load(inFile)
^^^^^^^^^^^^^^^^^^^
AttributeError: Can't get attribute 'SymSqr' on <module '__main__' from 'F:\Users\...\inter_session.py'>
Process finished with exit code 1