On 16 Apr, 09:39, Duncan Booth <duncan.bo...@invalid.invalid> wrote:
> 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 Boothhttp://kupuguy.blogspot.com


Thank you for everyone's explanations, help and interest on this one.
I have reworked my code as described and promised myself not to use
lambdas ever again (i still think they are an elegant idea, but if
they are incompatible with frequently used modules, then the
inelegance of reality quickly overshadows the elegance of the theory).

I think my problem now is that parallel python will want to unpickle
my objects but can't find the modules.  I've asked the pp forum for
insight, but i think i'm going to have to plug away with this one.

Thanks again,

Warren
--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to