Python Pickle: Pickled Objects Are Not Equal To Source Objects
Solution 1:
Your classes likely do not define a meaningful __eq__
, and thus are being compared for object identity. Since the classes loaded from pickles are not the same objects as the ones in your generated list (even though they have the same data), you get False
.
Solution 2:
Comparing two objects of the same class yields False by default (unless they are the same single object), even if they have the same contents; in other words, two intuitively "identical" objects from the same class are considered different, by default. Here is an example:
>>>classC(object):...def__init__(self, value):... self.value = value...>>>>>>C(12) == C(12)
False
You want to define __eq__()
(and __ne__()
) in your custom class so that it yields True for objects that contain the same data (respectively False). More information can be found in the official documentation. For the above example, this would be:
>>>classC(object):...# ......def__eq__(self, other):...return self.value == other.value...def__ne__(self, other):...returnnot self == other # More general than self.value != other.value...>>>C(12) == C(12) # __eq__() is called
True
>>>C(12) != C(12) # __ne__() is called
False
Post a Comment for "Python Pickle: Pickled Objects Are Not Equal To Source Objects"