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?
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 else: return False if check(x): print('Yay!') return else: for i in range(x): if check(i): print('Yay!') return print('Nay!') f(43) # 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:
f.check(1) # 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
Here’s an example fix:
def outer(): pass outer.inner = lambda x: 2*x print(outer.inner(21)) # 42
🌍 Recommended Tutorial: Introduction to Python Classes
While working as a researcher in distributed systems, Dr. Christian Mayer found his love for teaching computer science students.
To help students reach higher levels of Python success, he founded the programming education website Finxter.com that has taught exponential skills to millions of coders worldwide. He’s the author of the best-selling programming books Python One-Liners (NoStarch 2020), The Art of Clean Code (NoStarch 2022), and The Book of Dash (NoStarch 2022). Chris also coauthored the Coffee Break Python series of self-published books. He’s a computer science enthusiast, freelancer, and owner of one of the top 10 largest Python blogs worldwide.
His passions are writing, reading, and coding. But his greatest passion is to serve aspiring coders through Finxter and help them to boost their skills. You can join his free email academy here.