Function pickling#

REFERENCE: The python cookbook.

sage.misc.fpickle.call_pickled_function(fpargs)#
sage.misc.fpickle.code_ctor(*args)#

EXAMPLES:

This indirectly tests this function.

sage: def foo(a,b,c=10): return a+b+c
sage: sage.misc.fpickle.reduce_code(foo.__code__)
(<cyfunction code_ctor at ...>, ...)
sage: unpickle_function(pickle_function(foo))
<function foo at ...>
sage.misc.fpickle.pickleMethod(method)#

support function for copyreg to pickle method refs

sage.misc.fpickle.pickleModule(module)#

support function for copyreg to pickle module refs

sage.misc.fpickle.pickle_function(func)#

Pickle the Python function func. This is not a normal pickle; you must use the unpickle_function method to unpickle the pickled function.

NOTE: This does not work on all functions, but does work on ‘surprisingly’ many functions. In particular, it does not work on functions that includes nested functions.

INPUT:

func – a Python function

OUTPUT:

a string

EXAMPLES:

sage: def f(N): return N+1
...
sage: g = pickle_function(f)
sage: h = unpickle_function(g)
sage: h(10)
11
sage.misc.fpickle.reduce_code(co)#

EXAMPLES:

sage: def foo(N): return N+1
sage: sage.misc.fpickle.reduce_code(foo.__code__)
(<cyfunction code_ctor at ...>, ...)

Test that the constructed code matches the original code:

sage: ctor, args = sage.misc.fpickle.reduce_code(foo.__code__)
sage: ctor(*args) == foo.__code__
True
sage.misc.fpickle.unpickleMethod(im_name, __self__, im_class)#

support function for copyreg to unpickle method refs

sage.misc.fpickle.unpickleModule(name)#

support function for copyreg to unpickle module refs

sage.misc.fpickle.unpickle_function(pickled)#

Unpickle a pickled function.

EXAMPLES:

sage: def f(N,M): return N*M
...
sage: unpickle_function(pickle_function(f))(3,5)
15