Gui
Gui

Reputation: 33

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?

Upvotes: 0

Views: 359

Answers (3)

Lord Elrond
Lord Elrond

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

Greenstick
Greenstick

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

zvone
zvone

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:

  • you placed the function nolambda outside the make_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 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

Related Questions