Language
Control flow
if / elif / else
negative zero positive
while
15
while … else
The else runs when the loop ends without break.
loop finished cleanly
for
for iterates any iterable. Lists, tuples, dicts, sets, ranges, strings and generators all work.
a b c
The loop variable takes the same targets as assignment, nested and starred ones included. Tuple unpacking lists them.
a 1 b 2 c 3
break and continue
break exits the loop. continue skips to the next item. Both work in for and while.
1 3
for … else
The else runs when the loop exhausts its iterator without break. It fits a search that reports a miss.
found at 1 not found
match / case
match tries each case in order and runs the first one whose pattern fits the subject.
| Pattern | Example | Matches |
|---|---|---|
| Literal | 0, -1.5, "a", b"x" | An equal value |
| Singleton | True, False, None | The same object. case True rejects 1 |
| Capture | x | Anything, bound to the name |
| Wildcard | _ | Anything, bound to nothing |
| OR | 1 | 2 | 3 | Any of the alternatives |
as capture | [x, y] as pair | The inner pattern, bound to the name |
| Sequence | [a, *rest], (a, b), a, b | A list or tuple of that shape |
| Mapping | {"k": p, **rest} | A dict holding those literal keys |
| Class | Point(x, y=0), int(n) | An instance whose attributes match |
| Dotted name | Color.RED | A value equal to that attribute |
A few rules shape how the patterns combine.
- A guard such as
case x if x < 0adds a condition after the pattern. - Adjacent string or bytes literals join into one literal.
- Parentheses without a comma only group.
(x)is the capturex. - Items of a sequence pattern can be any pattern, nested sequences, OR groups and
ascaptures included. - A sequence pattern matches only list and tuple subjects. A
str,bytesor any other value fails it and falls through to the next case. - A mapping pattern matches only dicts.
**restcollects the other keys. - A class pattern checks
isinstanceand reads positional items through__match_args__. On a builtin type such asint(n)the positional item is the subject itself.
Literals, OR patterns, guards and the wildcard.
zero small negative other
Sequence patterns.
empty single 5 pair-equal 1 then 3 more
Mapping patterns.
api:443 {'tls': True}
api:80
no hostClass patterns.
origin on the x axis at 3 at 1, 2 int 7
Dotted names compare by value.
red green other
try / except / else / finally
5.0 None
A try statement has up to four kinds of clauses.
- An
excepthandler names one exception, a tuple of exceptions, or nothing. - A bare
exceptcatches everything. elseruns when thetrybody raised nothing.finallyalways runs.
parsed 42 cleanup
caught
Handlers match subclasses. except Exception catches ValueError, RuntimeError, KeyError and the rest of the exception hierarchy.
subclass caught
raise
raise takes an exception class or an instance. Any other value, such as raise "boom", raises TypeError with the message “exceptions must derive from BaseException”.
rejected
A bare raise inside an except block re-raises the exception being handled.
logging outer bad
raise X from Y raises X with Y as its __cause__. An exception raised while another is handled keeps that one as its __context__, and from None hides it. An uncaught chain prints each exception in turn.
KeyError True
with
with runs the context manager protocol in three steps.
- Evaluate the expression.
- Call
__enter__and bind its result to theastarget. - On exit, call
__exit__(exc_type, exc_value, traceback).
The arguments of __exit__ are (None, None, None) on a clean exit. On an exception they are the exception type and value, and traceback is always None.
Several managers in one with nest. The last one enters last and exits first.
enter a enter b a b exit b None None None exit a None None None enter c exit c <class 'ValueError'> bad None propagated
What __exit__ returns or raises decides how the block ends.
- A truthy return suppresses the exception. A falsy one lets it propagate.
- Each manager has its own handler. When an inner one suppresses, the outer ones exit with
(None, None, None). - If
__exit__raises, the new exception replaces the original.
suppressed
Cleanup on early exit
finally and __exit__ run on every way out of a block. That includes normal completion, exceptions, return, break and continue. A return or break inside finally replaces the original exit.
released 10 released negative tick 0 tick 1
assert
0.25
A failed assertion raises AssertionError. The message after the comma evaluates only on failure. It becomes the exception argument in e.args.
math broke
del
del removes a binding. It works on plain names, attributes (del obj.attr), indexed positions (del seq[i]) and parenthesized groups (del (a, b)).
gone [1, 3]
pass
pass does nothing. Use it where the grammar requires a block.
done