A function defined inside another function is called a nested function. Nested functions can access variables of the enclosing scope. In Python, these non-local variables are read-only by default and we must declare them explicitly as non-local (using nonlocal keyword) in order to modify them.
You use inner functions to protect them from everything happening outside of the function, meaning that they are hidden from the global scope.
Here’s a simple example that highlights that concept:
def outer(num1):
def inner_increment(num1): # Hidden from outer code
return num1 + 1
num2 = inner_increment(num1)
print(num1, num2)
inner_increment(10)
# outer(10)
Try calling inner_increment():
Traceback (most recent call last):
File "inner.py", line 7, in <module>
inner_increment()
NameError: name 'inner_increment' is not defined
Now comment out the inner_increment() call and uncomment the outer function call, outer(10), passing in 10 as the argument:
10 11
Note: Keep in mind that this is just an example. Although this code does achieve the desired result, it’s probably better to make inner_increment() a top-level “private” function using a leading underscore: _inner_increment().
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…