Hot-keys on this page
r m x p toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
# cython: old_style_globals=True """ Function pickling
REFERENCE: The python cookbook. """ from __future__ import absolute_import
import types import six from six.moves import copyreg from six.moves import cPickle
def 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__) (<built-in function code_ctor>, ...) sage: unpickle_function(pickle_function(foo)) <function foo at ...> """
def reduce_code(co): """ EXAMPLES::
sage: def foo(N): return N+1 sage: sage.misc.fpickle.reduce_code(foo.__code__) (<built-in function code_ctor>, ...) """
else: co_args = (co.co_argcount, co.co_kwonlyargcount)
copyreg.pickle(types.CodeType, reduce_code)
def 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 """
def 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 """
def call_pickled_function(fpargs): import sage.all from sage.misc.fpickle import unpickle_function (fp, (args, kwds)) = fpargs f = eval("unpickle_function(fp)", sage.all.__dict__, {'fp':fp}) res = eval("f(*args, **kwds)",sage.all.__dict__, {'args':args, 'kwds':kwds, 'f':f}) return ((args, kwds), res)
# The following four methods are taken from twisted.persisted.styles - the # import of twisted.persisted.styles takes a long time and we do not use # most functionality it provides def pickleMethod(method): 'support function for copyreg to pickle method refs'
# Note: On Python 3 there is no .im_class but we can get the instance's # class through .__self__.__class__
def unpickleMethod(im_name, __self__, im_class): 'support function for copyreg to unpickle method refs'
# Note: On Python 2 "unbound methods" are just functions, so they don't # have a __func__ # Attempt a common fix before bailing -- if classes have # changed around since we pickled this method, we may still be # able to get it by looking on the instance's current class. return unbound
copyreg.pickle(types.MethodType, pickleMethod, unpickleMethod)
oldModules = {}
def pickleModule(module): 'support function for copyreg to pickle module refs'
def unpickleModule(name): 'support function for copyreg to unpickle module refs' name = oldModules[name]
copyreg.pickle(types.ModuleType, pickleModule, unpickleModule) |