Advanced Python Programming — Closure

Observe → Implement → Design from usage → Apply with OOP

Survey Nested Functions

Read 3 examples and trace scope/captured values.

1 · Formatter
def report(title, values):
    def normalize(v):
        def label(x):
            return f"{title}: {x}"
        return label(round(v, 2))
    return [normalize(v) for v in values]
2 · Validation
def checkout(limit):
    def validate(amount):
        def remaining():
            return limit - amount
        return amount <= limit, remaining()
    return validate
3 · Nested state
def session(user):
    attempts = 0
    def login(password):
        def audit(ok):
            return user, attempts, ok
        return audit(password == "demo")
    return login

Learning Survey

Implement Closure

A · Greeter

make_greeter(prefix) returns inner greet(name).

Hello, KASA!
B · Multiplier

Capture factor in make_multiplier().

triple(7) → 21
C · Counter

Retain state with nonlocal.

start 10 → 11 → 12

Python Workspace

PYTHON CONSOLE Ready.

Using Closure — Caller First

The caller is fixed. Design a closure that supports it.

member_price = make_price_rule(0.10)
print(member_price(1000))
print(member_price(2500))
print(member_price(500))
Expectation
900.0
2250.0
450.0

Capture discount; the returned function receives amount.

Your Closure

PYTHON CONSOLE Ready.

Apply Closure with OOP

TicketService Validator Factory

The object owns service identity. A method creates a closure configured with a minimum amount. The closure remembers accepted-count state.

  1. Implement constructor.
  2. Implement make_validator(minimum).
  3. Create accepted = 0 in enclosing scope.
  4. Return validate(amount).
  5. Use nonlocal accepted.
KASA: REJECT amount=50
KASA: ACCEPT #1 amount=120
KASA: ACCEPT #2 amount=300

Build It

PYTHON CONSOLE Ready.