# Function pickling#

REFERENCE: The python cookbook.

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

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 ...>
```
```>>> from sage.all import *
>>> def foo(a,b,c=Integer(10)): return a+b+c
>>> sage.misc.fpickle.reduce_code(foo.__code__)
(<cyfunction code_ctor at ...>, ...)
>>> unpickle_function(pickle_function(foo))
<function foo at ...>
```
sage.misc.fpickle.pickleMethod(method)[source]#

support function for copyreg to pickle method refs

sage.misc.fpickle.pickleModule(module)[source]#

support function for copyreg to pickle module refs

sage.misc.fpickle.pickle_function(func)[source]#

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
```
```>>> from sage.all import *
>>> def f(N): return N+Integer(1)
...
>>> g = pickle_function(f)
>>> h = unpickle_function(g)
>>> h(Integer(10))
11
```
sage.misc.fpickle.reduce_code(co)[source]#

EXAMPLES:

```sage: def foo(N): return N+1
sage: sage.misc.fpickle.reduce_code(foo.__code__)
(<cyfunction code_ctor at ...>, ...)
```
```>>> from sage.all import *
>>> def foo(N): return N+Integer(1)
>>> 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
```
```>>> from sage.all import *
>>> ctor, args = sage.misc.fpickle.reduce_code(foo.__code__)
>>> ctor(*args) == foo.__code__
True
```
sage.misc.fpickle.unpickleMethod(im_name, __self__, im_class)[source]#

support function for copyreg to unpickle method refs

sage.misc.fpickle.unpickleModule(name)[source]#

support function for copyreg to unpickle module refs

sage.misc.fpickle.unpickle_function(pickled)[source]#

Unpickle a pickled function.

EXAMPLES:

```sage: def f(N,M): return N*M
...
sage: unpickle_function(pickle_function(f))(3,5)
15
```
```>>> from sage.all import *
>>> def f(N,M): return N*M
...
>>> unpickle_function(pickle_function(f))(Integer(3),Integer(5))
15
```