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

Closures

Stryg for at vise menuen

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ælg det korrekte svar

Var alt klart?

Hvordan kan vi forbedre det?

Tak for dine kommentarer!

Sektion 3. Kapitel 8

Spørg AI

expand

Spørg AI

ChatGPT

Spørg om hvad som helst eller prøv et af de foreslåede spørgsmål for at starte vores chat

Sektion 3. Kapitel 8
some-alt