By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
445,885 Members | 1,474 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 445,885 IT Pros & Developers. It's quick & easy.

Pickling object inherited from dict

P: n/a
Hi!

If I pickle a class which inherits from dict,
I don't get the same data again, if I unpickle
it.

def test_pickle():
home="..."
server=WorkflowServer(home)
server.save()
print server.users.items() # 1
unpickle=load(home)
print unpickle.users.items() #2

def load(home):
file=os.path.join(home, "data.pickle")
fd=open(file)
server=pickle.load(fd)
fd.close()
assert(server.__class__==WorkflowServer)
return server

WorkflowServer:
def save(self):
file=os.path.join(self.home, "data.pickle")
fd=open(file, "w")
pickle.dump(self, fd)
fd.close()

class User(dict):
....

class UserManagemente(dict):
.... # server.users

If I run test_pickle() I get this result: (See #1 and #2)
[('EGSADMIN', {}), ('TEST', {})]
[('EGSADMIN', {}), ('TEST', (<class '__main__.UserManagement'>,
<type 'dict'>, {'EGSADMIN': {}, 'TEST': {}}))]

Why are the two lines different? Sorry, I was not able
to make a smaller working example today.

thomas
Python 2.2.2
Jul 18 '05 #1
Share this Question
Share on Google+
1 Reply


P: n/a
Am Mon, 27 Oct 2003 17:19:08 +0100 schrieb Thomas Guettler:
Hi!

If I pickle a class which inherits from dict,
I don't get the same data again, if I unpickle
it.


Here is a executable example:
import pickle

class MyDictContainer(dict):
def __init__(self):
dict.__init__(self)
print "MyDictContainer.__init__"

class MyDict(dict):
def __init__(self, root, name):
dict.__init__(self)
self.root=root
self.name=name

container=MyDictContainer()
for name in ["one", "two", "three"]:
mydict=MyDict(container, name)
container[name]=mydict

print container
file="data.pickle"
fd=open(file, "w")
pickle.dump(container, fd)
fd.close()

fd=open(file)
unpickle=pickle.load(fd)
fd.close()
print unpickle
Output:

===> python test-pickle.py
MyDictContainer.__init__
{'three': {}, 'two': {}, 'one': {}}
{'one': {},
'three': (<class '__main__.MyDictContainer'>,
<type 'dict'>, {'three': {},
'two': (<class '__main__.MyDictContainer'>, <type 'dict'>,
{'three': {}, 'two': {}, 'one': {}}), 'one': {}}), 'two':
(<class '__main__.MyDictContainer'>, <type 'dict'>,
{'three': {}, 'two': {}, 'one': {}})}

After unpickling the object is not the same anymore.
Any hints?

thomas

Jul 18 '05 #2

This discussion thread is closed

Replies have been disabled for this discussion.