Function can return another function just like it can return any other value. This allows functions to create and return customized behavior that can be used later.
def outer():
def inner():
print("Hello")
return inner
func = outer()
func()
Output
Hello
Explanation:
- inner() is defined inside outer() and return inner returns the function itself, not the result of calling it.
- func = outer() stores the returned function in func.
- Calling func() executes the inner() function and prints "Hello".
Benefits of Returning Functions
Returning functions makes it possible to create reusable and flexible code. It is commonly used to:
- Create customized functions: Generate functions with specific behavior when needed.
- Preserve data using closures: Inner functions can access values from their enclosing function even after it has finished execution.
- Reduce code duplication: Reuse common logic instead of writing similar functions multiple times.
- Build decorators: Modify or extend the behavior of existing functions.
Examples
Example 1: The following example returns one function from another function and executes it later.
def B():
print("Inside method B")
def A():
print("Inside method A")
return B
func = A()
func()
Output
Inside method A Inside method B
Explanation:
- A() returns the function B.
- func = A() stores the returned function in func.
- Calling func() executes B().
Example 2: The following example returns a lambda function that uses values created inside the outer function.
def calc(a, b):
x = a + b
y = a - b
return lambda: x * y
func = calc(5, 2)
print(func())
Output
21
Explanation:
- calc() computes x and y.
- The returned lambda function remembers these values.
- Calling func() returns x * y, which is 21.
Example 3: The following example returns customized functions for different powers.
def power(exp):
return lambda num: num ** exp
square = power(2)
cube = power(3)
print(square(5))
print(cube(3))
Output
25 27
Explanation:
- power(2) returns a function that squares numbers.
- power(3) returns a function that cubes numbers.
- The returned functions remember the value of exp and use it when called.