🌐
Analytics Vidhya
analyticsvidhya.com › home › how nested functions are used in python?
How nested functions are used in Python? - Analytics Vidhya
March 4, 2025 - For example, in Python: def outer_function(x): def inner_function(y): return x + y return inner_function Here, inner_function is nested inside outer_function and can access variables from its enclosing scope, like x.
🌐
Dive into Python
diveintopython.org › home › learn python programming › functions in python › nested functions
Nested Functions in Python - Powerful Tool for Organized Code
May 3, 2024 - In this example, square is a nested function. It is defined inside exponential. exponential takes in a parameter x. exponential returns the square of x raised to the fourth power. square takes in a parameter y. It returns the square of y. When ...
Discussions

Nested Function in Python - Stack Overflow
However, the code you've posted ... the function immediately and returns the result, rather than the callable. It might be useful to post the actual code you saw. ... I've added a link to the original code in a comment on my question. As you can see, mine is a simplified example, but it's still almost the same. 2009-10-20T08:06:32.127Z+00:00 ... In Python, you can use a nested function to ... More on stackoverflow.com
🌐 stackoverflow.com
Python Nested Functions and Namespacing - A Guide with Examples - freeCodeCamp Contributors - The freeCodeCamp Forum
Namespaces A function’s parameters, plus any variables that are bound (by assignment or by other binding statements, such as def) in the function body, make up the function’s local namespace, also known as local scope. Each of these variables is known as a local variable of the function. More on forum.freecodecamp.org
🌐 forum.freecodecamp.org
0
June 30, 2026
python - Real-world examples of nested functions - Stack Overflow
I asked previously how the nested functions work, but unfortunately I still don't quite get it. To understand it better, can someone please show some real-wold, practical usage examples of nested More on stackoverflow.com
🌐 stackoverflow.com
Thoughts on nested / inner functions in Python for better encapsulation and clarity?
You seem very receptive to feedback and understanding how code “feels” to people, so I’ll be direct. It is hard to get across how much I hate this code. Look at those type hints. So many options! I get that you’re trying to make things flexible, but all of this variety of types makes things so much harder to follow. People end up passing around strings, users, lists of strings, lists of users and nulls all over the place instead of having one clear place for casting. If I want to reuse process_recipients I can’t. If I want to test it, I can’t. You could rename it to something like cast_to_emails_list and have this one reusable “takes anything” function. Your inner functions are more polluted because they have access to more outer scope variables. You’re more likely to be bitten by typos and other mistakes. The keyword only arguments are fine on send_mail since that’s so ripe for mistakes. It’s silly on process_recepients. The likelihood that someone will mix up the order of positional arguments on a function with one argument is… low. Other ways to achieve your goals: Give your functions more descriptive names, as in this name helps me understand what the function does if I didn’t know already. Use a doc string if needed. Give functions a leading underscore to mark them as a private. But consider if you need to do this. You’re not really making someone’s life easier by giving them less tools that are useful. It’s just if you don’t want it to be something supported outside of the scope of that module. __all__ is similar. Have one input type for arguments unless the role of the function is casting/deserialization (single responsibility). It’s fine to have some “helpers” module for stuff that isn’t part of the “main story”. A hint that you’re doing it right is you don’t end up with circular imports there. Check out Grokking Simplicity. I think you’ll like it. You have good instincts, just need to see some ways other people have solved the same problems. More on reddit.com
🌐 r/Python
72
173
January 8, 2023
🌐
Stack Abuse
stackabuse.com › python-nested-functions
Python Nested Functions
December 21, 2018 - In the rest of the article, we will use the word "inner function" and "nested function" interchangeably. There are various reasons as to why one would like to create a function inside another function. The inner function is able to access the variables within the enclosing scope. In this article, we will be exploring various aspects of inner functions in Python. To define an inner function in Python, we simply create a function inside another function using the Python's def keyword. Here is an example:
🌐
Berkeley
pythonnumericalmethods.studentorg.berkeley.edu › notebooks › chapter03.03-Nested-Functions.html
Nested functions — Python Numerical Methods
Notice that the variables x and y appear in both my_dist_xyz and my_dist. This is permissible because a nested function has a separate memory block from its parent function. Nested functions are useful when a task must be performed many times within the function but not outside the function.
🌐
Python Morsels
pythonmorsels.com › nested-functions
Nested functions in Python - Python Morsels
June 10, 2026 - When a function is defined within a function and the inner function accesses variables from the outer function, Python uses a "closure" to keep track of those variables that are defined just outside the inner function, in its enclosing scope. You mostly don't need to think about a function's enclosing scope or think about the closure that it makes. Closures are something that happens behind the scenes and they pretty much just make nested functions work the way we would expect them to. For example, here's another function that defines an inner function and returns it:
🌐
TutorialsPoint
tutorialspoint.com › How-do-nested-functions-work-in-Python
How do nested functions work in Python?
September 28, 2023 - Simply use the def keyword to initialize another function within a function to define a nested function. The following program demonstrates the inner function in Python − · # creating an outer function def outerFunc(sample_text): sample_text = sample_text # creating an inner function def innerFunc(): # Printing the variable of the parent class(outer class) print(sample_text) # calling inner function innerFunc() # Calling the outer Function by passing some random name outerFunc('Hello tutorialspoint python')
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-inner-functions
Python Inner Functions - GeeksforGeeks
May 22, 2026 - Example: This example shows an inner function where the inner function prints a message from the outer function. ... # outer function def fun1(msg): # inner function def fun2(): # access variable from outer scope print(msg) fun2() fun1("Hello") ...
🌐
freeCodeCamp
freecodecamp.org › news › nested-functions-in-python
Nested Functions in Python
January 6, 2020 - When you nest a function like this, it's hidden from the global scope. Because of this behavior, data encapsulation is sometimes referred to as data hiding or data privacy. For example:
Find elsewhere
🌐
Programiz
programiz.com › python-programming › closure
Python Closures (With Examples)
In the above example, we have defined the display_name() function inside the greet() function. Here, display_name() is a nested function. The nested function works similar to the normal function.
🌐
Real Python
realpython.com › inner-functions-what-are-they-good-for
Python Inner Functions: What Are They Good For? – Real Python
2 weeks ago - You can also create higher-order functions in Python. Higher-order functions are those that operate on other functions by taking them as arguments, returning them, or both. The examples of inner functions that you’ve seen so far are ordinary functions that happen to be nested inside other functions.
🌐
DataCamp
campus.datacamp.com › courses › introduction-to-functions-in-python › default-arguments-variable-length-arguments-and-scope
Nested functions | Python
Let's now look at another important use case of nested functions. In this example, we define a function raise_vals, which contains an inner function called inner. Now look at what raise_vals returns: it returns the inner function inner! raise_vals takes an argument n and creates a function inner that returns the nth power of any number.
🌐
Flavio Copes
flaviocopes.com › home › python › python nested functions
Python Nested Functions - Flavio Copes
August 7, 2026 - Learn how nested functions work in Python: defining a function inside another to hide local helpers, and using nonlocal to reach the outer variables.
🌐
Medium
medium.com › devtechie › nested-functions-in-python-52d9b0938bb3
Nested functions in Python. This article takes on nested functions… | by DevTechie | DevTechie | Medium
November 22, 2023 - def outer_function(): # this is outer function or enclosing function def inner_function(): # this is inner or nested function print ("Hello from nested (inner) function.") # definition of inner function ends here print ("Hi from enclosing (outer) function.") # call the nested function inner_function() Calling the inner function outside the body of the outer function will raise an error. For example,
🌐
freeCodeCamp
forum.freecodecamp.org › freecodecamp contributors
Python Nested Functions and Namespacing - A Guide with Examples - freeCodeCamp Contributors - The freeCodeCamp Forum
June 30, 2026 - Namespaces A function’s parameters, plus any variables that are bound (by assignment or by other binding statements, such as def) in the function body, make up the function’s local namespace, also known as local scope. Each of these variables is known as a local variable of the function.
🌐
Medium
medium.com › @tanishf24comp › nested-functions-and-their-use-cases-43d799f0de04
Nested Functions and Their Use Cases | by Tanish Fitkariwala | Medium
October 23, 2025 - The utility of nested functions is rooted in how they interact with the enclosing function’s scope — the region of code where a variable is accessible. In Python, the scope resolution follows the LEGB rule: Local $\rightarrow$ Enclosing $\rightarrow$ Global $\rightarrow$ Built-in.
🌐
Linux Hint
linuxhint.com › nested-functions-python
Linux Hint – Linux Hint
September 1, 2021 - Linux Hint LLC, [email protected] 1210 Kelly Park Circle, Morgan Hill, CA 95037 Privacy Policy and Terms of Use
Top answer
1 of 8
10

