I assume do_this and do_that are actually dependent on some argument of foo, since otherwise you could just move them out of foo and call them directly.

I suggest reworking the whole thing as a class. Something like this:

class Foo(object):
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def do_this(self):
        pass

    def do_that(self):
        pass

    def __call__(self):
        self.do_this()
        self.do_that()

foo = Foo(x, y)
foo()
foo.do_this()
Answer from Lauritz V. Thaulow on Stack Overflow
Top answer
1 of 7
33

I assume do_this and do_that are actually dependent on some argument of foo, since otherwise you could just move them out of foo and call them directly.

I suggest reworking the whole thing as a class. Something like this:

class Foo(object):
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def do_this(self):
        pass

    def do_that(self):
        pass

    def __call__(self):
        self.do_this()
        self.do_that()

foo = Foo(x, y)
foo()
foo.do_this()
2 of 7
20

These previous answers, telling you that you can not do this, are of course wrong. This is python, you can do almost anything you want using some magic code magic.

We can take the first constant out of foo's function code, this will be the do_this function. We can then use this code to create a new function with it.

see https://docs.python.org/2/library/new.html for more info on new and https://docs.python.org/2/library/inspect.html for more info on how to get to internal code.

Warning: it's not because you CAN do this that you SHOULD do this, rethinking the way you have your functions structured is the way to go, but if you want a quick and dirty hack that will probably break in the future, here you go:

import new
myfoo = new.function(foo.func_code.co_consts[1],{}) 
myfoo(x,y) # hooray we have a new function that does what I want

UPDATE: in python3 you can use the types module with foo.__code__:

import types
myfoo = types.FunctionType(foo.__code__.co_consts[1], {})
myfoo()  # behaves like it is do_this()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: do_this() missing 2 required positional arguments: 'x' and 'y'
🌐
Real Python
realpython.com › inner-functions-what-are-they-good-for
Python Inner Functions: What Are They Good For? – Real Python
2 weeks ago - Python inner functions are those you define inside other functions to access nonlocal names and bundle logic with its surrounding state. In this tutorial, you’ll learn how to create inner helper functions, build closures that retain state across calls, and implement decorators that modify the behavior or existing callables without changing the original implementation.
Discussions

python - calling a function inside another function(nested) - Stack Overflow
I'm quite new to the inspect library and with closure if this qualifies as closure. ... You call it the same way you call any other function... inner_funtion(). More on stackoverflow.com
🌐 stackoverflow.com
Python Run Inner Function Within Module - Stack Overflow
Bring the best of human thought and AI automation together at your work. Explore Stack Internal ... Save this question. Show activity on this post. How can I call an inner function within a Python module? More on stackoverflow.com
🌐 stackoverflow.com
Accessing inner functions in a class
Hi there! I am a beginner in python so I like to experiment. I was trying object oriented programming when I got stuck on this problem. Here is my code. The problem is in the last line of code. How can I access a nested inner function using object of a class? More on forum.freecodecamp.org
🌐 forum.freecodecamp.org
2
0
February 4, 2022
How to call a function within a function from another function in Python? - Stack Overflow
I have defined a function within another function in python and now I would like to call the inner function. Is this possible, in python? How do I call func2 from func3? def func1(): def func2... More on stackoverflow.com
🌐 stackoverflow.com
🌐
Reddit
reddit.com › r/learnprogramming › [python] | how to call nested functions
r/learnprogramming on Reddit: [Python] | How to call nested functions
October 17, 2021 -

This is the code I am trying to run:

x = 1
def f1():
    x = 2

    def f2():
        global x
        x = 3

print(x)
f1()
print(x)
f2()
print(x)

Output:

1
1
Traceback (most recent call last):
    f2()
NameError: name 'f2' is not defined

What I meant to do was call the f2() function but then it showed an error.

My question is how do I call the f2() function outside the nested block?

