Python nested functions

Function inPythonCan be nested in other functions.

The function defined inside the function is only visible inside the function.

This is useful for creating utilities that are useful for a certain function but are not useful outside of it.

You may ask: Why should I "hide" this feature if it does not harm this feature?

First, because it's best to always hide the local functions of a function, and it's useless in other places.

In addition, because we can use closures (more on this later).

This is an example:

def talk(phrase):
    def say(word):
words <span style="color:#f92672">=</span> phrase<span style="color:#f92672">.</span>split(<span style="color:#e6db74">' '</span>)
<span style="color:#66d9ef">for</span> word <span style="color:#f92672">in</span> words:

talk(‘I am going to buy the milk’)

If you want to access the variables defined in the external function from the internal function, you first need to declare it asnonlocal:

def count():
    count = 0
<span style="color:#66d9ef">def</span> <span style="color:#a6e22e">increment</span>():
    nonlocal count
    count <span style="color:#f92672">=</span> count <span style="color:#f92672">+</span> <span style="color:#ae81ff">1</span>
    <span style="color:#66d9ef">print</span>(count)



This is especially useful when shutting down, as we will see later.

More python tutorials: