473,407 Members | 2,320 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,407 software developers and data experts.

pickling subclasses of dict/list

I'm having trouble pickling subclasses of dict when they contain cycles.
In particular:
import pickle
class D(dict): pass
d = D()
d[1] = d # add a cycle.
print d {1: {...}} pickle.dump(d, open('d.pickle', 'w')) Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "/tmp/python-rSB6hN", line 6, in ?
pickle.dump(d, open('d.pickle', 'w'))
File "/usr/lib/python2.3/pickle.py", line 1382, in dump
Pickler(file, protocol, bin).dump(obj)
[...]
File "/usr/lib/python2.3/pickle.py", line 414, in save_reduce
save(func)
RuntimeError: maximum recursion depth exceeded

Note that pickling dict's that contain cycles works just fine, as does
pickling classes that contain cycles in their instance variables. E.g.:
d = {}
d[1] = d
print d
pickle.dump(d, open('d.pickle', 'w'))
print pickle.load(open('d.pickle'))

{1: {...}}

I tried several things with __getstate__, __reduce__, etc., but couldn't
get this to work. Is there some magic that I'm missing? What's the
best way to get around this? (And should I file this as a bug in
pickle? Or am I just not seeing the right way to do it?)

-Edward

Jul 18 '05 #1
1 2273
On Sat, 03 Jul 2004 14:37:28 -0400, Edward Loper
<ed*****@gradient.cis.upenn.edu> wrote:
I'm having trouble pickling subclasses of dict when they contain cycles.

Note that pickling dict's that contain cycles works just fine, as does
pickling classes that contain cycles in their instance variables. E.g.:
>>> d = {}
>>> d[1] = d
>>> print d
>>> pickle.dump(d, open('d.pickle', 'w'))
>>> print pickle.load(open('d.pickle')) {1: {...}}

I tried several things with __getstate__, __reduce__, etc., but couldn't
get this to work. Is there some magic that I'm missing? What's the
best way to get around this? (And should I file this as a bug in
pickle? Or am I just not seeing the right way to do it?)


I think the answer to this problem is to use the extended __reduce__ API
documented here:

http://www.python.org/peps/pep-0307.html

Your subclass's __reduce__ can return a dictitems (or listitems) iterator, the
items of which will get pickled after the subclass instance is memoized, thus
avoiding the infinite recursion. The following works for your simple example:
class D(dict): .... def __reduce__(self):
.... return (D, (), None, None, self.iteritems())
.... d = D()
d[1] = d
pickle.dumps(d) 'c__main__\nD\np0\n(tRp1\nI1\ng1\ns.' s = _
dd = pickle.loads(s)
dd.items()

[(1, {1: {...}})]

---
Greg Chapman

Jul 18 '05 #2

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

Similar topics

1
by: Thomas Guettler | last post by:
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()
1
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
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...
0
by: benevilent | last post by:
Hey, I am creating an extension type in C for Python, which I want it such that instances can be pickled. I basically want the functionality of the 'object' type such that subclasses of the type...
5
by: Charles Krug | last post by:
List: I have this: # classC.py class C(object): pass class D(C): pass
7
by: Daniel Nogradi | last post by:
What is the simplest way to instantiate all classes that are subclasses of a given class in a module? More precisely I have a module m with some content: # m.py class A: pass class x( A ):...
6
by: Marco Lierfeld | last post by:
Hello there, I want to save an instance of a class containing a dictionary with the pickle-module. The class looks like this: class subproject: configuration = {} build_steps = #...
0
by: dackz | last post by:
>>class ListyThing(list): pass .... Traceback (most recent call last): File "<stdin>", line 1, in <module> AssertionError <type 'list'> I don't find this intuitive. Is this intentional? I...
2
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...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
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...

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.