90_pickle.py 1.1 KB

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