473,407 Members | 2,312 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.

pickle and instancemethod objects

I'd like to be able to pickle instancemethod objects mainly because I
want to be able to delay a call like ``foo(spam, badger)`` by dumping
``foo``, ``spam`` and ``badger`` to disk and loading them again later.
Sometimes the callable ``foo`` is actually a bound method, e.g.
``bar.baz``, but in such cases, pickle doesn't work by default because
it doesn't know how to pickle/unpickle instancemethod objects.

I was thinking of doing something like::
>>def pickle_instancemethod(method):
.... func_name = method.im_func.__name__
.... cls = method.im_class
.... obj = method.im_self
.... return unpickle_instancemethod, (func_name, cls, obj)
....
>>def unpickle_instancemethod(func_name, cls, obj):
.... if obj is None:
.... return getattr(cls, func_name)
.... else:
.... return getattr(obj, func_name)
....
>>class C(object):
.... def __init__(self, foo, bar):
.... self.foo = foo
.... self.bar = bar
.... def baz(self):
.... return self.foo, self.bar
....
>>copy_reg.pickle(type(C.baz),
.... pickle_instancemethod,
.... unpickle_instancemethod)

This seems to basically do the right thing on the few simple things I've
tried::
>>c = C(42, 'badger')
new_c_baz = pickle.loads(pickle.dumps(c.baz))
new_c_baz()
(42, 'badger')
>>new_C_baz = pickle.loads(pickle.dumps(C.baz))
new_C_baz(C('eki', 'fekang'))
('eki', 'fekang')

Does this approach seem sound? Am I going to run into some weird
problems doing it this way?

Thanks,

STeVe
Sep 13 '06 #1
2 2124
Steven Bethard schrieb:
Does this approach seem sound? Am I going to run into some weird
problems doing it this way?
It's good, but I think rebuilding the object through
new.instancemethod should be even better.

pyclass A:
.... def f(self):print "A"
....
pyclass B(A):
.... def f(self):print "B"
....
pyb=B()
pyb.f
<bound method B.f of <__main__.B instance at 0xa7d728cc>>
pyx = new.instancemethod(A.__dict__['f'], b, A)
pyx
<bound method A.f of <__main__.B instance at 0xa7d728cc>>
pyx()
A
pyb.f()
B
pyx.im_func.__name__,x.im_class,x.im_self
('f', <class __main__.A at 0xa7d7002c>, <__main__.B instance at 0xa7d728cc>)

On unpickling x, you'ld get x.(B.f), not x.(A.f) with your
approach.

Not sure it matters much.

Regards,
Martin
Sep 13 '06 #2
Martin v. Löwis wrote:
Steven Bethard schrieb:
>Does this approach seem sound? Am I going to run into some weird
problems doing it this way?

It's good, but I think rebuilding the object through
new.instancemethod should be even better.

pyclass A:
... def f(self):print "A"
...
pyclass B(A):
... def f(self):print "B"
...
pyb=B()
pyb.f
<bound method B.f of <__main__.B instance at 0xa7d728cc>>
pyx = new.instancemethod(A.__dict__['f'], b, A)
pyx
<bound method A.f of <__main__.B instance at 0xa7d728cc>>
pyx()
A
pyb.f()
B
pyx.im_func.__name__,x.im_class,x.im_self
('f', <class __main__.A at 0xa7d7002c>, <__main__.B instance at 0xa7d728cc>)

On unpickling x, you'ld get x.(B.f), not x.(A.f) with your
approach.

Not sure it matters much.
Probably doesn't matter for my particular use, but it certainly wouldn't
hurt to do it the careful way. Thanks.

Is new.instancemethod basically equivalent to calling __get__? That is,
would the following two unpickle_instancemethod functions do the same thing?

def unpickle_instancemethod(func_name, cls, obj):
return cls.__dict__[func_name].__get__(obj, cls)

def unpickle_instancemethod(func_name, cls, obj):
return new.instancemethod(cls.__dict__[func_name], obj, cls)

Thanks again,

STeVe
Sep 13 '06 #3

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

Similar topics

2
by: Boris Borcic | last post by:
Assuming that the items of my_stream share no content (they are dumps of db cursor fetches), is there a simple way to do the equivalent of def pickles(my_stream) : from cPickle import...
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?
5
by: Chris | last post by:
Why can pickle serialize references to functions, but not methods? Pickling a function serializes the function name, but pickling a staticmethod, classmethod, or instancemethod generates an...
3
by: fizilla | last post by:
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...
2
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...
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 =...
1
by: srinivasan srinivas | last post by:
Hi, I would like to know how to pickle a bound method?? Thanks, Srini Meet people who discuss and share your passions. Go to http://in.promos.yahoo.com/groups/bestofyahoo/
1
by: srinivasan srinivas | last post by:
No. It does not work. def make_staticmethod(inst, methodname):     return getattr(inst, methodname) def pickle_function(method):     return make_staticmethod, (method.im_self,...
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...
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...
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
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
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...
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
agi2029
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,...
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.