Python: pickling nested functions

Viewed 7611

Using the example

def foo(a):
    def bar(b):
        return a+b
    return bar

d = {1:foo(1), 2:foo(2)}

It appears that pickle module will not work with a function not defined at the module scope, so pickling 'd' will not work. Is there another pickling mechanism available that I should consider?

3 Answers

according to Blckknght's answersing. if nested function is the only extrac serialized type and will use it as decorator, you can just add functools.warps at top of inner function defination to lead other interpret find the correct name:

from functools import warps

def foo(func):
    @wraps(func)
    def bar(b):
        return func(b)
    return bar

@foo
def zzz(b):
    return b

Related