81_pickle.py 1.1 KB

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