473,722 Members | 2,341 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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

2 New Member
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.def aultdict 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 6097
87 New Member
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
2 New Member
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 and it appears that shelve probably isn't the best option for various reasons. This lead me to try messing w/ pickle, but I can't figure out how to use it with classes. I've found many examples of using pickle w/ non-OOP code but nothing that...
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, 'b': 2, 'c': 1, 'd': 1}) But I have seen that if keys are quite sparse, and int() becomes called too much often, then code like this is faster:
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 = collections.defaultdict(lambda: 1) for f in features: model += 1 return 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 modify the list and restore the object, the list itself is not reverted to the saved one, but stays with one element deleted. An example session is the following: Data is A saving a with pickle
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'> ------------------------------------------------------------ Traceback (most recent call last):
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 calling namespace. I have mocked up a simple example that shows the problem. Run this first code (from create_pickle.py) to create the pickle. create_pickle.py: (run this first)
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,...
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
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,...
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...
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...
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
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...
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
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.