kaihami
kaihami

Reputation: 815

Transforming lambda expression to simple function

I'm curious if it is possible to avoid lambda expressions in the following case.

For example using lambda expression I can simple define a function that returns a lambda exp.

def square_fun(a,b,c):
   return lambda x: a*x**2 + b*x + c

After we can call it using:

f = square_fun(1,2,3)

f(1) # here x = 1

How can I get the same behaviour avoiding lambda expression?

for example, square_fun must return another function

def square_fun(a,b,c):
   return f...

Upvotes: 1

Views: 73

Answers (2)

David Robles
David Robles

Reputation: 9607

You can also use functools.partial:

from functools import partial


def square_fun(x, a, b, c):
    return a * x ** 2 + b * x + c


f = partial(square_fun, a=1, b=2, c=3)
print(f(1))
# should print 6

Upvotes: 4

slackmart
slackmart

Reputation: 4924

In python you can define a function inside another function, so the following snippet should give you the same behavior:

def square_fun(a, b, c):
    def result(x):
        return a*x**2 + b*x + c
    return result

f = square_fun(1, 2, 3)
print(f(1))
# Should print 6

So, I'll try to explain what's going on here:

  1. In the line f = square_fun(1, 2, 3), f will actually be mapped to the internal function (aka. result)
  2. Please note that return result does not have the () at the end, hence the function is not called yet
  3. The function gets called in print(f(1)) and the variable x takes 1 as its value
  4. Finally the result function returns the computed value using x, and a, b and c (from square_fun(1, 2, 3))

You can find additional info here => https://www.learnpython.org/en/Closures

Upvotes: 7

Related Questions