pickling code

Christophe Thibaut cthibaut at club-internet.fr
Mon Aug 13 23:16:52 CEST 2001

I have the following class

class RefList():
    def __init__(self, keyFunction):
        self._keyFunction = keyFunction
        self._list = {}

    def addRef(self, object):
        key = self._keyFunction(object)
        if not self._list.has_key(key):
            self._list[key] = object

    # ...

wich I use to collect references. A RefList object must be passed the
function or the lambda expression with wich it will obtain the object
unique ref. Id.
RefList collects references of objects from a class C, and must be
provided with a function that can extract a reference key from an object
of class C.

For example with :
class Item():
    def __init__(self, id, n, p):
        self._id = id
        self._name = n
        self._price = p

    def Id(self): #
        return self._id

I can create a reflist of items :
Items = RefList(lambda item:item.Id())

Each time I use addRef with some Item instance, the id is found by
applying the lambda expression on the Item instance. This way RefList do
not need to 'know' more about the items they collect.

So far so good.
The problem is that I want to pickle my Reflists. pickle is Ok to dump
them into a file, but pickle.load refuse to load lambda expressions :

  SystemError: Failed to import class <lambda> from module __main__

I tried to word around this problem by using a reference to the function
rather than lambda expression :

Items = RefList(Item.Item.id)

but then I get :
       pickle.PicklingError: can't pickle 'instance method' objects

I read from the docs that the pickle module doesn't handle code objects.

Is there a solution, apart from writing my own persistance functions or
getting rid of any function ref. or lambda expr. into my classes ?

Thanks you in advance for any tip.

More information about the Python-list mailing list