Hackforge Academy

Category: python

What Is a Closure?

Published on 27 Oct 2026

Explanation

A closure is an inner function that retains access to variables from its enclosing scope after the outer function returns.

Code:

def outer():
    message = 'Hello from outer'
    def inner(): print(message)
    return inner
fn = outer()
fn()

Explanation

An outer function can accept configuration and return a function that uses it.

Code:

def make_multiplier(factor):
    def multiply(number): return number * factor
    return multiply
double = make_multiplier(2)
print(double(10))

Explanation

Use nonlocal to reassign a variable from an enclosing function.

Code:

def counter_factory():
    count = 0
    def increment():
        nonlocal count
        count += 1
        return count
    return increment
c = counter_factory()
print(c(), c())

Explanation

Closures look up captured variables when called. Lambdas created in a loop can all observe the final loop value.

Code:

functions = []
for n in range(3): functions.append(lambda: n)
print([f() for f in functions])

Explanation

Capture the current loop value in a default argument to give each lambda its own value.

Code:

functions = []
for n in range(3): functions.append(lambda n=n: n)
print([f() for f in functions])

πŸš€ Learn Spring Boot with real-world projects

πŸ’‘ Build REST APIs step by step

🧠 Improve backend development skills

🎯 Get career-ready practical training

Join Our Free WhatsApp Community

Direct access to niche-specific mentors and peers on WhatsApp.

🐍

Python Community

Discuss Django, FastAPI, AI integration, and automation scripts with 15k+ developers.

Join Python Community
βš›οΈ

React Community

Master Next.js, Framer Motion, and State Management. Share your latest UI components.

Join React Community
β˜•

Java Community

Deep dives into Spring Boot, Microservices architecture, and high-performance backend ops.

Join Java Community