Lambda alternative?

J. Cliff Dyer jcd at sdf.lonestar.org
Fri Apr 17 14:43:04 EDT 2009


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.

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:

Python 2.5.2 (r252:60911, Oct  5 2008, 19:29:17) 
[GCC 4.3.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import cPickle as p
>>> class Foo(object):
...     a = lambda self, x: x+1
>>> foo.a(1)
2
>>> type(foo.a)
<type 'instancemethod'>
>>> p.dumps(foo)
'ccopy_reg\n_reconstructor\np1\n(c__main__\nFoo\np2\nc__builtin__
\nobject\np3\nNtRp4\n.'

Cheers,
Cliff





More information about the Python-list mailing list