Closures and Decorators Flashcards
7 cards from real PCAP practice questions. Tap to flip, then mark Knew It or Still Learning — missed cards come back until you master them.
Read the first 7 Closures and Decorators flashcards as text
What is a closure in Python?
Answer: An inner function that captures and remembers variables from the enclosing scope even after the outer function has returned
A closure is a nested function that retains access to variables from its enclosing scope, allowing those variables to persist beyond the outer function's lifetime.
What will the following code print? def outer(x): def inner(y): return x + y return inner add5 = outer(5) print(add5(3))
Answer: 8
`outer(5)` returns `inner` with `x` closed over as 5, so calling `add5(3)` computes 5 + 3 = 8.
What is the `nonlocal` keyword used for inside a nested function?
Answer: To modify a variable defined in the nearest enclosing non-global scope
`nonlocal` tells Python that an assignment in the nested function targets the variable in the enclosing scope rather than creating a new local variable.
Which attribute of a function object holds the variables captured by its closure?
Answer: __closure__
`func.__closure__` is a tuple of cell objects, each holding the value of one variable captured from the enclosing scope.
What will this code output? def make_counter(): count = 0 def counter(): nonlocal count count += 1 return count return counter c = make_counter() print(c(), c(), c())
Answer: 1 2 3
Each call to `c()` increments the shared `count` variable via `nonlocal`, producing 1, 2, then 3.
What will the following code print? def outer(): x = 10 def inner(): print(x) x = 20 return inner f = outer() f()
Answer: 20
Closures capture the variable binding (a reference to the cell), not a snapshot of the value at definition time, so `x` is 20 when `inner` runs.
Which of the following is the most common practical use case for closures in Python?
Answer: Factory functions that return specialized functions with pre-configured parameters
Closures are frequently used as factory functions (e.g., `make_adder(n)` returns a function that adds `n`) to produce families of related functions that carry private state.
How this page was made: written with AI tools and published by Nathan Beja, founder of Practice Test Geeks, who is responsible for its content. Exam facts are checked against the official sources listed below. Not reviewed by a subject-matter expert. Editorial policy
Sources & references
Exam facts on this page (fees, format, dates, passing scores) are checked against these official sources; the date is our last check. Editorial policy
- pythoninstitute.org — Eligibility, fees, retake fee, retake policy, score release, time limit, score validity · verified Nov 2026
- home.pearsonvue.com — Test delivery · verified Nov 2026