Reputation:
My program fails to unpickle my data, where pickle.load(f) does not match pickle.dump(object,f). My question is where am I going wrong with the following code, as I have experimented with various file modes with the corresponding errors listed above my code below:
f = open(home + '/.GMouseCfg','ab+')
out: They are different
f = open(home + '/.GMouseCfg','ab+', encoding='utf-8')
ValueError: binary mode doesn't take an encoding argument
f = open(home + '/.GMouseCfg','a+')
TypeError: must be str, not bytes
import abc, pprint
from evdev import ecodes as e
from os.path import expanduser
try:
import cPickle as pickle
except:
import pickle
class Command(object):
__metaclass__ = abc.ABCMeta
@abc.abstractmethod
def set(self, data):
"""set data used by individual commands"""
return
@abc.abstractmethod
def run(self):
"""implement own method of executing data of said command"""
return
class KeyCommand(Command):
def __init__(self, data):
self.data = data
def set(data):
self.data = data
def run(self):
pass
def __str__(self):
return data
class SystemCommand(Command):
def __init__(self, data):
self.data = data
def set(data):
self.data = data
def run(self):
pass
def __str__(self):
return data
if __name__ == '__main__':
ids = [2,3,4,5,6,7,8,9,10,11,12]
home = expanduser('~')
f = open(home + '/.GMouseCfg','a+')
f.seek(0)
commands = list()
commands.append(KeyCommand({3:[e.KEY_RIGHTCTRL,e.KEY_P]}))
commands.append(SystemCommand({5:['gedit','./helloworld.txt']}))
pickle.dump(commands,f)
f.seek(0)
commands2 = pickle.load(f)
if commands == commands2:
print('They are the same')
else:
print('They are different')
I have done alot of reading on python docs for pickles and file io but am unable to discern why there is a difference between my original object and the unpickled one
Upvotes: 0
Views: 420
Reputation: 69042
After pickling and unpickling, obviously command
and command2
will never be the same object.
That means commands == commands2
will always return False
, unless you implement comparision for your class, for example:
class KeyCommand(Command):
...
def __eq__(self, other):
return self.data == other.data
def __ne__(self, other):
return self.data != other.data
...
class SystemCommand(Command):
...
def __eq__(self, other):
return self.data == other.data
def __ne__(self, other):
return self.data != other.data
...
Upvotes: 2