VOOZH about

URL: https://www.geeksforgeeks.org/python/returning-a-function-from-a-function-python/

⇱ Returning Functions from Functions in Python - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Returning Functions from Functions in Python

Last Updated : 8 Jun, 2026

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.


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.


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.


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.


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.

Related Articles:

Comment