Your question made me curious, so I looked in some real-world code: the Python standard library. I found 67 examples of nested functions. Here are a few, with explanations.

One very simple reason to use a nested function is simply that the function you're defining doesn't need to be global, because only the enclosing function uses it. A typical example from Python's quopri.py standard library module:

def encode(input, output, quotetabs, header = 0):
    ...
    def write(s, output=output, lineEnd='\n'):
        # RFC 1521 requires that the line ending in a space or tab must have
        # that trailing character encoded.
        if s and s[-1:] in ' \t':
            output.write(s[:-1] + quote(s[-1]) + lineEnd)
        elif s == '.':
            output.write(quote(s) + lineEnd)
        else:
            output.write(s + lineEnd)

    ...  # 35 more lines of code that call write in several places

Here there was some common code within the encode function, so the author simply factored it out into a write function.


Another common use for nested functions is re.sub. Here's some code from the json/encode.py standard library module:

def encode_basestring(s):
    """Return a JSON representation of a Python string

    """
    def replace(match):
        return ESCAPE_DCT[match.group(0)]
    return '"' + ESCAPE.sub(replace, s) + '"'

Here ESCAPE is a regular expression, and ESCAPE.sub(replace, s) finds all matches of ESCAPE in s and replaces each one with replace(match).


In fact, any API, like re.sub, that accepts a function as a parameter can lead to situations where nested functions are convenient. For example, in turtle.py there's some silly demo code that does this:

    def baba(xdummy, ydummy):
        clearscreen()
        bye()

    ...
    tri.write("  Click me!", font = ("Courier", 12, "bold") )
    tri.onclick(baba, 1)

