'Lambda in a function
I am following the Python tutorial.
def make_incrementor(n):
return lambda x: x + n
Result:
f = make_incrementor(42)
print(f(1))
43
print(type(f))
<class 'function'>
Now consider we will replace the lambda expression by a regular function
def nolambda(x):
return x
def make_incrementor(n):
return nolambda(n)
f = make_incrementor(42)
print(type(f))
<class 'int'>
In the first case it returned <class 'function'>
but in the second it returned <class 'int'>
It only points to the lamba expression in the first case and do not execute it (ok, it would raise an error because of the missing argument). I could understand that but it returns an int
rather than a function
in the second example, so it is very strange to me. Could you explain what's going on?
Solution 1:[1]
In the first example, you are returning a callable (ie. the lambda function).
In the second example, you are calling the nolambda
function, which means that the return value of make_incrementor
will be the same value returned by nolambda
.
To better understand, try looking at it like this:
def make_incrementor(n):
def some_function(x):
return x + n
return some_function
def make_incrementor(n):
some_return_value = nolambda(n)
return some_return_value
Solution 2:[2]
In this code, the lambda function "sees" the argument x
and the variable n
, which is in the lambda's closure:
def make_incrementor(n):
return lambda x: x + n
In the other example, you have made three differences, which cause different behaviour:
- you placed the function
nolambda
outside themake_incrementor
function, so it does not have the closure - in the first example, you return the function itself (i.e. the lambda, which is a function), and in the second you return the result of
nolambda
- the
lambda
returnsx + n
, whereas thenolambda
returns justx
The following would be equivalent to the example with lambda:
def make_incrementor(n):
def nolambda(x):
return x + n
return nolambda
Solution 3:[3]
In the first example, where you return lambda x: x + n
, you're returning a callable
(i.e. anonymous function) without an invocation – the callable maps the input parameter, n
, to the lambda
function but does not actually get invoked. In the second, you are returning the invoked function, because you're actually calling it by using parentheses within the make_incrementor
function's body.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | juanpa.arrivillaga |
Solution 2 | zvone |
Solution 3 |