Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Full lesson preview

Build Nested Function Factories with Shared State

Create a factory that produces configurable inner functions which share and can update a common enclosed state.

Python practice25 minClosures & Function FactoriesAdvancedLast updated April 13, 2026

Problem statement

You will build a nested function factory that demonstrates closures and shared mutable state in Python. Implement a function make_factory(initial_base) that returns an object with three callable attributes: - create(increment): returns a function adder(x) which computes x + increment + current_base. - get_base(): returns the current base value. - set_base(new_base): updates the shared base value for the factory. Important behavior: adder functions should refer to the shared base dynamically. If set_base changes the base after an adder has been created but before it is called, the adder should use the updated base when called. Do not use global variables. Use closures/nonlocal to keep the shared state enclosed in the factory.

Task

Implement make_factory(initial_base) that returns an object with create, get_base, and set_base. Inner functions produced by create should use the shared base dynamically.

Examples

Basic usage

Input

f = make_factory(5); adder = f.create(3); adder(10)

Output

18

adder(10) computes 10 + 3 + base(5) = 18.

Input format

A single expression evaluated against the provided make_factory implementation (e.g., make_factory(5).create(3)(10)).

Output format

Return values of expressions (numbers or other values). Results are compared by their string representation.

Constraints

Do not use global state. The factory must enclose the shared base and allow it to be changed via set_base. adder functions must reflect base changes that occur after creation but before calling.

Samples

Sample 1

Input

make_factory(0).create(2)(4)

Output

6

4 + 2 + base(0) = 6