Python: Marshalling functions

If for some obscure reason do you want to call Python code from Javascript and viceversa you can take a look to my still(ever) green experimental project Slurpy.

The most tricky part coding the callback mechanism was to implement the function serialization.

Here is my function serialization class to produce a JSON string:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

from hashlib import md5

import marshal  
import json  
import types


class FuncMarshal:

    @classmethod
    def md5sum(cls, serialized):
        hasher = md5()
        hasher.update(serialized)
        return hasher.hexdigest()

    @classmethod
    def serialize(cls, function):
        if callable(function):
            serialized = json.dumps((
                            marshal.dumps(function.func_code),
                            function.func_name,
                            function.func_defaults)
                        )
            return (cls.md5sum(serialized), serialized)

    @classmethod
    def deserialize(cls, encoded):
        (code, name, defaults) = json.loads(encoded)
        code = marshal.loads(code)

        return (cls.md5sum(encoded), \
                types.FunctionType(code, globals=globals(), name=str(name), \
                                                            argdefs=defaults))

I also added a md5sum of the resulting object for validation but this part is not really needed.

Please let me know if you have a better approach for do this kind of serialization.


Jorge Niedbalski

Jorge Niedbalski

Software Engineer , focused on automation.


View or Post Comments