function defined inside another function
In computer programming, a nested function (or nested procedure or subroutine) is a named function that is defined within another (enclosing) block and is lexically scoped within the enclosing block โ€“ meaning โ€ฆ Wikipedia
๐ŸŒ
Wikipedia
en.wikipedia.org โ€บ wiki โ€บ Nested_function
Nested function - Wikipedia
August 26, 2026 - In computer programming, a nested function (or nested procedure or subroutine) is a named function that is defined within another (enclosing) block and is lexically scoped within the enclosing block โ€“ meaning it is only callable by name within the body of the enclosing block and can use ...
๐ŸŒ
Reddit
reddit.com โ€บ r/c_programming โ€บ what are some use cases of nested functions?
r/C_Programming on Reddit: What are some use cases of nested functions?
February 8, 2024 -

I know that they're a gcc extension and not standard, but I just wanted to know what makes them useful? Is there any task where using this extension makes things much easier than attempting to stick with the ISO standard?

Top answer
1 of 5
11
The nice thing is that a nested function can access your local variables. So, you can manipulate them without passing pointer arguments. For example, let's say you have a function that is parsing text from a stream, and has several variables to keep track of the input state. You can have a read_next_character() function to get the next character, and it can update all these local variables as appropriate. Without nested functions, you could do this by putting those variables into a struct and passing a pointer to a struct, but might be convenient to avoid that if you're calling your function in 200 different places. Another way to accomplish this is with a macro, but then macros have their own problems. Another situation I can think of where this might be convenient is when you have a function that will be recursive, but you have an initial setup and a bundle of data that gets passed along to every recursive invocation. For example, let's say you have a sort function, and you initially set up a buffer and some boundaries, then you call a recursive function to do the actual sorting; if you make the recursive part a nested function then it can access that state without needing to pass it along as arguments, or as a struct pointer. Again this is really convenience, it doesn't let you do anything you couldn't do otherwise. It's possible that in the past, using nested functions in this way could also get you better performance by avoiding argument passing, without the problems of using global variables. I doubt this is normally true today with the optimization we have, but I imagine it might've been part of the original justification for the feature.
2 of 5
2
there are a few uses but in general it lets you share your local state with the nested function. lets say you have a really complicated long function but you figure out there's some regularity that you can factor out into a function but when you're done this function needs a bunch of parameters and a few pointer out parameters because you need more than one return value because what the nested function does initself is still pretty intricate. the "greybeard" approach to cleaning this up is to make a context struct that contains all this information and you can just move that around and fill it as necessary. the "new c" approach would be to make that secondary function a nested function and let the nested function access any local that it needs from the parent function.
๐ŸŒ
Microsoft MakeCode
arcade.makecode.com โ€บ courses โ€บ csintro4 โ€บ appendix โ€บ nested-functions
Advanced Topics: Nested Functions
The creation of a nested function is fairly simple: just declare the function as it is normally done, only within the scope of another function.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ javascript โ€บ javascript-nested-functions
JavaScript Nested functions - GeeksforGeeks
Inside outer function, inner function is called, which multiplies 3 and 4, then adds x and y (which are 2 and 5). Nested functions can also be used for encapsulating logic and keeping variables private within the outer function's scope.
Published: July 12, 2025
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ why are nested functions used?
r/learnpython on Reddit: Why are nested functions used?
April 23, 2022 -

I was reading up on decorators and they started off giving examples of nested functions to illustrate how decorations work. I didnโ€™t really understand.

Take the following example code they give:

def split_string(function):
    def wrapper():
        func = function()
        splitted_string = func.split()
        return splitted_string

    return wrapper

def say_hi():
    return 'hello there

decorate = uppercase_decorator(say_hi)
decorate()

In the nested function def wrapper(), why does this need to be nested at all. You could easily write a to_uppercase function without nesting it so what are the advantages of this way?

