473,805 Members | 1,929 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Pickling object inherited from dict

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=Workflow Server(home)
server.save()
print server.users.it ems() # 1
unpickle=load(h ome)
print unpickle.users. items() #2

def load(home):
file=os.path.jo in(home, "data.pickl e")
fd=open(file)
server=pickle.l oad(fd)
fd.close()
assert(server._ _class__==Workf lowServer)
return server

WorkflowServer:
def save(self):
file=os.path.jo in(self.home, "data.pickl e")
fd=open(file, "w")
pickle.dump(sel f, 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__.UserM anagement'>,
<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
1 2005
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__(s elf)
print "MyDictContaine r.__init__"

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

container=MyDic tContainer()
for name in ["one", "two", "three"]:
mydict=MyDict(c ontainer, name)
container[name]=mydict

print container
file="data.pick le"
fd=open(file, "w")
pickle.dump(con tainer, 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__.MyDic tContainer'>,
<type 'dict'>, {'three': {},
'two': (<class '__main__.MyDic tContainer'>, <type 'dict'>,
{'three': {}, 'two': {}, 'one': {}}), 'one': {}}), 'two':
(<class '__main__.MyDic tContainer'>, <type 'dict'>,
{'three': {}, 'two': {}, 'one': {}})}

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

thomas

Jul 18 '05 #2

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
1534
by: Thomas Guettler | last post by:
Hi! After unpickling the objects are not the same any more. Is this a bug or feature? import pickle class MyDictContainer(dict): def __init__(self): dict.__init__(self)
3
1867
by: Nicolas Fleury | last post by:
Hi, Does anyone know if arrays would be picklable in python 2.4? Until then, I tried to derive from array.array and add __setstate__ and __getstate__ with the following code, but it seems I'm not doing it correctly. Any idea what I'm doing wrong? Thx and Regards, Nicolas import array as arr
1
2299
by: Edward Loper | last post by:
I'm having trouble pickling subclasses of dict when they contain cycles. In particular: >>> import pickle >>> class D(dict): pass >>> d = D() >>> d = d # add a cycle. >>> print d {1: {...}} >>> pickle.dump(d, open('d.pickle', 'w'))
1
3264
by: fedor | last post by:
Hi all, happy new year, I was trying to pickle a instance of a subclass of a tuple when I ran into a problem. Pickling doesn't work with HIGHEST_PROTOCOL. How should I rewrite my class so I can pickle it? Thanks , Fedor
2
2259
by: Kirk Strauser | last post by:
I have a module that defines a Search class and a SearchResult class. I use these classes by writing other modules that subclass both of them as needed to interface with particular search engines. My problem is that Search defines a method (called automatically by __del__) to save its results between invocations: def _saveresults(self): self._oldresults = self._results file = open(self._storefile(), 'w')
1
2282
by: Erik Max Francis | last post by:
I've come across a limitation in unpickling certain types of complex data structures which involve instances that override __hash__, and was wondering if it was known (basic searches didn't seem to come up with anything similar) and if there is a workaround for it short of restructuring the data structures in question. The fundamental issue rests with defining classes which override __cmp__ and __hash__ in order to be used as keys in...
9
3603
by: Alex | last post by:
I have a serious problem and I hope there is some solution. It is easier to illustrate with a simple code: >>> class Parent(object): __slots__= def __init__(self, a, b): self.A=a; self.B=b def __getstate__(self): return self.A, self.B def __setstate__(self, tup):
2
5500
by: Peter Bengtsson | last post by:
Hi, I'm trying to pickle an object instance of a class that is like a dict but with a __getattr__ and I'm getting pickling errors. This works but is not good enough. $ python2.4 .... pass .... {'age': 40, 'name': 'Zahid'} {'age': 40, 'name': 'Zahid'}
1
1148
by: Brian Blais | last post by:
Hello, I have a somewhat nested dict that I want to pickle, but it (sometimes) contains some no-no's (specifically, in this case, functions). I know I can't pickle them, but I would like to be able to pickle the rest of the dict. Is there a good way to be able to walk through a dict, and take out all of the non-pickleable objects? I could replace them with something else (a tag of some sort, for me to reconstruct things later).
0
9716
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9596
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
1
10366
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10105
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9185
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7646
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5542
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
2
3845
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3007
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.