On Apr 17, 1:43 pm, "J. Cliff Dyer" <j...@sdf.lonestar.org> wrote: > On Thu, 2009-04-16 at 13:33 +0200, Hrvoje Niksic wrote: > > mousemeat <mousem...@gmail.com> writes: > > > > Correct me if i am wrong, but i can pickle an object that contains a > > > bound method (it's own bound method). > > > No, you can't: > > > >>> import cPickle as p > > >>> p.dumps([]) > > '(l.' > > >>> p.dumps([].append) > > Traceback (most recent call last): > > File "<stdin>", line 1, in <module> > > TypeError: expected string or Unicode object, NoneType found > > Yes he can. mousemeat stated that he could pickle an object that > *contains* a bound method, not that he could pickle the method itself. > > That said, you can make an instance method out of a lambda, just as well > as any named function, and you can pickle that object, too: snip
'Contains' here is ambiguous. If the object contains a bound method, that is, if a bound method is in its dictionary, you can't. >>> import pickle as p >>> class A: pass ... >>> a= A() >>> class A: ... def f( self ): print( 'f' ) ... >>> a= A() >>> class B: pass ... >>> b= B() >>> b.f= a.f >>> b.f() f >>> p.dumps( b ) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "C:\Programs\Python30\lib\pickle.py", line 1329, in dumps Pickler(f, protocol).dump(obj) _pickle.PicklingError: Can't pickle <class 'method'>: attribute lookup builtins.method failed In this example, 'b' contains a bound method, 'a.f'. However, for other definitions of 'contains', such as if 'b' is an instance of a class that contains methods, you can. But in that case, the method is not in 'b.__dict__'. >>> b.__dict__ {'f': <bound method A.f of <__main__.A object at 0x00B54B90>>} -- http://mail.python.org/mailman/listinfo/python-list