serializing and deserializing lambdas

后端 未结 2 1385
栀梦
栀梦 2021-02-05 11:10

I would like to serialize on machine A and deserialize on machine B a python lambda. There are a couple of obvious problems with that:

  • the pickle module does not s
2条回答
  •  庸人自扰
    2021-02-05 12:13

    Surprisingly, checking whether a lambda will work without its associated closure is actually fairly easy. According to the data model documentation, you can just check the func_closure attribute:

    >>> def get_lambdas():
    ...     bar = 42
    ...     return (lambda: 1, lambda: bar)
    ...
    >>> no_vars, vars = get_lambdas()
    >>> print no_vars.func_closure
    None
    >>> print vars.func_closure
    (,)
    >>> print vars.func_closure[0].cell_contents
    42
    >>>
    

    Then serializing + loading the lambda is fairly straight forward:

    >>> import marshal, types
    >>> old = lambda: 42
    >>> old_code_serialized = marshal.dumps(old.func_code)
    >>> new_code = marshal.loads(old_code_serialized)
    >>> new = types.FunctionType(new_code, globals())
    >>> new()
    42
    

    It's worth taking a look at the documentation for the FunctionType:

    function(code, globals[, name[, argdefs[, closure]]])
    
    Create a function object from a code object and a dictionary.
    The optional name string overrides the name from the code object.
    The optional argdefs tuple specifies the default argument values.
    The optional closure tuple supplies the bindings for free variables.
    

    Notice that you can also supply a closure… Which means you might even be able to serialize the old function's closure then load it at the other end :)

提交回复
热议问题