Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

lambda returns lambda in python

Very rarely I'll come across some code in python that uses an anonymous function which returns an anonymous function...?

Unfortunately I can't find an example on hand, but it usually takes the form like this:

g = lambda x,c: x**c lambda c: c+1

Why would someone do this? Maybe you can give an example that makes sense (I'm not sure the one I made makes any sense).

Edit: Here's an example:

swap = lambda a,x,y:(lambda f=a.__setitem__:(f(x,(a[x],a[y])),
       f(y,a[x][0]),f(x,a[x][1])))()
like image 558
HEXbutler Avatar asked Dec 06 '10 00:12

HEXbutler


2 Answers

You could use such a construct to do currying:

curry = lambda f, a: lambda x: f(a, x)

You might use it like:

>>> add = lambda x, y: x + y
>>> add5 = curry(add, 5)
>>> add5(3)
8
like image 160
Greg Hewgill Avatar answered Nov 08 '22 16:11

Greg Hewgill


It can be useful for temporary placeholders. Suppose you have a decorator factory:

@call_logger(log_arguments=True, log_return=False)
def f(a, b):
    pass

You can temporarily replace it with

call_logger = lambda *a, **kw: lambda f: f

It can also be useful if it indirectly returns a lambda:

import collections
collections.defaultdict(lambda: collections.defaultdict(lambda: collections.defaultdict(int)))

It's also useful for creating callable factories in the Python console.

And just because something is possible doesn't mean that you have to use it.

like image 39
Rosh Oxymoron Avatar answered Nov 08 '22 16:11

Rosh Oxymoron