Why does a pickle loaded after saving differs from the original object?
--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Ancient Construction
--
Chapters
00:00 Why Does A Pickle Loaded After Saving Differs From The Original Object?
00:45 Accepted Answer Score 8
01:25 Answer 2 Score 1
01:51 Thank you
--
Full question
https://stackoverflow.com/questions/5757...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #pickle
#avk47
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Ancient Construction
--
Chapters
00:00 Why Does A Pickle Loaded After Saving Differs From The Original Object?
00:45 Accepted Answer Score 8
01:25 Answer 2 Score 1
01:51 Thank you
--
Full question
https://stackoverflow.com/questions/5757...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #pickle
#avk47
ACCEPTED ANSWER
Score 8
You haven't defined an explicit way to compare Person objects. Therefore, the only way Python can compare them is by their IDs (ie their memory address). The address of the items you've loaded from the pickle will be different from the originals - as they must be, because they are new objects - so the lists will not compare equal.
You can declare an explicit __eq__ method on the Person class:
class Person(object):
def __init__(self, name=None, job=None, quote=None):
self.name = name
self.job = job
self.quote = quote
def __eq__(self, other):
return (self.name == other.name and self.job == other.job and self.quote == other.quote)
Now your comparison will return True as expected.
ANSWER 2
Score 1
Running your code and printing personList1 and personList2; it appears that you are checking if the objects are the same, not if the contents are the same.
False
[<__main__.Person object at 0x000001A8EAA264A8>, <__main__.Person object at 0x000001A8EAA26A20>, <__main__.Person object at 0x000001A8EAA26F98>]
[<__main__.Person object at 0x000001A8EAA26240>, <__main__.Person object at 0x000001A8EAA260F0>, <__main__.Person object at 0x000001A8EAA26908>]
Where if you change your print statement to the following, it will yield true because it is checking the contents.
print(personList[0].name == personList2[0].name)