472,777 Members | 2,643 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

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

Problem: Pickle and collections.defaultdict with default_factory set do not work

Hello all!

I have the following weird problem and since I am new to Python I somehow cannot figure out an elegant solution. The problem reduces to the following question:

How to pickle a collections.defaultdict object that has set the default_factory property?

For Example (from the IDLE console):

Expand|Select|Wrap|Line Numbers
  1. >>> words = collections.defaultdict(lambda: 1)
  2. >>> f = file("temp","w")
  3. >>> pickle.dump(words,f)
  5. Traceback (most recent call last):
  6.   File "<pyshell#77>", line 1, in <module>
  7.     pickle.dump(words,f)
  8.   File "C:\Python25\lib\pickle.py", line 1362, in dump
  9.     Pickler(file, protocol).dump(obj)
  10.   File "C:\Python25\lib\pickle.py", line 224, in dump
  11.     self.save(obj)
  12.   File "C:\Python25\lib\pickle.py", line 331, in save
  13.     self.save_reduce(obj=obj, *rv)
  14.   File "C:\Python25\lib\pickle.py", line 401, in save_reduce
  15.     save(args)
  16.   File "C:\Python25\lib\pickle.py", line 286, in save
  17.     f(self, obj) # Call unbound method with explicit self
  18.   File "C:\Python25\lib\pickle.py", line 562, in save_tuple
  19.     save(element)
  20.   File "C:\Python25\lib\pickle.py", line 286, in save
  21.     f(self, obj) # Call unbound method with explicit self
  22.   File "C:\Python25\lib\pickle.py", line 748, in save_global
  23.     (obj, module, name))
  24. PicklingError: Can't pickle <function <lambda> at 0x00C030B0>: it's not found as __main__.<lambda>
  26. If I repeat the same with words = collections.defaultdict() everything goes fine..
  28. In my real code I have a class that has an object property which is a defaultdict with the same default_factory set. I want to dump an object from this class with pickle and I get the following error: 
  29. Traceback (most recent call last):
  30.   File "BayesianFilter.py", line 125, in <module>
  31.     pickle.dump(bf,file(sys.argv[1]+'.bf','w'))
  32.   File "C:\Python25\lib\copy_reg.py", line 69, in _reduce_ex
  33.     raise TypeError, "can't pickle %s objects" % base.__name__
  34. TypeError: can't pickle function objects
If I do not set a default_factory in the constructor of the defaultdict object everything goes ok.. which makes me think that the problem is exactly this.

I know that Pickle cannot dump objects that have function properties. I did not find a way to unset the default_factory property from the defaultdict object before dumping though.. Neither I found a way to set it again after a defaultdict object was created once..

Does anyone have a clue how to resolve this issue elegantly?

Thanks for the help
Mar 21 '08 #1
3 5999
I think I understand what the issue is, but how to solve it I don't know. Why do you need to pickle the object? I have never found a use for that module myself, so I would be interested to know what it is being used for in your case. There is probably a more elegant way to save information from the program than using the pickle module.
Mar 21 '08 #2
I think I understand what the issue is, but how to solve it I don't know. Why do you need to pickle the object? I have never found a use for that module myself, so I would be interested to know what it is being used for in your case. There is probably a more elegant way to save information from the program than using the pickle module.
Basically, I need some sort of persistence layer for my program. I.e. to store objects and load them from files afterwards. I have read about the pickle module and it seems a good solution to me. If anyone knows a better way to do this, I would like to know.
Mar 24 '08 #3

Expand|Select|Wrap|Line Numbers
  1. def give_me_1(): return 1
  2. words = collections.defaultdict(give_me_1)
  4. # the rest was good
  5. f = file("temp","w")
  6. pickle.dump(words,f)
Sep 29 '10 #4

Sign in to post your reply or Sign up for a free account.

Similar topics

by: crystalattice | last post by:
I'm creating an RPG for experience and practice. I've finished a character creation module and I'm trying to figure out how to get the file I/O to work. I've read through the python newsgroup...
by: bearophileHUGS | last post by:
This post sums some things I have written in another Python newsgroup. More than 40% of the times I use defaultdict like this, to count things: .... defaultdict(<type 'int'>, {'a': 5, 'r': 2,...
by: tutufan | last post by:
It seems like x = defaultdict(defaultdict(list)) should do the obvious, but it doesn't. This seems to work y = defaultdict(lambda: defaultdict(list)) though is a bit uglier.
by: Gordon Airporte | last post by:
I was going to try tweaking defaultdict, but I can't for the life of me find where the collections module or its structures are defined. Python 2.5.
by: metaperl.com | last post by:
I'm reading http://norvig.com/spell-correct.html and do not understand the expression listed in the subject which is part of this function: def train(features): model =...
by: Mario Ceresa | last post by:
Hello everybody: I'd like to use the pickle module to save the state of an object so to be able to restore it later. The problem is that it holds a list of other objects, say numbers, and if I...
by: Matthew Wilson | last post by:
I used defaultdict.fromkeys to make a new defaultdict instance, but I was surprised by behavior: defaultdict(None, {'y': <type 'list'>, 'x': <type 'list'>}) <type 'list'> ...
by: Irmen de Jong | last post by:
I'm having troubles pickling classes that extend Exception. Given the following source: class Foo(object): def __init__(self, m): self.m=m class Bar(Exception): def __init__(self, m):
by: Danny Shevitz | last post by:
Howdy, In my app I need to exec user text that defines a function. I want this function to unpickle an object. Pickle breaks because it is looking for the object definition that isn't in the...
by: Rina0 | last post by:
Cybersecurity engineering is a specialized field that focuses on the design, development, and implementation of systems, processes, and technologies that protect against cyber threats and...
by: erikbower65 | last post by:
Using CodiumAI's pr-agent is simple and powerful. Follow these steps: 1. Install CodiumAI CLI: Ensure Node.js is installed, then run 'npm install -g codiumai' in the terminal. 2. Connect to...
by: linyimin | last post by:
Spring Startup Analyzer generates an interactive Spring application startup report that lets you understand what contributes to the application startup time and helps to optimize it. Support for...
by: Taofi | last post by:
I try to insert a new record but the error message says the number of query names and destination fields are not the same This are my field names ID, Budgeted, Actual, Status and Differences ...
by: DJRhino1175 | last post by:
When I run this code I get an error, its Run-time error# 424 Object required...This is my first attempt at doing something like this. I test the entire code and it worked until I added this - If...
by: Rina0 | last post by:
I am looking for a Python code to find the longest common subsequence of two strings. I found this blog post that describes the length of longest common subsequence problem and provides a solution in...
by: DJRhino | last post by:
Private Sub CboDrawingID_BeforeUpdate(Cancel As Integer) If = 310029923 Or 310030138 Or 310030152 Or 310030346 Or 310030348 Or _ 310030356 Or 310030359 Or 310030362 Or...
by: lllomh | last post by:
How does React native implement an English player?
by: Mushico | last post by:
How to calculate date of retirement from date of birth

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.