81_pickle.py 906 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  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(_0)
  8. print(_1)
  9. assert False
  10. test(1)
  11. test(1.0)
  12. test("hello")
  13. test(True)
  14. test(False)
  15. test(None)
  16. test([1, 2, 3])
  17. test((1, 2, 3))
  18. test({1: 2, 3: 4})
  19. class Foo:
  20. def __init__(self, x, y):
  21. self.x = x
  22. self.y = y
  23. def __eq__(self, __value: object) -> bool:
  24. if not isinstance(__value, Foo):
  25. return False
  26. return self.x == __value.x and self.y == __value.y
  27. def __repr__(self) -> str:
  28. return f"Foo({self.x}, {self.y})"
  29. test(Foo(1, 2))
  30. a = [1,2]
  31. test(Foo([1, 2], a))
  32. from linalg import vec2
  33. test(vec2(1, 2))
  34. a = {1, 2, 3, 4}
  35. test(a)
  36. a = bytes([1, 2, 3, 4])
  37. test(a)
  38. a = [1, 2]
  39. d = {'k': a, 'j': a}
  40. c = loads(dumps(d))
  41. assert c['k'] is c['j']
  42. assert c == d