KennisbankExamencentrum
NL · NLNederlands (Nederland)
Taal kiezen13

CKTIS / Python

Sleutelwoord nonlocal

Verwijst naar de dichtstbijzijnde bestaande binding in een omvattende functie en staat hertoewijzing toe.

Versie: Python 3.14; repository image, production runtime not attested

Syntax

nonlocal total

Verwijst naar de dichtstbijzijnde bestaande binding in een omvattende functie en staat hertoewijzing toe.

Een teruggegeven sluiting bewaart de binding tussen aanroepen. Alleen een modulevariabele volstaat niet en zonder omvattende functiebinding ontstaat al bij compilatie een SyntaxError.

Elke aanroep van de buitenste functie maakt een afzonderlijke teller.

Voorbeelden

def counter(start):
    total = start
    def next_value():
        nonlocal total
        total += 1
        return total
    return next_value
a, b = counter(0), counter(7)
print(a(), a(), b())
try:
    compile("def bad():\n    nonlocal absent", "<example>", "exec")
except SyntaxError:
    print("missing binding")

Resultaat

1 2 8
missing binding

Elke aanroep van de buitenste functie maakt een afzonderlijke teller.

Bronnen