Python serialize lexical closures?

Posted by dsimcha on Stack Overflow See other posts from Stack Overflow or by dsimcha
Published on 2009-02-21T19:03:12Z Indexed on 2010/03/19 13:31 UTC
Read the original article Hit count: 520

Filed under:
|
|

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 the details of binary vs. string serialization, etc., it just has to work. For example:

def foo(bar, baz) :
    def closure(waldo) :
        return baz * waldo
    return closure

I'd like to just be able to dump instances of closure to a file and read them back.

Edit: One relatively obvious way that this could be solved is with some reflection hacks to convert lexical closures into class objects and vice-versa. One could then convert to classes, serialize, unserialize, convert back to closures. Heck, given that Python is duck typed, if you overloaded the function call operator of the class to make it look like a function, you wouldn't even really need to convert it back to a closure and the code using it wouldn't know the difference. If any Python reflection API gurus are out there, please speak up.

© Stack Overflow or respective owner

Related posts about serialization

Related posts about python