81_pickle.py 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. from pickle import dumps, loads, _wrap, _unwrap
  2. def test(x):
  3. ok = x == loads(dumps(x))
  4. if not ok:
  5. _0 = _wrap(x)
  6. _1 = _unwrap(_0)
  7. print('='*50)
  8. print(_0)
  9. print('-'*50)
  10. print(_1)
  11. print('='*50)
  12. assert False
  13. test(1)
  14. test(1.0)
  15. test("hello")
  16. test(True)
  17. test(False)
  18. test(None)
  19. test([1, 2, 3])
  20. test((1, 2, 3))
  21. test({1: 2, 3: 4})
  22. class Foo:
  23. def __init__(self, x, y):
  24. self.x = x
  25. self.y = y
  26. def __eq__(self, __value: object) -> bool:
  27. if not isinstance(__value, Foo):
  28. return False
  29. return self.x == __value.x and self.y == __value.y
  30. def __repr__(self) -> str:
  31. return f"Foo({self.x}, {self.y})"
  32. test(Foo(1, 2))
  33. test(Foo([1, True], 'c'))
  34. from linalg import vec2
  35. test(vec2(1, 2))
  36. a = {1, 2, 3, 4}
  37. test(a)
  38. a = bytes([1, 2, 3, 4])
  39. test(a)
  40. a = [1, 2]
  41. d = {'k': a, 'j': a}
  42. c = loads(dumps(d))
  43. assert c['k'] is c['j']
  44. assert c == d
  45. # test circular references
  46. from collections import deque
  47. a = deque([1, 2, 3])
  48. test(a)
  49. a = [int, float, Foo]
  50. test(a)