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




