How to marshal a function?

François Pinard pinard at iro.umontreal.ca
Wed Nov 14 17:53:54 EST 2001


[Cliff Wells]

> > I quickly found out that, for a given `function f(...) ...' I should
> > transmit marshal-ed `f.func_code' instead of `f'.

> Try pickle (or cPickle) rather than marshal:

I did not even try `pickle' for that, after the documentation (printed at
1.5.2 time) insists that `pickle' has no representation for code objects.

> import pickle
> def f(a, b, c):
>     return a + b + c
> pc = pickle.dumps(f)

> # transmit pc to another machine...

> f = pickle.loads(pc)
> print f(1, 2, 3)

If you examine `pc', you will have some difficulty to believe that it
actually conveys the function definition.  It probably only holds a
reference to the name.  Oh, it does works if I do everything in a single
Python session, because `f' is already defined.  But if I save `pc' to
disk and reload it in a fresh Python session, the `pickle.loads(pc)' yields:

   SystemError: Failed to import class f from module __main__

So, I would not think that `pickle' is a solution.

-- 
François Pinard   http://www.iro.umontreal.ca/~pinard





More information about the Python-list mailing list