gitcmds: "globals to locals" micro-optimization
[git-cola.git] / cola / serializer.py
blob5dda86dd246d3abfda3838a0254400d27a8187d4
1 """Provides a serializer for arbitrary Python objects"""
2 import jsonpickle
3 jsonpickle.set_encoder_options('simplejson', indent=4)
5 from cola import utils
7 handlers = {}
10 def save(obj, path):
11 utils.write(path, encode(obj))
14 def load(path):
15 import jsonpickle
16 return decode(utils.slurp(path))
19 def clone(obj):
20 # Go in and out of encode/decode to return a clone
21 return decode(encode(obj))
24 def encode(obj):
25 handler = _gethandler(obj)
26 if handler:
27 handler.pre_encode_hook()
28 jsonstr = jsonpickle.encode(obj)
29 if handler:
30 handler.post_encode_hook()
31 return jsonstr
34 def decode(jsonstr):
35 obj = jsonpickle.decode(jsonstr)
36 handler = _gethandler(obj)
37 if handler:
38 handler.post_decode_hook()
39 return obj
42 def _gethandler(obj):
43 cls = type(obj)
44 # Allow base classes to provide a serialization handlers
45 # for their subclasses
46 if hasattr(cls, 'mro'):
47 for supercls in cls.mro():
48 if supercls in handlers:
49 return handlers[supercls](obj)
50 if cls in handlers:
51 return handlers[cls](obj)
52 return None