Skip to content

ADR 0038: x is None is a tag test, and a guard clause narrows

Status: Final Type: Feature Created: 2026-08-03 Related-ADRs: 0029 (the tagged unions this extends), 0024 (the instance-in-a-box rung, formerly 0034), 0023 (its refusal of is between instances is untouched), 0033 (the fall-through question reused here), 0063 (== between instances). Provenance: arbitrations A115, A116, A144, A153, A163.

Context

item = ledger.find(name)
if item is None:
    return False
item.qty += qty

Before this ADR the compiler refused both: is was not lowered; the line after the test saw Item | None, which has no attributes. This is the shape find() exists for, unreachable since the day optionals became constructible.

Typed Python narrows in many more shapes than the guard clause. The census programs refreshed under A153 (a field set to None in __init__, annotated T | None, each use preceded by assert self.f is not None) use them. What the checkers accept, this compiler must accept too (A144), and where it cannot do so faithfully it refuses.

Decision

x is None is not the is that 0023 refuses

That refusal covers a is b between two instances, for a good reason. Identity asks whether two references denote one object, which makes non-deterministic collection observable. CPython's answer for cached ints and interned strs depends on caching this compiler does not have. Lowering identity for one type would give one operator two meanings, the argument of 0020 against **.

x is None asks none of that. In this compiler None is a case with no address, payload or reference count. The language guarantees exactly one of it: CPython specifies None as a singleton, which is why the Python style guide says to write is None and not == None. So "is this value in the None case?" is answered by reading the tag, the read a match case already does. The operator acquires no second meaning, because this was never the identity meaning. It is also the only practical spelling: a match over two cases is an unnatural way to write a guard clause, and refusing if x is None: would refuse the idiom the language documents for the type this compiler had just made constructible.

Lowering: a comparison of the union's tag with None's, with is not flipping it. This works for a scalar optional too: int | None has no pointer anywhere in it, which is the case an identity-comparison lowering would get silently wrong.

x == None and x != None lower as x is None and x is not None, in either operand order, for the test and the narrowing. No case of a union defines an __eq__ that equals None, so CPython falls back to identity. == and != between a C | None and a C, or two C | None, are that identity fallback too: None equals None and no instance, an instance equals only itself, and the payload is read only on the path where both are instances.

Narrowing records a fact about a name, never a rebind

The obvious implementation, rebinding item to the payload, does not work: a name has one slot and the slot's dtype is the union's. Assignment writes into the slot and cannot change the slot's type. A match case sidesteps this by binding a fresh name with a new slot, but a guard clause has no fresh name to bind.

So the narrowing is recorded as a fact (name → (box, case)). The payload is read on demand at each use: one load per use instead of one per narrowing, a single instruction either way. The trade pays because there is no binding to invalidate. A reassignment drops the narrowing at the single place a binding changes, so a future assignment path is covered without further work, since each rebound name already passes through it.

Where it holds: the condition is the whole correctness argument

narrows
if x is None: return / raise / any body that cannot fall through everything after the if
if x is None: ... else: <here> the else branch
if x is not None: <here> the body
if x is None: log(): body falls through no narrowing
assert x is not None everything after it
if x is not None and x.v > 0: the later operands, and the body
if x is None or x.v: the later operands, and the else
a if x is not None else b a where the test holds, b where it fails
x = <a C> into an x: C | None everything after, until x is bound again
both paths of an if, or of a try without finally, narrow x to one case everything after the statement
a loop whose body rebinds x no narrowing in the loop, the uses above the binding included
the end of the block that made the narrowing no narrowing after the block, except where a join keeps it

The rule: the code after an if sees the narrowed type only when the branch for the other case cannot reach it. "Can this fall through?" is the question 0033's definite-assignment pass already asks, answered here from the block terminator the lowering has just produced. A wrong answer would access the wrong member of a C union (a pointer as an integer or the reverse) on all three backends with no diagnostic, so the refusal side is tested harder than the acceptance side.

Conditions. An operand of and is resolved with the earlier operands' narrowings in force. An operand of or is resolved with the narrowings that hold where the earlier ones were false. The arms of a conditional expression narrow as an if's branches do, and no narrowing extends past the expression.

