90_pickle.py 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. import pickle as pkl
  2. def test(data): # type: ignore
  3. print('-'*50)
  4. b = pkl.dumps(data)
  5. print(b)
  6. o = pkl.loads(b)
  7. print(o)
  8. assert data == o
  9. test(None) # PKL_NONE
  10. test(1) # PKL_INT8
  11. test(277) # PKL_INT16
  12. test(-66666) # PKL_INT32
  13. test(0xffffffffffff) # PKL_INT64
  14. test(1.0) # PKL_FLOAT32
  15. test(1.12312434234) # PKL_FLOAT64
  16. test(True) # PKL_TRUE
  17. test(False) # PKL_FALSE
  18. test("hello") # PKL_STRING
  19. test(b"hello") # PKL_BYTES
  20. from linalg import vec2, vec3, vec2i, vec3i
  21. test(vec2(2/3, 1.0)) # PKL_VEC2
  22. test(vec3(2/3, 1.0, 3.0)) # PKL_VEC3
  23. test(vec2i(1, 2)) # PKL_VEC2I
  24. test(vec3i(1, 2, 3)) # PKL_VEC3I
  25. test(vec3i) # PKL_TYPE
  26. test([1, 2, 3]) # PKL_LIST
  27. test((1, 2, 3)) # PKL_TUPLE
  28. test({1: 2, 3: 4}) # PKL_DICT
  29. # test complex data
  30. test([1, '2', True])
  31. test([1, '2', 3.0, True])
  32. test([1, '2', True, {'key': 4}])
  33. test([1, '2', 3.0, True, {'k1': 4, 'k2': [b'xxxx']}])
  34. exit()
  35. from pickle import dumps, loads, _wrap, _unwrap
  36. def test(x):
  37. y = dumps(x)
  38. # print(y.decode())
  39. ok = x == loads(y)
  40. if not ok:
  41. _0 = _wrap(x)
  42. _1 = _unwrap(_0)
  43. print('='*50)
  44. print(_0)
  45. print('-'*50)
  46. print(_1)
  47. print('='*50)
  48. assert False
  49. test(1)
  50. test(1.0)
  51. test("hello")
  52. test(True)
  53. test(False)
  54. test(None)
  55. test([1, 2, 3])
  56. test((1, 2, 3))
  57. test({1: 2, 3: 4})
  58. class Foo:
  59. def __init__(self, x, y):
  60. self.x = x
  61. self.y = y
  62. def __eq__(self, __value: object) -> bool:
  63. if not isinstance(__value, Foo):
  64. return False
  65. return self.x == __value.x and self.y == __value.y
  66. def __repr__(self) -> str:
  67. return f"Foo({self.x}, {self.y})"
  68. test(Foo(1, 2))
  69. test(Foo([1, True], 'c'))
  70. from linalg import vec2
  71. test(vec2(1, 2))
  72. a = {1, 2, 3, 4}
  73. test(a)
  74. a = bytes([1, 2, 3, 4])
  75. test(a)
  76. a = [1, 2]
  77. d = {'k': a, 'j': a}
  78. c = loads(dumps(d))
  79. assert c['k'] is c['j']
  80. assert c == d
  81. # test circular references
  82. from collections import deque
  83. a = deque([1, 2, 3])
  84. test(a)
  85. a = [int, float, Foo]
  86. test(a)