onclick expects you to pass an event-handler function, so we define one and pass it in.

2 of 8
9

Decorators are a very popular use for nested functions. Here's an example of a decorator that prints a statement before and after any call to the decorated function.

def entry_exit(f):
    def new_f(*args, **kwargs):
        print "Entering", f.__name__
        f(*args, **kwargs)
        print "Exited", f.__name__
    return new_f

@entry_exit
def func1():
    print "inside func1()"

@entry_exit
def func2():
    print "inside func2()"

func1()
func2()
print func1.__name__
🌐
Colinsblog
colinsblog.net › 2023-08-05-nesting-functions
Better Code Organization by Nesting Functions - Colin's Notes
August 5, 2023 - The other day I found myself writing a really long Python script full of small groups of “helper” functions. Each group only “helped” a single caller. Something felt off. What a mess. Hidden under all the clutter, the script had a fairly simple structure. There’s only one path through the code. Breaking it into separate files would only obscure the logic. So how could I make that more clear? Then I remembered Python allows nested (inner) function definitions – they have access to their enclosing scope too.
🌐
PYnative
pynative.com › home › python › inner functions in python: a comprehensive guide
Inner Functions in Python: A Comprehensive Guide – PYnative
January 26, 2025 - def outer_function(): count = 0 def inner_function(): nonlocal count count += 1 return count return inner_function counter = outer_function() print(counter()) # Output: 1 print(counter()) # Output: 2 Code language: Python (python) Run · Performance: Be cautious when overusing inner functions, as excessive nesting can make the code harder to read and debug.