Returning Functions from Functions in Python
In Python, functions are first-class objects, meaning they can be assigned to variables, passed as arguments, or even returned from other functions. This feature is widely used in callbacks, closures, decorators, and factory functions.
Why Return a Function?
Returning a function allows you to:
- Encapsulate logic: Return customized functions without rewriting code.
- Preserve state (closures): Inner functions can remember values from the outer scope.
- Write cleaner, reusable code: Instead of duplicating logic, you can generate functions on the fly.
- Enable decorators: A powerful way to modify or enhance behavior of other functions.
Example 1: Basic Function Returning Another Function
def fun1(name):
def fun2():
return f"Hello, {name}!"
return fun2
# Get the function returned by fun1()
msg = fun1("Emma")
print(msg())
Output
Hello, Emma!
Explanation:The function fun1 creates another function fun2 inside it and returns it. When we call msg(), it runs fun2, which uses the name we passed ("Emma") and returns the greeting "Hello, Emma!", which is then printed.
Example 2: Returning a Function Without Arguments
def B():
print("Inside the method B.")
def A():
print("Inside the method A.")
return B # function A returns function B
return_fun = A()
return_fun()
Output
Inside the method A. Inside the method B.
Explanation:Here, A() returns the function B. When assigned to return_fun, we can later call it as return_fun().
Example 3: Returning a Function with Arguments
def B(st2):
print("Good " + st2 + ".")
def A(st1, st2):
print(st1 + " and ", end="")
B(st2) # call B with st2
A("Hello", "Morning")
Output
Hello and Good Morning.
Explanation: This example shows how one function (A) can call another function (B) and pass arguments to it. Function A prints its own message and then uses B to print an additional message.
Example 4: Returning a Lambda Function
The function A calculates values w and z and returns a lambda function (an anonymous function) that multiplies w and z when called.
def A(u, v):
w = u + v
z = u - v
return lambda: print(w * z) # return lambda
return_fun = A(5, 2)
print(return_fun) # prints function object
return_fun() # execute lambda
Output
<function A.<locals>.<lambda> at 0x7f17a634f380> 21
Explanation:
- return_fun = A (5, 2) stores the returned lambda function.
- return_fun prints the function object.
- return_fun() executes the lambda and prints the result (w * z).
Example 5: Creating a Custom Power Function (Practical Example)
The power function returns a new function (a lambda) that raises a number to the given exponent.
def power(exp):
return lambda base: base ** exp
s = power(2)
c = power(3)
print(s(5))
print(c(3))
Output
25 27
Explanation:
- power(2) returns a function that squares numbers.
- power(3) returns a function that cubes numbers.