I am very confused about how to use pickle
, I'm trying to make the computation a lot faster by storing the values that have been computed, and creating a pickle file for the ones computed. When a certain function hasn't been computed yet I want to open the pickle file and create a new input of the newly computed function. Here's my atttempt:
try:
with open('EinsteinBbb.pickle','rb') as f:
Bbb = pickle.load(f)
except:
Bbb = dict()
def EinsteinBbb(nl, ll, nu, lu):
global Bbb
try:
Bbbfile=pickle.load(open('EinsteinBbb.pickle','rb'))
# Check if Bbb[(nl, ll, nu, lu)] needs to be computed
if True: #TODO: replace with the correct condition
print('Computing Bbb[{0}, {1}, {2}, {3}]'.format(nl, ll, nu, lu))
except:
Bbb[(nl, ll, nu, lu)] = nl*ll*nu*lu
with open('EinsteinBbb.pickle','wb') as f:
pickle.dump(Bbb, f)
with open('EinsteinBbb.pickle','rb') as f:
EinsteinBbb_read = pickle.load(f)
# TODO: Open 'EinsteinBbb.pickle' with write mode and dump Bbb so that it does not need to be recomputed
return Bbb[(nl, ll, nu, lu)]
print(EinsteinBbb(1,2,3,4))
When I try for example print(EinsteinBbb(2,1,2,0))
I get TypeError: string indices must be integers
I feel like my code is very far from being right but any advice would be incredibly helpful!
Edit: Creating a minimal reproducible made the TypeError
disappear, and I think it had to do with where the code was stored, but now I get KeyError
for any key other than the one I ran the code with the first time.