4. Saving objects to file

In the example below, shelve is shown as an alternative for storing multiple objects in one place.

Serialization choices become easier to maintain when the code states whether it is storing one value or a small keyed collection of values. Showing shelve alongside lower-level pickling makes that tradeoff more concrete for small local persistence tasks.

4.1. Don’t do this

 1import pickle
 2
 3object_1 = 'pretend some big object 1'
 4object_2 = 'pretend some big object 2'
 5data = {
 6    'object_1': object_1,
 7    'object_2': object_2,
 8}
 9
10# write to file
11pickle.dump(data, open('data.p', 'wb'))
12
13# read from file
14data = pickle.load(open('data.p', 'rb'))

4.2. Do this

 1import shelve
 2
 3object_1 = 'pretend some big object 1'
 4object_2 = 'pretend some big object 2'
 5
 6# write to file
 7with shelve.open('data') as s:
 8    s['object_1'] = object_1
 9    s['object_2'] = object_2
10
11# read from file
12with shelve.open('data') as s:
13    print(s['object_1'])
14    print(s['object_2'])