How to marshal a function?

Ben Wolfson wolfson at uchicago.edu
Wed Nov 14 18:12:00 EST 2001


In article <mailman.1005772461.23419.python-list at python.org>, "Cliff
Wells" <logiplexsoftware at earthlink.net> wrote:

> On Wednesday 14 November 2001 12:54, Cliff Wells wrote:
> 
> 
>> > Earlier today, I wondered how to marshal a function, in view of
>> > transmitting it to a remote machine and executing it there.  The idea
>> > was to not transmit Python source, when the byte-compilation has
>> > already been done on this side.
> 
> Another reason to use pickle rather than marshal:

Pickle won't necessarily work, though.  If I have:

#file test.py
def make_adder(a):
    def adder(b):
        return a + b
    return adder

#file test2.py
import test, cPickle
print cPickle.dumps(make_adder)

The result relies on importing a module called "test" and accessing an
attribute called "make_adder".  If that file isn't present on the other
machine, there's trouble.  A solution using marshal that doesn't suffer
from that problem is:

def load_function(s):
    dummy = lambda: None
    dummy.func_code = marshal.loads(s)
    return dummy

But that dumps core with nested scopes:

Python 2.2b1 (#1, Oct 19 2001, 15:58:12) 
[GCC 2.96 20000731 (Red Hat Linux 7.1 2.96-81)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import marshal
>>> import test
>>> def load_function(s):
...     dummy = lambda: None
...     dummy.func_code = marshal.loads(s)
...     return dummy
... 
>>> g = load_function(marshal.dumps(test.add4.func_code))
>>> g(1)
Segmentation fault (core dumped)

-- 
BTR    
Why does this Wolfson person see fit to clutter up Usenet with such
absurd nonsense?
  -- Bob Cunningham in <km4butor1ke8f5et2f3p5h80jh521cn2sk at 4ax.com>



More information about the Python-list mailing list