How a Python Function Can Return a Function



In Python, functions are treated as first-class objects, which means that all functions in Python are treated like any other object or variable. You can assign a function to a variable, pass it as an argument to another function, return it from a function, or even store it in data structures like lists.

One very useful feature in Python is that a function can return another function. This means you can define a function inside another function and return it as a result. This is used in advanced programming concepts like closures, decorators, and higher-order functions.

Returning a Simple Function

In Python, you can define a function inside another function. The inner function can be returned by the outer function. This means you are not calling (running) the inner function right away, you are just sending it back so that it can be used later.

This is useful when you want to create different behaviors based on conditions or inputs. The outer function creates the inner function and returns it back, and then you can run that returned function whenever you need it.

Example

In this example, the outer() function creates another function called inner() and returns it without calling it, and we store this returned function in the variable my_func, which we can then call later using my_func() to run the inner() function -

def outer():
   def inner():
      print("Hello from the inner function!")
   # returning the function, not calling it	  
   return inner  

# Store the returned function in a variable
my_func = outer()

# Now call the returned function
my_func()

The output of the above code is -

Hello from inner function!

Returning Functions Based on Conditions

You can also return different inner functions based on some condition. This means the outer function decides which inner function to return depending on the input or logic.

This is useful when you want to create different behaviors based on different situations. You don't have to run the chosen function right away; you just return it and then call it later when needed.

This technique is used in things like decision-making, routing options, or handling different user choices.

Example

Here, the get_operation() function returns different functions based on the operation name -

# Outer function returns different functions
def get_operation(op):
   def add(a, b):
      return a + b
   def subtract(a, b):
      return a - b

   if op == "add":
      return add
   else:
      return subtract

# Get the add function
f = get_operation("add")
print(f(10, 5))  

# Get the subtract function
g = get_operation("subtract")
print(g(10, 5))  

The output will be -

15
5

Using Closures

When a function returns another function and the inner function remembers the variables from the outer function, it is called a closure. Closures are very useful for keeping some data private or creating function factories.

The inner function can still use the values from the outer function even after the outer function has finished executing.

Example

In the example below, the outer function make_multiplier() returns a function that multiplies its input by a fixed number -

# Closure example
def make_multiplier(x):
   def multiplier(n):
      return x * n
   return multiplier

# Create two multiplier functions
double = make_multiplier(2)
triple = make_multiplier(3)

print(double(5))  
print(triple(5))  

We get the following output -

10
15

Functions Returning Lambda Functions

You can also return lambda functions from another function. A lambda function is a small anonymous function that can be defined in one line. This is useful when you want to return simple functions without defining them with def.

This is a common technique used in functional programming to create dynamic behavior.

Example

In this example, we return a lambda function that performs a power operation -

# Function returning a lambda
def power_function(exp):
   return lambda x: x ** exp

# Create square and cube functions
square = power_function(2)
cube = power_function(3)

print(square(4))  
print(cube(2))    

The output is as follows -

16
8

Understanding Higher-Order Functions

A higher-order function is a function that either takes another function as an argument or returns a function as a result. Built-in Python functions like map(), filter(), and sorted() are examples of higher-order functions.

Example

Here is a custom higher-order function that takes a function and applies it to each item in a list -

# Higher-order function example
def apply_to_list(func, values):
   return [func(v) for v in values]

# Function to square a number
def square(n):
   return n * n

nums = [1, 2, 3, 4]
print(apply_to_list(square, nums)) 

The output will be -

[1, 4, 9, 16]

Using Decorators

Decorators are a special form of higher-order functions. A decorator is a function that takes another function and adds extra functionality to it without changing its original structure. In Python, decorators are used for logging, authentication, or modifying input/output behavior.

Decorators use the @decorator_name syntax above the function they modify.

Example

In the following example, the decorator log_decorator() adds logging to a simple function -

# Decorator example
def log_decorator(func):
   def wrapper(*args, **kwargs):
      print("Calling function:", func.__name__)
      result = func(*args, **kwargs)
      print("Function executed")
      return result
   return wrapper

@log_decorator
def greet(name):
   print("Hello,", name)

greet("Alice")

The output will be -

Calling function: greet
Hello, Alice
Function executed
Updated on: 2025-04-14T15:45:33+05:30

18K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements