liveBook · Manning

Inner function

As explained in Python Workout: 50 ten-minute exercises

An inner function is a function defined within the body of another function.

When several programs need passwords with different allowed characters, an inner function can preserve each character set while exposing a simple length-based interface. The outer function creates and returns the inner function, which retains access to the outer variable. section 6.11 section 6.12

Password-generator factory

import random def create_password_generator(characters): def create_password(length): return ''.join(random.choice(characters) for _ in range(length)) return create_password alpha_password = create_password_generator('abcdef') symbol_password = create_password_generator('!@#$%') print(alpha_password(5)) print(symbol_password(5)) Each call to create_password_generator creates a separate inner function. The inner function looks up characters in the enclosing scope through Python's LEGB rule. section 6.11 section 6.12

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))  # @!%%$%$%%#

Compare two returned functions and observe how each retains a different character set while accepting the same length argument. section 6.11

How Python Workout: 50 ten-minute exercises covers it

How deep it goes
Explains definition, creation timing, returned functions, closures, and LEGB lookup, stopping short of broader closure mechanics.
Examples
Demonstrates password generators for alphabetic and symbolic character sets, including multiple returned functions and generated outputs.
What it assumes
Assumes familiarity with Python functions and introduces inner-function definition, return, and enclosing-scope access through an exercise.
What you can do after
Build reusable function factories that retain configuration from an outer call.
How it connects
Connects inner functions with closures, lexical scoping, LEGB lookup, higher-order functions, and random.choice.

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: 50 ten-minute exercises. The section links point to the parts of the book it draws on.