frozenutils.py 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2014-2016 OpenMarket Ltd
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. from canonicaljson import json
  16. from frozendict import frozendict
  17. def freeze(o):
  18. if isinstance(o, dict):
  19. return frozendict({k: freeze(v) for k, v in o.items()})
  20. if isinstance(o, frozendict):
  21. return o
  22. if isinstance(o, (bytes, str)):
  23. return o
  24. try:
  25. return tuple(freeze(i) for i in o)
  26. except TypeError:
  27. pass
  28. return o
  29. def unfreeze(o):
  30. if isinstance(o, (dict, frozendict)):
  31. return dict({k: unfreeze(v) for k, v in o.items()})
  32. if isinstance(o, (bytes, str)):
  33. return o
  34. try:
  35. return [unfreeze(i) for i in o]
  36. except TypeError:
  37. pass
  38. return o
  39. def _handle_frozendict(obj):
  40. """Helper for EventEncoder. Makes frozendicts serializable by returning
  41. the underlying dict
  42. """
  43. if type(obj) is frozendict:
  44. # fishing the protected dict out of the object is a bit nasty,
  45. # but we don't really want the overhead of copying the dict.
  46. return obj._dict
  47. raise TypeError(
  48. "Object of type %s is not JSON serializable" % obj.__class__.__name__
  49. )
  50. # A JSONEncoder which is capable of encoding frozendicts without barfing
  51. frozendict_json_encoder = json.JSONEncoder(default=_handle_frozendict)