jsonpickle忽略了集合deque的maxlen

时间:2013-10-21 12:37:41

标签: python collections pickle jsonpickle

我尝试使用jsonpickle保存和恢复collection.deque列表,但maxlen参数在此过程中丢失。

original_test = deque(maxlen=2)
original_test.append(1)
original_test.append(2)

print(original_test)
>>> deque([1, 2], maxlen=2) # everything ok

encoded_test = jsonpickle.encode(original_test)
print(encoded_test)
>>> {"py/seq": [1, 2], "py/object": "collections.deque"} # where is maxlen?

restored_test = jsonpickle.decode(encoded_test)
restored_test.append(3)

print(restored_test)
>>> deque([1, 2, 3]) # maxlen missing

1 个答案:

答案 0 :(得分:1)

jsonpickle本身并不猜测应该序列化哪些属性。如果您正在编写自定义类,则必须tell it

但是,由于您无法控制deque课程,因此您必须实施custom serialization handler

class DequeHandler(jsonpickle.handlers.BaseHandler):
    def flatten(self, obj, data):
        return list(obj),obj.maxlen
    def restore(self,obj):
        return deque(obj[0], maxlen=obj[1])
jsonpickle.handlers.register(deque, DequeHandler)