Create Configured Functions with Factories
Core idea
A function factory is a function that creates and returns another function. A closure can retain configuration provided to the factory, so callers do not need to pass that configuration again. Each factory call creates its own local bindings.
def multiplier(factor): def multiply(value): return value * factor return multiplytriple = multiplier(3)print(triple(5))The factory captures factor; the returned function accepts only value.
Use independent configurations
def offset(amount): def adjust(value): return value + amount return adjustadd_two = offset(2)add_five = offset(5)print(add_two(10), add_five(10))The two closures retain separate amount bindings.
Keep state per factory call
def counter(): count = 0 def advance(): nonlocal count count += 1 return count return advancea = counter()b = counter()print(a(), a(), b())Each counter owns an independent enclosing count. nonlocal lets advance update its own count.
Common mistake
If you store configuration in a single global variable instead, independent returned functions may unexpectedly use the latest configuration. Avoid sharing state unless that is intentional.
Practice
Build a factory that returns a function for adding a fixed fee. Create two different fees and apply both to the same price. Then try the coding challenge.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Configure independent callables
Check your understanding of function factories.
What is printed?
def factory(n): def apply(v): return n * v return applyf = factory(2)print(f(7))What is printed?
def factory(n): def apply(v): return n + v return applya = factory(2)b = factory(5)print(a(3), b(3))What is printed?
def make(): n = 0 def step(): nonlocal n n += 2 return n return stepa = make()b = make()print(a(), a(), b())Why use separate enclosing bindings for configurations?