Here’s another article in the Functions in Python series. Today we’ll be talking about nested functions. If you haven’t read the previous parts yet, feel free to do so. Here they are:
6) Mutable Optional Parameters
8) Arbitrary Number of Positional Parameters
9) Arbitrary Number of Keyword Parameters
10) Arbitrary Number of Both Positional and Keyword Parameters
Functions may be nested. We can have one function inside another. In such a case the nested function will be only available inside the function in which it is nested. Let’s have a look at this:
def sift_letters(frequency = 2):
print("My sieve is ready.")
print()
def prepare_word(word):
return word.upper()
formatted_word = prepare_word("unbelievable")
print(formatted_word[::frequency])
sift_letters()
Here the enclosing function is sift_letters and the nested function is prepare_word. Below the definition of sift_letters we’re trying to call the enclosing function. Here’s the output:
My sieve is ready.
UBLEAL
It works. Now let’s try to call the nested function outside the enclosing function like so:
def sift_letters(frequency = 2):
print("My sieve is ready.")
print()
def prepare_word(word):
return word.upper()
formatted_word = prepare_word("unbelievable")
print(formatted_word[::frequency])
sift_letters()
new_word = prepare_word("interesting")
print(new_word)
Let’s run it. Here’s what we get:
NameError: name 'prepare_word' is not defined
The error message tells us that the function prepare_word is not defined. This is because it’s only defined inside another function and it’s available only in that function. So, we can call prepare_word inside sift_letters, which we are actually doing, but only there. That’s how nested functions work.