This is an archived version of the course. Please find the latest version of the course on the main webpage.

Chapter 1: Introduction

Inner/nested functions

face Josiah Wang

Before we talk about decorators, let us first talk about functions.

Here is the first point you need to know about functions. In Python, you can define another function inside a function. These are called inner or nested functions.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
def outer(text):
    print("Inside outer")

    def inner():
        print("Inside inner")
        print(text)
        print("Exiting inner")

    print("Calling inner")
    inner()
    print("Exiting outer")

outer("Hello!")

If you run the code, you should get the following output.

Inside outer
Calling inner
Inside inner
Hello!
Exiting inner
Exiting outer

Notice that the variable text is accessible from Line 6 inside the inner function.

You would usually not have any need to use nested/inner functions, so please avoid doing this unless you have a good reason to do so!

One possible reason is encapsulation, that is to hide the inner function so that you cannot call the inner function from outside the function definition of outer (that was a confusing sentence!)

Try calling inner() after outer("Hello!") in Line 14 in the code above. It should not work!

Traceback (most recent call last):
  File "inner2.py", line 14, in <module>
    inner()
NameError: name 'inner' is not defined