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

Closures

Svep för att visa menyn

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())

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?

Vänligen välj det korrekta svaret

Var allt tydligt?

Hur kan vi förbättra det?

Tack för dina kommentarer!

Avsnitt 3. Kapitel 8

Fråga AI

expand

Fråga AI

ChatGPT

Fråga vad du vill eller prova någon av de föreslagna frågorna för att starta vårt samtal

Avsnitt 3. Kapitel 8
some-alt