Closures
Once you master closures, you unlock the ability to create custom function factories, stateful functions, decorators, event handlers, configuration-based logic, and real-world abstractions used in production systems.
Learn Python, JavaScript, Java and more with free interactive lessons, real projects and AI-powered help. Beginner-friendly.
Part of the free Python course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.
What You'll Learn in This Lesson
Once you master closures, you unlock the ability to create:
This lesson takes you from theory → real project engineering.
Think of lexical scope like a house with rooms. Each room (function) can see into the hallway (outer scope), but the hallway can't see into the rooms. Inner functions can "see" outer variables, but not vice versa.
A closure is like a backpack that a function carries. When you create an inner function, it "packs" any variables it needs from the outer function. Even after the outer function is done, the inner function still has its backpack with all those values!
When you want to modify (not just read) an outer variable, you MUST use nonlocal . Without it, Python thinks you're creating a NEW local variable!
💡 Why This Matters: Each counter has its own private count . This is used for tracking events, API call limits, unique ID generators, and session tracking.
This is exactly how Flask decorators, FastAPI dependencies, permission systems, and API gateways work behind the scenes.
Closures here enable ORM-like systems, flexible APIs, and dashboard filtering.
This powers data pipelines, ML preprocessing, and functional programming styles.
Both closures and classes can store state. But closures are lightweight (just a function), while classes are feature-rich (methods, inheritance, etc.). Choose based on complexity!
💡 Modern codebases often mix both. Use closures for quick utilities, classes for complex domains.
❌ Mistake #2: Loop variable capture (Tricky!)
You've mastered the basics. Now let's explore how senior engineers use closures in large-scale systems.
Most dependency injection systems in other languages require containers, service providers, and registries. Python can do it with one function.
Used in microservices, test environments, feature-flagged deployments, and plugin systems.
This is how FastAPI Dependency Injection, Flask Decorators, Django Middleware, and Starlette Routing all work internally.
Cloud-based systems (AWS, GCP, Stripe, PayPal, Twilio) ALL use retry + exponential backoff to prevent failures.
Used in ML inference servers, recommendation systems, data dashboards, and pricing engines.
This mirrors real A/B testing systems at Netflix, Facebook, and Shopify.
Used in Mixpanel, Firebase Analytics, and Amplitude.
Frameworks like Flask, FastAPI, Click, and Typer are closure-heavy.
Closures → registry → framework. You just built something similar to CLI libraries, routing systems, and plugin engines.
Used by Pandas, Spark, ML preprocessing, and data validation systems.
Used with database connections, file streams, and cache layers.
Closures store level states, UI states, and game event metadata.
Useful for debugging decorators, factories, async pipelines, and cached layers.
This is one of the most common closure bugs in the world.
You've expanded your closure knowledge. Now let's explore expert-level patterns used in AI pipelines, backends, and production systems.
Used in websocket reconnection, unstable network fetches, async microservice calls, and task orchestration tools.
This pattern runs boss AI in games, dialogue systems, backend workflow state, and user authentication flow.
This powers preprocessing, augmentation, feature engineering, and batch transforms.
This mimics syntax highlighters, linting engines, formatters, and interpreters.
This pattern appears in Flask, FastAPI, Node.js Express equivalents, and API gateways.
Used for price updates, leaderboard refresh, background jobs, and monitoring tasks.
This allows dynamic model creation, field injection, serialization/deserialization, and validation.
Used in game UIs, terminal apps, custom dashboards, and educational tools.
This powers admin dashboards, e-commerce backends, and authentication gateways.
Used for simulation, job queues, event systems, and async workers.
Used in physics simulation, rendering engines, machine learning, and game movement curves.
Alternate to functools.partial, giving Python the power of functional programming and cleaner callbacks.
Used in web servers, request filtering, AI agent chains, and on-device pipelines.
Used in UI systems, stock trackers, game events, and reactive dashboards.
Better than lru_cache when you need dynamic TTL, external invalidation, or distributed system caching.
You now understand the deepest real-world closure techniques, used in:
You've reached expert-level closure mastery used by senior Python engineers in production systems.
You now understand how closures capture state and how Python resolves variable scope — a key skill behind decorators, factories, and callback systems.
Up next: Context Managers — control resource lifecycle with the with statement.
Practice quiz
What is lexical scope?
- Variable visibility decided by where code RUNS
- A type of global variable
- Variable visibility decided by where code is WRITTEN
- A way to import modules
Answer: Variable visibility decided by where code is WRITTEN. Lexical scope means visibility is determined by where code is written, not where it runs.
What is a closure?
- An inner function that remembers variables from its enclosing scope
- A function that takes no arguments
- A way to close a file
- A built-in Python keyword
Answer: An inner function that remembers variables from its enclosing scope. A closure is an inner function that captures and remembers variables from its outer function.
Which keyword lets an inner function MODIFY a variable from the enclosing function?
- global
- static
- extern
- nonlocal
Answer: nonlocal. nonlocal tells Python to modify the outer (enclosing) variable instead of creating a new local one.
Given make_multiplier(factor) returning multiply(x)=x*factor, what does make_multiplier(10)(3) return?
- 13
- 30
- 10
- 3
Answer: 30. factor=10 is captured, so multiply(3) returns 3 * 10 = 30.
What happens if you do count += 1 inside an inner function WITHOUT declaring nonlocal count?
- It raises an UnboundLocalError
- It works fine
- It modifies a global
- It returns None
Answer: It raises an UnboundLocalError. Without nonlocal, Python treats count as a new local, so reading it before assignment raises UnboundLocalError.
Given compose(f, g) returning f(g(x)), with double(x)=x*2 and add_5(x)=x+5, what does compose(double, add_5)(10) print?
- 25
- 20
- 30
- 15
Answer: 30. g runs first: add_5(10)=15, then double(15)=30.
What does [lambda: i for i in range(3)] then [f() for f in funcs] print (the late-binding bug)?
All lambdas share the same i, which ends at 2 after the loop, so every call returns 2.
How do you fix the loop-variable capture bug?
- Use nonlocal
- Use global
- Use a tuple
- Use a default argument like lambda i=i: i
Answer: Use a default argument like lambda i=i: i. lambda i=i: i captures the current value of i as a default, giving each lambda its own copy.
Where does Python store a closure's captured variables?
- In __dict__
- In the function's __closure__ cell objects
- In a global registry
- In the stack
Answer: In the function's __closure__ cell objects. Captured variables live in cell objects accessible via the function's __closure__ attribute.
Given a polynomial factory f(x)=a*x*x+b*x+c made with polynomial(1, -3, 2), what does the function return for x=2?
- 2
- 4
- 0
- -3
Answer: 0. 1*4 + (-3)*2 + 2 = 4 - 6 + 2 = 0.