Reputation: 33
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?
Upvotes: 0
Views: 359
Reputation: 16032
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
Upvotes: 2
Reputation: 9027
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.
Upvotes: 0
Reputation: 19352
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:
nolambda
outside the make_incrementor
function, so it does not have the closurenolambda
lambda
returns x + n
, whereas the nolambda
returns just x
The following would be equivalent to the example with lambda:
def make_incrementor(n):
def nolambda(x):
return x + n
return nolambda
Upvotes: 2