Python Return From Nested Function

4/5 - (1 vote)

This quick tutorial will show you how to return a value from a nested function. I assume you have your reasons for doing so. However, a word of warning:

⚑ Attention: The main reason you want to create “nested functions”, i.e., inner and outer functions in Python, is to use them for closures and decorators.

This tutorial, however, is not on closures or decorators. If you want to learn more about them, feel free to check out the following tutorial:

🌍 Recommended Tutorial: Python Decorators Made Simple

With that out of the way, let’s get started! πŸ‘‡

πŸ’¬ Question: How to Return a Value From a Nested Function, i.e., how to use and call them in practice?

Quick Answer

If you call an inner function from inside the outer function, you can return a value from the inner function using the return value expression. You can call the inner function just like you would call any outer function.

Here’s an example where you return a Boolean value from an inner function check(x) that is then used in the outer function f(x) to do some dummy computations:

def f(x):

    def check(x):
        if x == 42:
            return True
            return False

    if check(x):
        for i in range(x):
            if check(i):

# Yay!

AttributeError: ‘function’ object has no attribute ‘…’

However, if you try to call the inner function from the outside (e.g., like so outer.inner()), you get an AttributeError: 'function' object has no attribute 'inner'.

Here’s an example using the definitions from the previous code snippet:

# AttributeError: 'function' object has no attribute 'check'

To fix this error, the best thing would be to fix it on a conceptual basis: use a class with methods that you can call from the outside. If you cannot do this for some reason, you can assign a lambda function such as outer.inner = lambda x: 2*x.

Now, you can call the inner function using outer.inner().

Here’s an example fix:

def outer():

outer.inner = lambda x: 2*x

# 42

🌍 Recommended Tutorial: Introduction to Python Classes