How can a Python function return a function?


Python supports first-class functions. In fact, all functions in python are first- class functions. Python may return functions from functions, store functions in collections such as lists and generally treat them as you would any variable or object. A function can return a function in Python because functions are treated as first-class objects. This means that you can assign a function to a variable, pass it as an argument to another function, or use it as a return value in a function. Defining functions in other functions and returning functions are all possible.

In this code, the outer function defines and returns the inner function. You can then call the outer function and assign its return value to a variable:

Now, f is a reference to the inner function. You can call it like any other function:

Example

def outer():
   def inner():
      print("Hello from inner!")
   return inner
f = outer()
f()

Output

Hello from inner!

Using arguments with returned functions

You can use arguments with returned functions in different ways. One way is to pass arguments to the outer function and use them inside the inner function.

In this code, the outer function takes an argument x and returns a function that prints its value. You can call it like this −

Example

def outer(x):
   def inner():
      print("x is", x) 
   return inner
f = outer(10)
f()

Output

x is 10

Another way is to pass arguments to the inner function when you call it.

In this code, the outer function returns a function that takes an argument y and prints its value. You can call it like this

Example

def outer():
   def inner(y):
      print("y is", y) 
   return inner
f = outer()
f(20)

Output

y is 20

Higher-Order Functions

In Python, a function can return another function as its result. This is known as a "higher-order function".

Example

def adder(x):
   def inner(y):
      return x + y 
   return inner

In this example, we define a function called adder that takes a single argument, x. Inside adder, we define another function called inner, which takes a single argument y and returns the sum of x and y.

Instead of returning the sum directly, adder returns the inner function itself. This means that when we call adder(1), for example, we get back a new function that adds 1 to its argument

Returning Functions from Functions in Python

To return a function from a function in Python, you can define a new function inside the first function and then return it. This technique is called nested functions or closures. The returned function can then be assigned to a variable and called later.

Example

def adder(x):
   def inner(y):
      return x + y 
   return inner

add_one = adder(1)
print(add_one(5))
# prints 6

Output

6

In this example, adder is a function that takes an argument x and returns a new function inner. The inner function takes an argument y and returns the sum of x and y. When we call adder(1), it returns a new function object inner with x set to 1. We can then assign this new function object to a variable add_one and call it with an argument of 5, which results in the output of 6.

Overall, this pattern can be useful for writing more flexible and reusable code, especially when combined with other higher-order programming concepts like closures and currying.

Example

def create_multiplier(factor):
   def multiplier(number):
      return number * factor
   return multiplier

double = create_multiplier(2) 
triple = create_multiplier(3)

print(double(5))	# Output: 10
print(triple(5))	# Output: 15

Output

10
15

In this example, create_multiplier() is a function that takes a factor argument and returns a new function multiplier(). The multiplier function takes a number argument and returns the result of multiplying number by factor. We create two new functions double and triple by calling create_multiplier() with different factors. We can then call these functions with different numbers to get the desired output.

It must be noted that when we call create_multiplier(), it returns a new function object each time. This means that double and triple are distinct functions even though they were created using the same create_multiplier() function.

Returning a Function from a Function in Python

Returning a function from a function in Python can be a powerful tool for creating flexible and reusable code. By returning a function, we can abstract away the details of how the function works and provide a more high-level interface to the user. In this article, we'll explore how to return a function from a function in Python using nested functions or lambda functions.

Example: Nested Functions

def adder(x):
   def inner(y):
      return x + y 
   return inner

add_one = adder(1) 
print(add_one(5))	# prints 6

Output

6

In this example, adder is a function that takes an argument x and returns a new function inner. The inner function takes an argument y and returns the sum of x and y. When we call adder(1), it returns a new function object inner with x set to 1. We then assign this new function to the variable add_one. When we call add_one(5), it's equivalent to calling inner(5) with x set to 1.

Overall, this pattern can be useful for writing more flexible and reusable code, especially when combined with other higher-order programming concepts like closures and currying.

Here's another example of a function that returns a function in Python, but this time using lambda functions

Example: Lambda Functions

def make_incrementor(n):
   return lambda x: x + n

increment_by_five = make_incrementor(5)
increment_by_ten = make_incrementor(10)

print(increment_by_five(3))	# Output: 8 
print(increment_by_ten(3))	# Output: 13

Output

8
13

In this example, make_incrementor() is a function that takes an argument n and returns a lambda function that takes an argument x and returns the sum of x and n. When we call make_incrementor(5), it returns a new lambda function object that adds 5 to its argument. We then assign this new function to the variable increment_by_five(). When we call increment_by_five(3), it's equivalent to calling (lambda x: x + 5)(3).

By returning a function from a function, we can create more flexible and reusable code in Python. Whether you use nested functions or lambda functions, the ability to return functions as values is a powerful tool in your programming arsenal.

In summary, returning a function from a function in Python can be done using nested functions or lambda functions, and it allows us to create more flexible and reusable code. By returning a function, we can abstract away the details of how the function works and provide a more high-level interface to the user.

Updated on: 31-Aug-2023

13K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements