Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Learn Closures | Variable Scope, Nested Functions, and Closures
Functional Programming Concepts in Python

bookClosures

Swipe to show menu

Closures vs. Nested Functions

A nested function is any function that you define inside another function. Nested functions are useful for organizing code and limiting the scope of helper functions. However, not all nested functions are closures.

A closure is a special type of nested function. Closures are nested functions that "remember" and can access variables from their enclosing function's scope, even after the outer function has finished running. This means closures can maintain state across multiple calls.

Key points:

  • All closures are nested functions;
  • Not all nested functions are closures;
  • A nested function becomes a closure only if it uses variables from the outer function's scope and those variables are still accessible after the outer function has returned.

This distinction is important for understanding how Python manages variable scope and how you can use closures to encapsulate state and behavior together.

12345678910
def make_greeter(name): def greet(): return f"Hello, {name}!" return greet greeter = make_greeter("Alice") print(greeter()) another_greeter = make_greeter("Bob") print(another_greeter())
copy

When you call make_greeter("Alice"), Python creates a new greet function that remembers the value of name as "Alice". Even though make_greeter finishes running, the returned greet function still has access to the name variable from its original scope. This is why calling greeter() prints Hello, Alice!, and calling another_greeter() prints Hello, Bob!. Each closure keeps its own copy of the variables it needs.

question mark

What makes a function a closure?

Select the correct answer

Everything was clear?

How can we improve it?

Thanks for your feedback!

Section 3. Chapter 8

Ask AI

expand

Ask AI

ChatGPT

Ask anything or try one of the suggested questions to begin our chat

Section 3. Chapter 8
some-alt