global & nonlocal : l'explicite contre l'implicite global & nonlocal: the explicit against the implicit

Lire un nom englobant ne demande aucune déclaration — LEGB s'en charge (numéro 13). Le réassigner en demande une : sans mot-clé, Python déclare un nom local tout neuf, et l'original englobant reste intouché. global et nonlocal lèvent cette ambiguïté, chacun pointant vers un scope différent — mais l'un crée silencieusement, l'autre exige que la case existe déjà. Reading an enclosing name needs no declaration — LEGB handles it (issue 13). Reassigning it needs one: without a keyword, Python declares a brand-new local name, and the original enclosing one stays untouched. global and nonlocal lift that ambiguity, each pointing to a different scope — but one creates silently, the other demands the slot already exists.

Audience
Dev dont le compteur enfermé dans une closure refuse obstinément de s'incrémenter Dev whose counter locked inside a closure stubbornly refuses to increment
ChapitresChapters
5
LectureReading
≈ 18 min
NiveauLevel
●●●○
Date
Juil 2026 Jul 2026

PortéeClosuresglobalnonlocal

SommaireContents ·
№ 01CadrageFraming3 min

Le compteur qui refuse de compter : réassigner un nom englobant ne va pas de soi.The counter that refuses to count: reassigning an enclosing name isn't automatic.

Le numéro précédent s'est arrêté sur une lecture : une closure qui consulte une variable englobante n'a besoin d'aucune déclaration — LEGB s'en charge silencieusement. Mais vouloir réassigner cette même variable depuis l'intérieur change tout. incrementer() veut seulement ajouter 1 à compte — et pourtant Python refuse dès le premier appel, sur la lecture que contient compte += 1. La raison tient en une règle déjà posée au numéro 13 : une assignation, où qu'elle soit dans le corps d'une fonction, classe le nom comme local pour toute la fonction. compte += 1 est une assignation. Elle rend compte local à incrementer() — un nom local qu'on lit avant de l'avoir jamais assigné.The previous issue stopped at a read: a closure consulting an enclosing variable needs no declaration — LEGB handles it silently. But wanting to reassign that same variable from the inside changes everything. incrementer() only wants to add 1 to compte — and yet Python refuses on the very first call, on the read hidden inside compte += 1. The reason is a rule already laid down in issue 13: an assignment, wherever it sits in a function's body, classifies the name as local for the whole function. compte += 1 is an assignment. It makes compte local to incrementer() — a local name read before it was ever assigned.

Une lecture qui semblait anodine, une UnboundLocalErrorA read that looked harmless, an UnboundLocalError
def fabrique_compteur():
    compte = 0
    def incrementer():
        compte += 1     # compte += 1  ==  compte = compte + 1  -> une ASSIGNATION
        return compte
    return incrementer

c = fabrique_compteur()
c()
# UnboundLocalError: cannot access local variable 'compte'
# where it is not associated with a value

# "compte" est pourtant juste au-dessus, dans fabrique_compteur() !
Le sous-réflexe du numéroThis issue's sub-reflex

Face à une fonction imbriquée qui doit modifier — pas seulement lire — un nom vivant dans une portée englobante, demande : ce nom vit-il dans le module (Global), ou dans la fonction qui contient celle-ci (Enclosing) ? La réponse fixe le mot-clé à utiliser.Facing a nested function that must modify — not just read — a name living in an enclosing scope, ask: does this name live in the module (Global), or in the function that contains this one (Enclosing)? The answer fixes which keyword to use.

Ce n'est pas une nouvelle UnboundLocalErrorThis isn't a new UnboundLocalError

C'est exactement le même mécanisme que le numéro 13 — une variable classée locale par une assignation, lue avant sa première affectation. Seule différence : la variable qu'on croyait pouvoir réassigner sans effort n'était pas globale, mais une portée plus loin, dans une closure.It's exactly the same mechanism as issue 13 — a variable classified local by an assignment, read before its first binding. The only difference: the variable you thought you could reassign freely wasn't global, but one scope further out, inside a closure.

№ 02La surpriseThe surprise4 min

Deux façons de réparer le compteur : déclarer l'intention, ou ne jamais réassigner le nom.Two ways to fix the counter: declare the intent, or never reassign the name.

La surprise n'est pas que Python refuse la réassignation implicite — c'est qu'il existe deux réponses également valides, et qu'elles ne coûtent pas la même chose. La première déclare explicitement l'intention avec nonlocal, et laisse compte += 1 réassigner la case englobante. La seconde évite le problème à la racine : elle ne réassigne jamais compte, elle mute un objet que compte référence — une liste à une case. Aucune déclaration n'est alors nécessaire, parce que muter n'est jamais une assignation de nom.The surprise isn't that Python refuses the implicit reassignment — it's that two equally valid answers exist, and they don't cost the same. The first explicitly declares intent with nonlocal, letting compte += 1 reassign the enclosing slot. The second avoids the problem at the root: it never reassigns compte, it mutates an object that compte references — a one-slot list. No declaration is needed then, because mutating is never a name assignment.

