frozenutils.py 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  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 frozendict import frozendict
  16. def freeze(o):
  17. t = type(o)
  18. if t is dict:
  19. return frozendict({k: freeze(v) for k, v in o.items()})
  20. if t is frozendict:
  21. return o
  22. if t is str or t is unicode:
  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. t = type(o)
  31. if t is dict or t is frozendict:
  32. return dict({k: unfreeze(v) for k, v in o.items()})
  33. if t is str or t is unicode:
  34. return o
  35. try:
  36. return [unfreeze(i) for i in o]
  37. except TypeError:
  38. pass
  39. return o