You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

51 lines
1.3 KiB

  1. # Copyright 2014-2016 OpenMarket Ltd
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import collections.abc
  15. from typing import Any
  16. from immutabledict import immutabledict
  17. def freeze(o: Any) -> Any:
  18. if isinstance(o, dict):
  19. return immutabledict({k: freeze(v) for k, v in o.items()})
  20. if isinstance(o, immutabledict):
  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: Any) -> Any:
  30. if isinstance(o, collections.abc.Mapping):
  31. return {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