nonlocal déclare l'intention avant la réassignationnonlocal declares the intent before the reassignment
def fabrique_compteur():
    compte = 0
    def incrementer():
        nonlocal compte      # déclare : "compte" ici DÉSIGNE celui d'au-dessus
        compte += 1          # réassignation -> plus de UnboundLocalError
        return compte
    return incrementer

c = fabrique_compteur()
print(c(), c(), c())   # 1 2 3 — la même case, incrémentée à chaque appel

Les deux fonctionnent. Le numéro 04 (aliasing) avait déjà posé la distinction entre muter en place et réassigner le nom local — c'est exactement cette distinction qui décide si un mot-clé est nécessaire ici.Both work. Issue 04 (aliasing) already drew the line between mutating in place and reassigning the local name — that's exactly the distinction that decides whether a keyword is needed here.

№ 03La mécaniqueThe mechanics5 min

global saute directement au module. nonlocal remonte les portées Enclosing, une par une — jamais jusqu'au module.global jumps straight to the module. nonlocal climbs the Enclosing scopes, one by one — never as far as the module.

Les deux mots-clés répondent à la même question — quel nom réassigner — mais visent des étages différents de LEGB. global ignore Local et Enclosing : il pointe directement sur le nom tel qu'il vit dans le module qui contient la fonction, sans jamais traverser les fonctions intermédiaires. nonlocal fait l'inverse : il ignore Global et cherche uniquement parmi les portées Enclosing, celles des fonctions qui englobent directement ou indirectement celle où le mot-clé apparaît — en remontant jusqu'à la trouver, mais sans jamais atteindre le module.Both keywords answer the same question — which name to reassign — but target different LEGB tiers. global ignores Local and Enclosing: it points straight at the name as it lives in the module containing the function, never crossing through intermediate functions. nonlocal does the opposite: it ignores Global and searches only among the Enclosing scopes, those of the functions directly or indirectly containing the one where the keyword appears — climbing up until it finds it, but never reaching the module.

global : accès direct au module, quelle que soit la profondeur d'imbricationglobal: direct access to the module, regardless of nesting depth
compteur_appels = 0     # vit dans le module -- portée Global

def suivre_appel():
    global compteur_appels   # pointe DIRECTEMENT sur le Global, saute l'Enclosing
    compteur_appels += 1

suivre_appel()
suivre_appel()
print(compteur_appels)   # 2 -- le nom du module a bien été réassigné
nonlocal : remonte les Enclosing, s'arrête avant le modulenonlocal: climbs the Enclosing scopes, stops before the module
def externe():
    x = 0
    def milieu():
        def interne():
            nonlocal x        # cherche en Enclosing -- ignore Global -- trouve x dans externe()
            x += 1
        interne()
        return x
    return milieu()

print(externe())   # 1 -- nonlocal a traversé "milieu" pour atteindre "externe"
# nonlocal NE cherche JAMAIS dans Global -- seulement dans les Enclosing, un par un
Une asymétrie à retenirAn asymmetry worth remembering

Il n'existe pas de global qui viserait une portée Enclosing intermédiaire, ni de nonlocal qui atteindrait le module. Les deux mots-clés se partagent LEGB sans se chevaucher : Global pour l'un, Enclosing pour l'autre — jamais Local (déjà acquis par défaut) ni Built-in (qu'aucun mot-clé ne vise : un nom assigné au module le masque, sans le modifier).There's no global that targets an intermediate Enclosing scope, nor a nonlocal that reaches the module. The two keywords split LEGB without overlap: Global for one, Enclosing for the other — never Local (already the default) nor Built-in (which no keyword targets: a name assigned at module level shadows it, without changing it).

№ 04Le piègeThe trap4 min

global crée sans demander ; nonlocal exige que la case existe déjà. Et le vrai piège n'est ni l'un ni l'autre : c'est l'état global mutable.global creates without asking; nonlocal demands the slot already exists. And the real trap is neither one — it's mutable global state.

Les deux mots-clés ne sont pas symétriques face à l'absence : global tolère qu'un nom n'existe pas encore dans le module et le crée à la première assignation, sans lever la moindre erreur. nonlocal, lui, exige qu'une portée Enclosing possède déjà cette variable — sinon Python refuse le code avant même de l'exécuter, avec une SyntaxError repérée à la compilation. Mais le piège qui coûte vraiment cher n'est pas cette asymétrie syntaxique : c'est la tentation d'utiliser global pour partager un état mutable entre des dizaines de fonctions d'un même module, jusqu'à ce que plus personne ne sache qui l'a modifié en dernier.The two keywords aren't symmetric about absence: global tolerates a name that doesn't exist yet in the module and creates it on first assignment, raising no error at all. nonlocal, meanwhile, demands that some Enclosing scope already owns that variable — otherwise Python refuses the code before it even runs, with a SyntaxError caught at compile time. But the trap that actually costs is not this syntactic asymmetry — it's the temptation to use global to share mutable state across dozens of functions in the same module, until nobody can tell anymore who last changed it.

