An inner function is defined inside an enclosing function. It exists only within that enclosing function’s scope, so calling it from the main program causes an error. The inner function runs when the enclosing function calls it. section 22.3
A function inside another function
def sing(): def stop(line): print("STOP", line) stop("it's hammer time") stop("in the name of love") sing() When sing() runs, stop() is defined and called twice. A stop() call outside sing() is not available because stop belongs to sing’s scope. section 22.3
Inner functions can use names from their enclosing functions. They can also be returned as function objects, allowing one function call to produce another specialized function. Follow chained calls from left to right, replacing each call with what it returns. section 22.5
Returning an inner function
def grumpy(): def no_n_times(n): def no_m_more_times(m): for i in range(n + m): print("no") return no_m_more_times return no_n_times grumpy()(4)(2) The outer call returns no_n_times; the next call returns no_m_more_times. The innermost function still knows n from its enclosing function. section 22.5
Use inner functions when a helper belongs only to one specific task.
- Keep task-specific helper functions inside the function that uses them. section 23.6
- Test each function soon after writing it, then test how several functions work together. section 23.6