assert narrows what follows, as a guard clause whose other case raises. In release, where assertions are not evaluated (python -O's rule), an assertion that narrows a name is kept, because the payload of a narrowed name is loaded without a check: for a program whose assertion fails, that release build raises AssertionError where python -O would go on with None. An assertion that narrows a field is elided, since its reads are checked.

A loop that rebinds the name ends the narrowing for the whole loop. A loop body is lowered once and runs many times, so a use above a binding in the body runs again after it. Before a while or a for is lowered, each narrowed name the body rebinds stops being narrowed (notes/accept-then-wrong.md §57). For a while this is exact. For a for it is stricter than mypy in one shape: the iterable is evaluated once, before any pass, so mypy still narrows a name the iterable uses. This compiler does not when the body rebinds that name (for c in node.kids: node = c). That refusal is recorded distance. A comprehension's next pass ends a narrowing the same way.

A narrowing ends with the block that made it: after a body, only the narrowings that held before it and still hold are kept (notes/accept-then-wrong.md §58). Joins keep the rest where mypy keeps them. Where both paths of an if reach the code after it, a name narrowed to the same case at the end of each stays narrowed. A try without finally joins the same way over the body through its else and each handler that does not leave. A handler starts from what held before the body, less what the body ended, since the exception can come from any statement of the body. With a finally, the statement keeps only what held at its entry. Only names join; a field's narrowing is kept after a join only where it held before the statement.

Only a union of exactly two cases narrows. int | str | None would narrow to int | str, which is still a box needing a match, so there is no payload to rebind. That branch is unreachable, because a three-case union is refused one rung earlier (0029), and a test checks the unreachability in place of a comment claiming it.

Fields

A chain of fields ending in a T | None field narrows (self.root, n.left) by each form that narrows a name, keyed by the chain's text. A store narrows a field as an assignment narrows a name (A163). Where a field's narrowing ends is mypy's rule: an assignment to the chain or to any link of it, a binding of the root name, or a loop that does either.

A read through a narrowed field is checked. A call does not end the narrowing, which is where mypy is unsound: the call may rebind the field to None. So no box is held across the region; each read loads the field again and checks the tag, raising CPython's AttributeError: 'NoneType' object has no attribute 'v' at the read, where CPython raises it. That makes the narrowing an acceptance rule, never a trust: no read depends on it being true.

A narrowed field is a value only while no program code can have run since the narrowing. A value (r = r.right, visit(self.root)) has no CPython error to raise at the read, and where CPython would pass None along, this compiler cannot put None into a C slot. One predicate says whether evaluating a node may run program code. None runs in names, constants, field reads, displays, range, len, empty constructors, a class built with no __init__ in its chain, the loads, stores and walks of a builtin list or dict (when hashing their keys runs no program code, A168), operators over scalars and strs, and comprehensions of such parts. Anything else may, and marks the narrowing stale. The rule is stricter than mypy, which trusts the narrowing across all of them. The distance is a value use after such code; an assert right above the use closes it.

A field the checkers keep narrowed, assigned to a local declared its class, makes the local hold the optional (A163). The binding that declared the local is annotated C | None, the way A147 types an x = None. Each attribute read or store through the local tests for None and raises CPython's AttributeError there, with CPython's message for a store. Where the value would leave as a C (an argument to a C parameter, a return from -> C, a store into a C slot), it is refused with a message naming the field and the narrowing the checkers assumed, and giving x is not None as the test that admits it. A narrowing the checkers do not make stays refused, by A153. A local the program itself annotated C | None is not read this way: the checkers reject unguarded access to it, and so does this compiler.

The diagnostic

An un-narrowed x.field once reported that attribute expressions were not lowered, which was false and pointed at the wrong line. It now says the name may be None, quotes the union, and names the forms that narrow and the one that does not.

Consequences

  • The narrowed payload is borrowed from the box, for the same reason as in a match case: the test proves the box is in a live slot for the whole narrowed region, so the frame needs no reference. Reclamation is unchanged and tested.
  • A function with a narrowing assert, or a test that narrows a field, may raise, so the raisers analysis marks it and its callers look at the pending exception.
  • Two distances from mypy are recorded: a for whose body rebinds a name its iterable uses, and a narrowed field used as a value after program code may have run.
  • A dataclass case in == with a C | None stays refused (notes/accept-then-wrong.md §56).