Paul Rubin <http://phr...@nospam.invalid> wrote:

> Duncan Booth <duncan.bo...@invalid.invalid> writes:
>> dumped = dumps(air)
>> t = loads(dumped)
>> print t # works fine
> 
> 
> Hmm, well, that doesn't really pickle the function; it pickles a class
> instance that records where the class definition was and (on
> unpickling) imports that module.  Maybe that is sufficient for this
> purpose.

It pickles a class instance which contains a reference to a function and 
on unpickling it recreates the class instance with a new reference to 
the function of the same name.

That's how pickling works: it records where the class or function is 
defined and creates a new reference to the class or function of the same 
name when you unpickle. The classes and functions have to be defined at 
module scope otherwise it won't be able to reference them. You don't 
ever actually get either a class or function in the pickle so if you 
want you can update the code and the unpickled object gets the new one.

>>> import pickle
>>> class C(object):
        def __init__(self, fn):
                self.fn = fn
        def callfn(self):
                self.fn()

                
>>> def foo():
        print "Hello I'm foo"

        
>>> inst = C(foo)
>>> inst.callfn()
Hello I'm foo
>>> p = pickle.dumps(inst)
>>> def foo():
        print "I'm a new foo"

        
>>> inst2 = pickle.loads(p)
>>> inst2.callfn()
I'm a new foo
>>> inst.callfn()
Hello I'm foo

-- 
Duncan Booth http://kupuguy.blogspot.com
--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to