🌐
freeCodeCamp
freecodecamp.org › news › nested-functions-in-python
Nested Functions in Python
January 6, 2020 - For example: def outer(): print("I'm the outer function.") def inner(): print("And I'm the inner function.") inner() inner() ... Traceback (most recent call last): File "main.py", line 16, in <module> inner() NameError: name 'inner' is not defined
🌐
CodeSpeedy
codespeedy.com › home › how to call a nested function: python nested function call!
Nested Function Call : How to call a Nested Function in Python
October 16, 2020 - You can pass functions as an argument, return them or you can save them in data structures also. You can do it using Python Closures i.e. a function instance enclosed within an enclosing scope. There is one thing you should take care of, you must have to call the outer function to call the inner function because it’s scope is inside that function.
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-inner-functions
Python Inner Functions - GeeksforGeeks
May 22, 2026 - In Python, an inner function (also called a nested function) is a function defined inside another function. They are mainly used for: Encapsulation: Hiding helper logic from external access. Code Organization: Grouping related functionality for cleaner code. Access to Outer Variables: Inner functions can use variables of the enclosing (outer) function.
🌐
DEV Community
dev.to › divshekhar › python-inner-function-nested-functions-1dbn
Python Nested Function - DEV Community
May 23, 2023 - Let’s Learn about Python Inner Function / Nested Function. def outerFunction(a, b): def innerFunction(c, d): return c*d return innerFunction(a, b) ... In the above code, the outer function is called with two integer arguments and the outer ...
Find elsewhere
🌐
Python Examples
pythonexamples.org › python-inner-functions
Python Inner Functions
Now, let us understand the execution of a function with inner functions. We will take the above program for example. We know that the program execution happens sequentially. Following is the step by step execution of the above program. Define function(). Call function(). Execute print('Inside ...
🌐
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
🌐
Python Morsels
pythonmorsels.com › nested-functions
Nested functions in Python - Python Morsels
June 10, 2026 - To use this function, we can call it by putting parentheses after a reference to it: ... This works because functions are just objects in Python and like every object we can point variables to them and pass them around.
🌐
Stack Overflow
stackoverflow.com › questions › 49738600 › calling-a-function-inside-another-functionnested
python - calling a function inside another function(nested) - Stack Overflow
You can use inner_function() anywhere in the scope where inner_function() is defined, that is anywhere in outer_function() after you defined inner_function(). ... I find myself using this technique quite a bit.
🌐
freeCodeCamp
forum.freecodecamp.org › curriculum help
Accessing inner functions in a class - Curriculum Help - The freeCodeCamp Forum
February 4, 2022 - Hi there! I am a beginner in python so I like to experiment. I was trying object oriented programming when I got stuck on this problem. Here is my code. The problem is in the last line of code. How can I access a nested inner function using object of a class?
🌐
TutorialsPoint
tutorialspoint.com › How-do-nested-functions-work-in-Python
How do nested functions work in Python?
September 28, 2023 - When run, the above code will return no results because the outer function is never called. The scope of a variable is the location where we can find a variable and access it if necessary. It is well-understood how to access a global variable within a function, but what about accessing the variable of an outside function? The following program demonstrates the scope of the nested functions − · # creating an outer function def outerFunc(): sample_str = 'Hello tutorialspoint python' # creating an inner function def innerFunc(): print(sample_str) # calling an inner function inside the outer function innerFunc() # calling outer function outerFunc()
🌐
Analytics Vidhya
analyticsvidhya.com › home › how nested functions are used in python?
How nested functions are used in Python? - Analytics Vidhya
March 4, 2025 - Nested functions have many uses, primarily for creating closures and decorators. ... Hello, World! In this code, we define internally to display a string . To do this, we call on the last line .
🌐
Upgrad
upgrad.com › home › tutorials › software & tech › how to call a function in python?
How to Call a Function in Python?
July 28, 2026 - Nested Functions: Functions can be defined within other functions, creating nested functions. This allows you to encapsulate logic and maintain encapsulation. def function in Python code def outer_function(x): def inner_function(y): return x * y return inner_function
🌐
Stack Abuse
stackabuse.com › python-nested-functions
Python Nested Functions
December 21, 2018 - It is important to mention that the outer function has to be called in order for the inner function to execute. If the outer function is not called, the inner function will never execute.
Top answer
1 of 2
16

You can't, at least not directly.

I'm not sure why you would want to do that. If you want to be able to call func2() from outside func1(), simply define func2() at an appropriate outer scope.

One way that you could do it is to pass a parameter to func1() indicating that it should invoke func2():

def func1(call_func2=False):
    def func2():
        print("Hello!")
    if call_func2:
        return func2()

def func3():
    func1(True)

but since that requires modification to the existing code, you might as well move func2() to the same scope as func1().


I don't recommend that you do this, however, with some indirection you can reach into the func1() function object and access it's code object. Then using that code object access the code object for the inner function func2(). Finally call it with exec():

>>> exec(func1.__code__.co_consts[1])
Hello!

To generalise, if you had multiple nested functions in an arbitrary order and you wanted to call a specific one by name:

from types import CodeType
for obj in func1.__code__.co_consts:
    if isinstance(obj, CodeType) and obj.co_name == 'func2':
        exec(obj)
2 of 2
3

Let's go into little deep and explore it :

You can do this via three methods :

First method:

Just return the nested function from main function so return will become the caller of nested function:

def func1():
    def func2():
        print("Hello!")
    return func2()


def func3():
    return func1()

func3()

output:

Hello!

Second method : Even you can pass argument directly to nested function:

Using Closure concept :
def func1():
    def func2(x):
        print("Hello {}".format(x))
    return func2

closure=func1()
def func3():
    return closure('bob')

func3()

Look above example , Main function is not accepting any parameter but nested function have one parameter so here i directly pass the argument to nested function.

Third method :

You can try this little hacky thing :

def func1():
    def func2():
        print("Hello")
    return func2


def func3():
    return func1()()

func3()
🌐
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()
🌐
PYnative
pynative.com › home › python › inner functions in python: a comprehensive guide
Inner Functions in Python: A Comprehensive Guide – PYnative
January 26, 2025 - def calculate_area(shape, dimension): def circle_area(radius): return 3.14 * radius * radius def square_area(side): return side * side if shape == "circle": return circle_area(dimension) elif shape == "square": return square_area(dimension) else: return "Unknown shape" print(calculate_area("circle", 5)) # Output: 78.5 print(calculate_area("square", 4)) # Output: 16Code language: Python (python) Run · In this example, circle_area and square_area are defined as inner functions because they are exclusively used within calculate_area. This ensures: Scope Control: These helper functions are not exposed outside calculate_area, preventing their accidental use elsewhere in the program. Readability: Grouping the logic for calculating areas makes calculate_area more cohesive and easier to understand.