Top answer
1 of 5
3
As a rule, almost all tutorials explaining what a decorator is use an example where you do not need a decorator. However, they get the gist right - decorators are a meta programming tool that you use when you want to make the same modification to a bunch of functions. As far an an example goes, I like the @memoize example; https://wiki.python.org/moin/PythonDecoratorLibrary#Memoize Itโ€™s actually complicated enough that you would want to use a decorator, and you smoothly couldnโ€™t handle the situation by passing the results of each individual function into a different function (each function should have its own cache, after all). Decorators are the cleanest solution here.
2 of 5
2
Consider sorting a list of objects on an attribute of choice, like a Person class that has first, last and age attributes. To provide a key to sort on you'd need to extract the attribute: def get_age(obj): return obj.age def get_first(obj): return obj.first ... persons.sort(key=get_age) But now you need a function for every attribute you want to sort on. So consider this: def get_attribute(name): def return_value(obj): return obj.__getattribute__(name) return return_value Now you can do this: first = get_attribute('first') persons.sort(key=first) But why stop there? You can even do persons.sort(key=get_attribute('first')) In fact, you'll find attrgetter in the operator library so you'll never have to implement it yourself, but it illustrates why you'd want to do something like this.
๐ŸŒ
GNU
gcc.gnu.org โ€บ onlinedocs โ€บ gcc โ€บ Nested-Functions.html
Nested Functions (Using the GNU Compiler Collection (GCC))
A nested function can jump to a label inherited from a containing function, provided the label is explicitly declared in the containing function (see Locally Declared Labels). Such a jump returns instantly to the containing function, exiting the nested function that did the goto and any intermediate functions as well.
Find elsewhere
๐ŸŒ
Colinsblog
colinsblog.net โ€บ 2023-08-05-nesting-functions
Better Code Organization by Nesting Functions
August 5, 2023 - The inner function has read-only access to its enclosing scope, but isnโ€™t automatically a closure. The inner function accesses the values of the parent scope variables at call time. Thereโ€™s more you can do with Python inner functions: How Nested Functions are Use in Pytho including making closures.
๐ŸŒ
Microsoft Support
support.microsoft.com โ€บ en-us โ€บ excel โ€บ use-nested-functions-in-an-excel-formula
Use nested functions in an Excel formula | Microsoft Support
Nest (include) other functions inside the IF function in a formula to mimic an If Then statement. You can nest up to 64 functions in another function.
๐ŸŒ
W3Schools
w3schools.com โ€บ r โ€บ r_functions_nested.asp
R Nested Functions
You cannot directly call the function because the Inner_func has been defined (nested) inside the Outer_func.
๐ŸŒ
IBM
ibm.com โ€บ docs โ€บ en โ€บ xl-c-and-cpp-aix โ€บ 13.1.0
Nested functions (IBM extension)
About cookies on this site Our websites require some cookies to function properly (required). In addition, other cookies may be used with your consent to analyze site usage, improve the user experience and for advertising. For more information, please review your cookie preferences options.
Top answer
1 of 1
5

R uses lexical scoping which means that if a function needs to reference an object not defined in that function it looks at the environment in which the function was defined, not the caller. In the question g is defined in the global environment so that is where g looks for c.

Also note that in R we would not call the functions in the question nested functions. Rather what is nested is the calls, not the functions. In (3) below we show nested functions.

1) We can reset a function's environment in which case it will think it was defined in that environment.

g <- function(a,b){       # help function
    a^2 + b^2 - c
}

f <- function(a,b,c,d){   # main function
    environment(g) <- environment()
    g(a,b)
}

f(1, 2, 3, 4)
## [1] 2

2) Another possibility is to explicitly tell it which environment to search using envir$c (where envir is the desired environment) or get("c", envir) or with(envir, c) . envir$c will look into envir. The other two will look there and if not found will look into ancestor environments. (Each environment has a parent or the emptyenv(). This is distinct from the call stack.)

g <- function(a, b, envir = parent.frame()){       # help function
    a^2 + b^2 - envir$c
}

f <- function(a,b,c,d){   # main function
    g(a,b)
}

f(1, 2, 3, 4)
## [1] 2

3) We can nest the functions so that g is defined in f.

f <- function(a,b,c,d){   # main function
    g <- function(a,b){       # help function
        a^2 + b^2 - c
    }
    g(a,b)
}

f(1, 2, 3, 4)
## [1] 2

4) Of course you could just pass c and avoid all these problems.

g <- function(a, b, c) { 
    a^2 + b^2 - c
}

f <- function(a, b, c, d) {   # main function
    g(a, b, c)
}

f(1, 2, 3, 4)
## [1] 2
Top answer
1 of 12
137
>>> def sum(x, y):
...     def do_it():
...             return x + y
...     return do_it
... 
>>> a = sum(1, 3)
>>> a
<function do_it at 0xb772b304>
>>> a()
4

Is this what you were looking for? It's called a closure.

2 of 12
57

You don't really gain much by doing this, in fact it slows method_a down because it'll define and recompile the other function every time it's called. Given that, it would probably be better to just prefix the function name with underscore to indicate it's a private method -- i.e. _method_b.

I suppose you might want to do this if the nested function's definition varied each time for some reason, but that may indicate a flaw in your design. That said, there is a valid reason to do this to allow the nested function to use arguments that were passed to the outer function but not explicitly passed on to them, which sometimes occurs when writing function decorators, for example. It's what is being shown in the accepted answer although a decorator is not being defined or used.

Update:

Here's proof that nesting them is slower (using Python 3.6.1), although admittedly not by much in this trivial case:

setup = """
class Test(object):
    def separate(self, arg):
        some_data = self._method_b(arg)

    def _method_b(self, arg):
        return arg+1

    def nested(self, arg):

        def method_b2(self, arg):
            return arg+1

        some_data = method_b2(self, arg)

obj = Test()
"""
from timeit import Timer
print(min(Timer(stmt='obj.separate(42)', setup=setup).repeat()))  # -> 0.24479823284461724
print(min(Timer(stmt='obj.nested(42)', setup=setup).repeat()))    # -> 0.26553459700452575

