Vol. 7 — № 20
The Python Loop · KiosqueNewsstand
Blog  
Un atelier Python · Édition d'ApprentissageA Python Workshop · Learning Edition

EAFP contre LBYL : l'exception comme flux EAFP versus LBYL: the exception as control flow

Vérifier qu'une clé existe avant de la lire semble plus prudent que d'essayer et de rattraper l'échec. Mais entre la vérification et la lecture s'ouvre un intervalle — le temps qu'un autre thread, un autre processus, ou simplement le disque, change l'état vérifié. Python préfère EAFP : tenter l'opération directement, attraper l'exception si elle survient — sans jamais laisser cet intervalle s'ouvrir. Checking that a key exists before reading it looks more careful than trying and catching the failure. But between the check and the read opens a gap — time enough for another thread, another process, or simply the disk, to change the state just checked. Python prefers EAFP: attempting the operation directly, catching the exception if it happens — never leaving that gap open.

AudienceAudience
Dev qui a écrit if cle in dictionnaire: avant de lire dictionnaire[cle], et se demande pourquoi Python trouve ça suspect Dev who's written if key in dictionary: before reading dictionary[key], and wonders why Python finds that suspicious
Format
Self-paced
ChapitresChapters
5
Date
Juil 2026 Jul 2026
≈ 18 min ●●●○ ExceptionsEAFPtry/except

Chapitre 1 en accès libre — la suite (ch. 2 à 5) est réservée. Chapter 1 free to read — the rest (ch. 2–5) is members-only.

01CadrageFraming3 min

Vérifier avant d'agir semble plus prudent. Ça ouvre pourtant un intervalle que Python préfère ne jamais laisser exister.Checking before acting looks more careful. Yet it opens a gap Python prefers to never let exist.

Le numéro précédent a traité l'exception comme un accident à contenir — with garantissait le nettoyage après coup. Ce numéro retourne la question : Python encourage-t-il à prévenir l'erreur, ou à la laisser survenir puis à la rattraper ? Deux styles s'opposent. LBYL — Look Before You Leap — vérifie une condition avant d'agir : tester qu'une clé existe avant de la lire, qu'un fichier existe avant de l'ouvrir. EAFP — Easier to Ask Forgiveness than Permission — tente l'opération directement, et attrape l'exception si elle échoue. Le second style est idiomatique en Python ; le premier, hérité d'habitudes plus défensives, cache un défaut structurel que ce numéro va exposer.The previous issue treated the exception as an accident to contain — with guaranteed cleanup after the fact. This issue flips the question: does Python encourage preventing the error, or letting it happen and then catching it? Two styles compete. LBYL — Look Before You Leap — checks a condition before acting: testing that a key exists before reading it, that a file exists before opening it. EAFP — Easier to Ask Forgiveness than Permission — attempts the operation directly, and catches the exception if it fails. The latter style is idiomatic in Python; the former, inherited from more defensive habits, hides a structural flaw this issue is about to expose.

LBYL : deux lectures, un intervalle entre les deuxLBYL: two reads, a gap between them
# LBYL -- "Look Before You Leap" : vérifier, PUIS agir
if "utilisateur" in cache:
    valeur = cache["utilisateur"]
else:
    valeur = charger_depuis_la_base()

# deux lectures de "cache" : une pour vérifier, une pour lire
# -- rien ne garantit que l'état est LE MÊME entre les deux
EAFP : une seule lecture, aucun intervalleEAFP: one read, no gap
# EAFP -- "Easier to Ask Forgiveness than Permission" : agir, PUIS gérer l'échec
try:
    valeur = cache["utilisateur"]
except KeyError:
    valeur = charger_depuis_la_base()

# une seule lecture de "cache" -- pas d'intervalle entre vérifier et lire
Le sous-réflexe du numéroThis issue's sub-reflex

Face à un if condition: agir(), demande : entre la vérification et l'action, l'état pourrait-il changer — par un autre thread, un autre processus, ou simplement le temps qui passe ? Si oui, LBYL ouvre une fenêtre que EAFP referme.Facing an if condition: act(), ask: between the check and the action, could the state change — via another thread, another process, or simply the passage of time? If so, LBYL opens a window that EAFP closes.

🔒

La suite est réservée The rest is members-only

Le premier numéro est libre. Débloque tout The Python Loop — tous les volumes, à vie — pour 5 €, paiement unique. The first issue is free. Unlock all of The Python Loop — every volume, forever — for €5, one-time.

Retour au kiosqueBack to newsstand