August 2018
Intermediate to advanced
366 pages
10h 14m
English
The shelve module is implemented as a context manager that manages a dbm database.
When the context is entered, the database is opened, and the contained objects become accessible because shelf was a dictionary.
Each object is stored into the database as a pickled object. That means that before storing it, each object is encoded with pickle and results in a serialized string:
>>> import pickle >>> pickle.dumps(MyClass(5)) b'\x80\x03c__main__\nMyClass\nq\x00)\x81q\x01}' b'q\x02X\x05\x00\x00\x00valueq\x03K\x05sb.'
That allows shelve to store any kind of Python object, even custom classes, as far as they are available again at the time the object is read back.
Then, when the context is exited, all the keys of shelf that were ...