Note I added some self arguments to your sample functions to make them more like real methods (although method_b2 still isn't technically a method of the Test class). Also the nested function is actually called in that version, unlike yours.

๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ is it bad practice to have functions nested in your main function?
r/learnpython on Reddit: Is it bad practice to have functions nested in your main function?
June 11, 2023 -

So, I am writing a main function (so that I can say if name == "main" because that is good practice). And my main file accesses a lot of classes that are not inside of the main function. This is all fine, but then there is a function in a number of different classes that I want to call at once. Think of it like: reset_box(), reset_circle(), reset_triangle() or whatever.

Under certain conditions I want to just hit all these at once. So, it would be nice to have a function I can call that just does them all at once rather than writing them all out each time.

It would be easiest to do this in the main function, to just add in another function that resets everything. Or is this bad code? Should I take the function out of main and call it that way? The downside of this is that I have to pass it every object that I want to reset which will make it look a little ugly?

What are people's thoughts? Is it better to have a little function inside main that I can call to reset a bunch of objects. Or does it seem better to have the function out of main and just pass in every object that I need to?

Top answer
1 of 9
40
You can just make a function that calls all of them def all(): class.method_1() class_two.method_2() class.method_3() Then when you want to cal all three at once you you just call โ€œall()โ€ generally the rule of thumb is if you have to do something more then twice it should probably be itโ€™s own function. We cal this DRY Donโ€™t Repeat Yourself code as opposed to WET We Enjoy Typing code. We are going to need some code to really understand you problem. main() should be calling everything as usually itโ€™s the only thing that is actually running.
2 of 9
4
I'm not a Python programmer per se, I spend more time with C so I may be missing something, but I think that in languages that support it it is NOT a bad practice (at all) to define functions within the scope where they are used. It's a form of encapsulation, and it can serve as a way to keep your code organised and tidy. If your inner function is never called outside of the main function, it makes sense to define it within that main function - making it invisible to anything else. But if I were building something in Python I think I would go one step (OK, a few steps) further and implement the whole application in a class. Then I could just do something like this: if __name__ == "__main__": application = Application() application.run() Of course, any methods of the Application class could also have nested functions within them. You can take this as far as you like. In any case I don't think you really need a function called main(), that's just a leftover convention from C. In Python, anything after if __name__ == "__main__": could be considered the "main" part of your program.
๐ŸŒ
Baeldung
baeldung.com โ€บ home โ€บ scala core โ€บ nested functions in scala
Nested Functions in Scala | Baeldung on Scala
April 10, 2025 - Scala supports the usage of nested functions. Nested functions are those that are defined within another function.
Top answer
1 of 7
4

One popular use of nested functions is closures. In a lexically scoped language with first-class functions it's possible to use functions to store data. A simple example in Scheme is a counter:

(define (make-counter)
  (let ((count 0))                ; used to store the count
    (define (counter)             ; this is the counter we're creating
      (set! count (+ count 1))    ; increment the count
      count)                      ; return the new count
    counter))                     ; return the new counter function

(define mycounter (make-counter)) ; create a counter called mycounter

(mycounter)                       ; returns 1

(mycounter)                       ; returns 2

In this example, we nest the function counter inside the function make-counter, and by returning this internal function we are able to access the data available to counter when it was defined. This information is private to this instance of mycounter - if we were to create another counter, it would use a different spot to store the internal count. Continuing from the previous example:

(define mycounter2 (make-counter))

(mycounter2)                      ; returns 1

(mycounter)                       ; returns 3
2 of 7
3

It's useful for recursion when there is only 1 method that will ever call it

string[] GetFiles(string path)
{
  void NestedGetFiles(string path, List<string> result)
  {
    result.AddRange( files in the current path);
    foreach(string subPath in FoldersInTheCurrentPath)
      NestedGetFiles(subPath, result);
  }

   List<string> result = new List<string>();
   NestedGetFiles(path, result);
   return result.ToArray();
}

The above code is completely made up but is based on C# to give the idea of what I mean. The only method that can call NestedGetFiles is the GetFiles method.

๐ŸŒ
IBM
ibm.com โ€บ docs โ€บ en โ€บ xl-c-aix โ€บ 13.1.3
Nested functions (C only) (IBM extension)
About cookies on this site Our websites require some cookies to function properly (required). In addition, other cookies may be used with your consent to analyze site usage, improve the user experience and for advertising. For more information, please review your cookie preferences options.
๐ŸŒ
Pluralsight
pluralsight.com โ€บ blog โ€บ tech guides & tutorials
Creating Nested and Special-Purpose Functions in R | Pluralsight
The above plots show how we can use the ggplot(), geom_boxplot(), and ggtitle functions nested within the create_boxplot function to perform complex data science tasks in fewer lines of code.