Closures

Functions remembering their environment

Interview Relevant: Advanced concept

Closures

Functions that capture their enclosing scope.

Code Examples

Closures for state preservation.

python
1# Closure example
2def make_multiplier(n):
3    def multiplier(x):
4        return x * n  # n is captured
5    return multiplier
6
7double = make_multiplier(2)
8triple = make_multiplier(3)
9double(5)  # 10
10triple(5)  # 15
11
12# Counter with closure
13def make_counter():
14    count = 0
15    def counter():
16        nonlocal count
17        count += 1
18        return count
19    return counter
20
21c = make_counter()
22c()  # 1
23c()  # 2
24c()  # 3
25
26# Inspect closure
27double.__closure__[0].cell_contents  # 2

AI Tutor

Ask about the topic

Sign in Required

Please sign in to use the AI tutor

Sign In