global n'exige pas que le nom existe déjàglobal doesn't require the name to already exist
def initialiser():
    global config          # "config" n'existe pourtant nulle part encore
    config = {"debug": True}

initialiser()
print(config)   # {'debug': True} -- AUCUNE erreur : global a CRÉÉ le nom dans le module

# global ne réclame pas que le nom existe déjà. Il déclare une intention
# de destination -- et Python crée la case au module si besoin.
Quand global reste légitimeWhen global stays legitimate

Un flag de configuration lu une fois au démarrage, jamais réassigné en cours de route, ne pose aucun problème avec global. Le risque grandit avec le nombre de fonctions qui réassignent la même variable au fil de l'exécution — c'est ce nombre-là, pas le mot-clé lui-même, qui rend l'état intraçable.A configuration flag read once at startup, never reassigned along the way, poses no problem with global. The risk grows with the number of functions that reassign the same variable over the course of execution — it's that count, not the keyword itself, that makes the state untraceable.

№ 05Bilan & éditoWrap-up & editorial2 min

Portée & closures, refermé : un nom n'est jamais résolu une fois pour toutes — il l'est à chaque lecture, à chaque écriture.Scope & closures, closed: a name is never resolved once and for all — it's resolved on every read, on every write.

Trois numéros pour une seule idée, vue sous trois angles temporels. Le №13 a posé LEGB et sa conséquence la plus contre-intuitive : une assignation, où qu'elle soit dans le corps, classe un nom local pour toute la fonction — avant la première ligne exécutée. Le №14 a montré qu'une closure ne fige rien à sa création : elle capture une variable, lue au moment de l'appel, jamais avant. Ce numéro a fermé la boucle en distinguant lire d'écrire : lire un nom englobant ne demande rien, mais le réassigner exige de déclarer global ou nonlocal — et ces deux mots-clés ne sont pas symétriques face à un nom absent.Three issues for one idea, seen from three temporal angles. №13 laid out LEGB and its most counter-intuitive consequence: an assignment, wherever it sits in the body, classifies a name as local for the whole function — before the first line runs. №14 showed that a closure freezes nothing at creation: it captures a variable, read at call time, never before. This issue closed the loop by splitting reading from writing: reading an enclosing name asks for nothing, but reassigning it demands declaring global or nonlocal — and the two keywords aren't symmetric in the face of an absent name.

NuméroIssueCe qu'il a poséWhat it established
№ 13LEGB (Local, Enclosing, Global, Built-in) ; une assignation classe un nom local pour toute la fonction, dès la compilation.LEGB (Local, Enclosing, Global, Built-in); an assignment classifies a name local for the whole function, at compile time.
№ 14Une closure capture la variable, pas sa valeur ; elle la lit au moment de l'appel — jamais à sa création.A closure captures the variable, not its value; it reads it at call time — never at creation.
№ 15global vise le module, nonlocal les Enclosing ; global crée le nom absent, nonlocal l'exige déjà présent.global targets the module, nonlocal the Enclosing scopes; global creates an absent name, nonlocal requires it already exist.
Un nom ne vit nulle part par défaut. Il vit là où la dernière assignation l'a rangé — et c'est à toi de le dire, quand ce n'est pas Local.A name doesn't live anywhere by default. It lives where the last assignment filed it — and it's on you to say so, when it isn't Local.
Mot de l'éditeurFrom the editor

Le Vol. V a résolu un nom libre dans le temps. Le suivant résout un attribut dans l'espace : instance, classe, ou ailleurs ?Vol. V resolved a free name in time. The next one resolves an attribute in space: instance, class, or elsewhere?

LEGB répond à une question : où Python cherche-t-il un nom qui n'appartient à aucun objet ? Mais obj.x pose une question voisine, jamais couverte jusqu'ici : où Python cherche-t-il un attribut qui appartient, lui, à un objet précis ? La réponse est une seconde recherche à étages — d'abord le __dict__ de l'instance, puis celui de la classe, en remontant sa chaîne d'héritage (le MRO) — et elle réserve la même surprise que LEGB : un attribut de classe mutable, partagé par toutes les instances qui ne l'ont pas encore réécrit dans leur propre __dict__.LEGB answers one question: where does Python look for a name that belongs to no object? But obj.x asks a neighboring question, never covered so far: where does Python look for an attribute that belongs to a specific object? The answer is a second tiered search — first the instance's __dict__, then the class's, climbing its inheritance chain (the MRO) — and it holds the same surprise as LEGB: a mutable class attribute, shared by every instance that hasn't yet overwritten it in its own __dict__.

Prochain numéro : la recherche d'attribut, instance contre classe contre MRO. __dict__ d'instance contre __dict__ de classe ; l'attribut de classe mutable partagé ; __getattr__ contre __getattribute__. Ouverture du Vol. VI, le modèle d'attributs.Next issue: attribute lookup, instance versus class versus MRO. Instance __dict__ versus class __dict__; the shared mutable class attribute; __getattr__ versus __getattribute__. Opening Vol. VI, the attribute model.