Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Expressions and evaluation

Arguments and ordinary binary operands evaluate once, from left to right. and and or short-circuit; conditions and Boolean operators require bool rather than truthiness. Conditional expressions evaluate only the selected branch. Assignment evaluates its value before destination indices.

Operator precedence, from highest to lowest:

GroupOperators or forms
PostfixCalls, member access, indexing, slicing, error propagation ?
Unary+, -, bitwise not ~, dereference *, borrowing & and &mut
Multiplication*, /, //, %
Addition+, -
Shift<<, >>
Bitwise and&
Bitwise exclusive or^
Bitwise or|
Comparison and membership==, !=, <, >, <=, >=, in, not in
Boolean negationnot
Boolean conjunctionand
Boolean disjunctionor
Conditionalvalue_if_true if condition else value_if_false

Arithmetic operators associate left to right. Parentheses override precedence. Chained comparisons are rejected. There is no exponentiation operator: two adjacent stars, as in a ** b, are rejected with a diagnostic that names base.pow(exponent), whatever the operand types. Multiplying by a dereference needs a space: a * *b. Numeric rules specify type matching, casts, overflow, and float behavior. Membership follows the container’s facilities contract.

Ordering operators accept matching integers, floats, strings, and orderable tuples. Tuple operators use the same lexicographic total order as sort(), including its signed-zero and NaN rules; scalar float comparisons retain IEEE behavior.

Format strings build text from fields with static specs. Suites and conditionals have value and exit rules. Enums support exhaustive matching; loops provide repeated execution. Postfix ? follows error propagation, and resource scopes follow cleanup.

Nesting

Blocks and expressions nest to at most 64 levels in total. A function body is level 1. A suite is one level below the statement that owns it, and so are that statement’s expressions. An operand, argument, index, or element is one level below the expression that holds it, and parentheses add a level around what they enclose.

Operators group to the left, so a + b + c is (a + b) + c: every binary operator, call, member access, index, or ? in a chain puts everything before it one level deeper. A statement in a function body can chain 62 of them. Each manager of a with statement is one level around the managers after it and the body, and each for or if clause of a comprehension is one level around the clauses after it and the element. The elif arms of an if are not nested.

Deeper source is rejected at the token that reaches level 65, with block and expression nesting exceeds the implementation limit of 64. Bind an intermediate value to a name, group a long chain with parentheses, or move inner blocks into a function. Types and patterns have their own limits of 64.