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): - >>> words = collections.defaultdict(lambda: 1)
-
>>> f = file("temp","w")
-
>>> pickle.dump(words,f)
-
-
Traceback (most recent call last):
-
File "<pyshell#77>", line 1, in <module>
-
pickle.dump(words,f)
-
File "C:\Python25\lib\pickle.py", line 1362, in dump
-
Pickler(file, protocol).dump(obj)
-
File "C:\Python25\lib\pickle.py", line 224, in dump
-
self.save(obj)
-
File "C:\Python25\lib\pickle.py", line 331, in save
-
self.save_reduce(obj=obj, *rv)
-
File "C:\Python25\lib\pickle.py", line 401, in save_reduce
-
save(args)
-
File "C:\Python25\lib\pickle.py", line 286, in save
-
f(self, obj) # Call unbound method with explicit self
-
File "C:\Python25\lib\pickle.py", line 562, in save_tuple
-
save(element)
-
File "C:\Python25\lib\pickle.py", line 286, in save
-
f(self, obj) # Call unbound method with explicit self
-
File "C:\Python25\lib\pickle.py", line 748, in save_global
-
(obj, module, name))
-
PicklingError: Can't pickle <function <lambda> at 0x00C030B0>: it's not found as __main__.<lambda>
-
-
If I repeat the same with words = collections.defaultdict() everything goes fine..
-
-
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:
-
Traceback (most recent call last):
-
File "BayesianFilter.py", line 125, in <module>
-
pickle.dump(bf,file(sys.argv[1]+'.bf','w'))
-
File "C:\Python25\lib\copy_reg.py", line 69, in _reduce_ex
-
raise TypeError, "can't pickle %s objects" % base.__name__
-
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
3 6099
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.
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.
solution: - def give_me_1(): return 1
-
words = collections.defaultdict(give_me_1)
-
-
# the rest was good
-
f = file("temp","w")
-
pickle.dump(words,f)
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: 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...
| |
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: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
|
by: 6302768590 |
last post by:
Hai team
i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
|
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...
| |