liveBook · Manning

Inner function

As explained in Python Workout, Second Edition

An inner function is a function defined within the scope of another function or enclosing code block.

An inner function is defined inside an outer function and can be returned as a callable object. It retains access to variables from the enclosing invocation. section 7.11

Use inner functions when each outer invocation should create a specialized callable:

  • Pass configuration to the outer function, such as an allowed-character string. section 7.10
  • Define the inner function during the outer function’s execution. section 7.11
  • Return the inner function and call it later with its own argument. section 7.10

Password generators

Calling create_password_generator with different character strings produces independent functions, such as alphabetic and symbol generators, each accepting a requested length. section 7.10 section 7.11

alpha_password = create_password_generator('abcdef')
symbol_password = create_password_generator('!@#$%')

print(alpha_password(5))    # efeaa
print(alpha_password(10))   # cacdacbada

print(symbol_password(5))   # %#@%@
print(symbol_password(10))  # @!%%$%$%%#

Inspect executable calls that create separate alphabetic and symbol password functions and invoke them at different lengths. section 7.10

How Python Workout, Second Edition covers it

How deep it goes
Explains definition timing, returned functions, enclosing-scope access, and LEGB lookup, but stops short of broader closure mechanics.
Examples
Demonstrates password generators for alphabetic and symbol character sets, with lengths five and ten.
What it assumes
Assumes basic function calls and arguments, while teaching nested definition, function returns, and enclosing-scope access.
What you can do after
Build it from scratch: define, return, and invoke specialized password generators that retain an outer character set.
How it connects
Connects inner functions with closures, variable scoping, functions, and LEGB variable lookup.

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 Python Workout, Second Edition. The section links point to the parts of the book it draws on.