Lambda alternative?

Hrvoje Niksic hniksic at xemacs.org
Fri Apr 17 22:41:13 CEST 2009


"J. Cliff Dyer" <jcd at sdf.lonestar.org> writes:

> On Thu, 2009-04-16 at 13:33 +0200, Hrvoje Niksic wrote:
>> mousemeat <mousemeat at 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.

To pickle an object that contains something, that something still
needs to be picklable.

>>> import cPickle as p
>>> class X(object): pass
...
>>> x = X()
>>> x.foo = [].append
>>> p.dumps(x)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: expected string or Unicode object, NoneType found

> 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:
[...]

The object in your example doesn't contain an instance method, its
class contains a function which gets converted to a bound method
if/when it is accessed through the instance.  Pickling the object
doesn't pickle the method at all, because it's left up to the class to
provide it after unpickling.

On the other hand, the OP had a use case where he tried to pickle an
object that actually contained lambdas as part of its data, such as:

class Foo(object):
    pass

foo = Foo()
foo.a = lambda x: x+1

Now pickling foo requires pickling the lambda, which doesn't work.  My
point was that this, on its own, is no reason to avoid lambdas in
general, because by that logic one would also avoid bound methods,
which are also unpicklable.



More information about the Python-list mailing list