Python: prototyping nested functions

Using an example

def foo(a): def bar(b): return a+b return bar d = {1:foo(1), 2:foo(2)} 

It appears that the brine module will not work with a function not defined in the module area, so the 'd' etching will not work. Is there any other etching mechanism that I should consider?

+7
source share
2 answers

I am afraid that you cannot reveal nested functions.

The pickle module serializes functions by name. That is, if you have the myfunc function in the mymodule module, it simply saves the name mymodule.myfunc and looks for it again when not serializing. (This is an important security and compatibility issue, as it ensures that non-serializing code uses its own definition for the function, not the original definition, which may be compromised or deprecated.)

Alas, pickle cannot do this with nested functions, because there is no way to directly access them by name. For example, your bar function is not accessible from outside foo .

If you need a serializable object that works as a function, you can instead create a class using the __call__ method:

 class foo(object): def __init__(self, a): self.a = a def __call__(self, b): # the function formerly known as "bar" return self.a + b 

This works just like the nested functions in the question, and should not present any problems for pickle . However, keep in mind that you need to have the same class definition if you are not serializing an instance of foo .

+13
source

You can parse nested functions if you use dill instead of pickle .

 >>> import dill >>> >>> def foo(a): ... def bar(b): ... return a+b ... return bar ... >>> d = {1:foo(1), 2:foo(2)} >>> >>> _d = dill.dumps(d) >>> d_ = dill.loads(_d) >>> d_ {1: <function bar at 0x108cfe848>, 2: <function bar at 0x108cfe8c0>} >>> d[1](0) + d[2](10) 13 >>> 
+3
source

Source: https://habr.com/ru/post/923192/


All Articles