I want to save all of my variables (including primitives, objects, lists, dictionaries, etc.) with python shelve. In my workspace, I have a few empty lists which will be used and filled on specific conditions or on the next steps of my code. Unfortunately, when I want to save my workspace with python shelve
it raises an error on empty list keys. My code is as below:
for key in dir():
try:
my_ws[key] = globals()[key]
except TypeError:
print('ERROR shelving: {0}'.format(key))
Do you have any idea?
Shelve doesn't have problem with empty lists.
Please make sure: 1) you initialize the shelve object properly before using it. 2) exclude all elements that shelve cannot serialize. It uses pickle module and all elements supported may be found here:
https://docs.python.org/3/library/pickle.html#what-can-be-pickled-and-unpickled
Check if below code will work for you and if you get any errors.
import inspect
import shelve
my_ws = shelve.open('test')
for key in dir():
if not inspect.ismodule(globals()[key]):
try:
my_ws[key] = globals()[key]
except TypeError:
print('ERROR shelving: {0}'.format(key))