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 that produces a JSON:

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

from hashlib import md5

import marshal  
import json  
import types

class FuncMarshal:

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

    def serialize(cls, function):
        if callable(function):
            serialized = json.dumps((
            return (cls.md5sum(serialized), serialized)

    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), \

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

Dev and Ops , and might be the opposite.

View or Post Comments