Python serialize lexical closures?

后端 未结 5 1006
遇见更好的自我
遇见更好的自我 2020-12-14 18:24

Is there a way to serialize a lexical closure in Python using the standard library? pickle and marshal appear not to work with lexical closures. I don\'t really care about

5条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-14 18:45

    If you simply use a class with a __call__ method to begin with, it should all work smoothly with pickle.

    class foo(object):
        def __init__(self, bar, baz):
            self.baz = baz
        def __call__(self,waldo):
            return self.baz * waldo
    

    On the other hand, a hack which converted a closure into an instance of a new class created at runtime would not work, because of the way pickle deals with classes and instances. pickle doesn't store classes; only a module name and class name. When reading back an instance or class it tries to import the module and find the required class in it. If you used a class created on-the-fly, you're out of luck.

提交回复
热议问题