473,404 Members | 2,137 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,404 software developers and data experts.

Why can't pickle dump this instance?

Hi.

class A:
def __init__(self,tick):
if tick:
self.foo=self.bar
else:
self.foo=self.bur
def bar(self):
print 'bar'
def bur(self):
print 'bur'

import pickle
pickle.dumps(A())

running this script results in "TypeError: can't pickle function objects"

Why does this happen? and what can I do?

Jane
Jul 18 '05 #1
2 9814
On Thu, 12 Aug 2004 22:46:27 -0700, Jane Austine wrote:
class A:
def __init__(self,tick):
if tick:
self.foo=self.bar
else:
self.foo=self.bur
def bar(self):
print 'bar'
def bur(self):
print 'bur'

import pickle
pickle.dumps(A())

running this script results in "TypeError: can't pickle function objects"

Why does this happen? and what can I do?


Running this script should actually result in

TypeError: __init__() takes exactly 2 arguments (1 given)

because you did not write

def __init__(self, tick=None):
But coming back to your original problem, have a look at the
following code:

def bar():
print 'bar'

def bur():
print 'bur'

class A:
def __init__(self,tick=None):
if tick:
self.foo=bar
else:
self.foo=bur

import pickle
pickle.dumps(A())

The above will do what you want. Have a look at the Python
Library Reference's

3.14.4 What can be pickled and unpickled?
http://www.python.org/doc/2.3.4/lib/node65.html

to see, why this works while the other script does not.

HTH, Th.

Jul 18 '05 #2
Jane Austine wrote:
class A:
def __init__(self,tick):
if tick:
self.foo=self.bar
else:
self.foo=self.bur
def bar(self):
print 'bar'
def bur(self):
print 'bur'

import pickle
pickle.dumps(A())

running this script results in "TypeError: can't pickle function objects"

Why does this happen? and what can I do?


By default pickle bypasses the __init__() method completely, it just saves
class name and the instance's __dict__. In your case __dict__ happens to
contain a bound method which cannot be pickled. I don't know why, maybe the
general case where the instance the method is bound to could be a different
object would get too messy.

The normal way to manipulate the state to be pickled/unpickled is to
implement the __getstate__()/__setstate__() pair, but in your case it is
easier to trigger invocation of __init__() by generating the appropriate
argument list via __getinitargs__().

Peter

<code>
import pickle

class A:
def __init__(self, tick):
if tick:
self.foo = self.bar
else:
self.foo = self.bur

def __getstate__(self):
# copy the __dict__ so that further changes
# do not affect the current instance
d = dict(self.__dict__)
# remove the closure that cannot be pickled
del d["foo"]
# return state to be pickled
return d

def __getinitargs__(self):
tick = self.foo == self.bar
# return argument tuple for __init__()
# all items must be pickleable
return (tick,)

def bar(self):
print "bar"
def bur(self):
print "bur"

if __name__ == "__main__":
# test it
for tick in [False, True]:
print "\ntick =", tick
a = A(tick)
a.foo()
s = pickle.dumps(a)
b = pickle.loads(s)
b.foo()
</code>
Jul 18 '05 #3

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

Similar topics

6
by: Rene Mansveld | last post by:
Hi, how can I create an instance (object) of a class (form) if I only know the classname (VB.NET 1.0)? I need to do this in a complex app where jobs consist of parts. Each part's data is saved...
18
by: Sandra-24 | last post by:
Can you create an instance of a subclass using an existing instance of the base class? Such things would be impossible in some languages or very difficult in others. I wonder if this can be done...
6
by: Jim Lewis | last post by:
Pickling an instance of a class, gives "can't pickle instancemethod objects". What does this mean? How do I find the class method creating the problem?
4
by: Ashish | last post by:
Can i create two instance with same user id in AIX ? I just need what should be the params to be passed in db2icrt utility.. Thanks in Advance Ashish Prasad
20
by: Boki Digtal | last post by:
Hi All, How to limit the c# program can only run one instance at the same time ? Thank you! Best regards, Boki.
0
by: eso40043 | last post by:
Hello, due to a memory leak (bug, I guess) in pyraf(or rather in IRAF) I have to fork an iterative process that goes through hundreds of image frames and does unspeakable things to them. In the...
2
by: Michele Simionato | last post by:
Can somebody explain what's happening with the following script? $ echo example.py import pickle class Example(object): def __init__(self, obj, registry): self._obj = obj self._registry =...
10
by: est | last post by:
>>import md5 Traceback (most recent call last): File "<stdin>", line 1, in <module> File "C:\Python25\lib\pickle.py", line 1366, in dumps Pickler(file, protocol).dump(obj) File...
1
by: IceMan85 | last post by:
Hi to all, I have spent the whole morning trying, with no success to pickle an object that I have created. The error that I get is : Can't pickle 'SRE_Match' object: <_sre.SRE_Match object at...
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
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
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,...
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
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...
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.