liveBook · Manning

Inner function

As explained in Get Programming: Learn to code with Python

A function defined within the scope of an enclosing function.

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 grum​py()(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

How Get Programming: Learn to code with Python covers it

How deep it goes
Defines nesting, scope, returned function objects, and chained execution through small examples and trace exercises.
Examples
Uses singing stops, chained message functions, area helpers, student vacation details, and file-data analysis helpers.
What it assumes
Assumes basic function definitions and calls while reinforcing parameters, return values, scopes, and function objects.
What you can do after
Build it from scratch by defining task-specific inner functions, calling them within scope, and returning function objects when useful.
How it connects
Connects inner functions to function scope, function objects, parameters, and return values.

Also explained in

Compare how 5 books explain inner function →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Get Programming: Learn to code with Python. The section links point to the parts of the book it draws on.