Welcome, guest | Sign In | My Account | Store | Cart

The pickle' module provides a convenient way to serialize Python data structures to disk. With the introduction ofwith' statement in Python 2.5, we can write code that reads/updates Python data in a more intuitive way.

Python, 24 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
from __future__ import with_statement
from contextlib import contextmanager

@contextmanager
def pickled(filename):
    if os.path.isfile(filename):
        data = pickle.load(open(filename))
    else:
        data = {}

    def getter(item, type):
        if item in data:
            return data[item]
        else:
            data[item] = type()
            return data[item]

    yield getter

    pickle.dump(data, open(filename, "w"))

# Here is an example usage:
with pickled("foo.db") as p:
    p("users", list).append(["srid", "passwd", 23])

The pickled' context returns afunction' object that, when called, returns the object that was serialized. All objects (in this example, a list) are serialized after hashing them in a dictionary. The users list is hashed using the key "users". If the object does not already exist, it will be created using the type passed as second argument. For example, since "users" does not already exist in a new pickled file, a new `list' will be returned.

This way of writing program abstracts both serialization and explicit input/output operations.