Evaluation Order and Function Arguments
Evaluation order matters when a function argument performs work, shares state, or may raise an exception before the call.
- Source
- Anbloq
- Language
- English
- Created
- Updated
- Chapters
- 4
- Reading time
- 2 min
In this article4 chapters
Separate grouping from execution
Operator precedence determines which expressions belong together. Evaluation order determines when those expressions run. Python evaluates the relevant argument expressions before entering an ordinary call. For two positional arguments written as combine(read_left(), read_right()), the left call is evaluated first. A failure there prevents the later expression and the enclosing call from running.
Two reads from one source
Suppose read() removes and returns the first item from a queue containing A followed by B. The call pair(read(), read()) receives A first and B second. The queue is already empty when pair begins. To make both side effects evident, bind the values in two statements before calling pair. If reading the second entry can fail, decide what happens to the first consumed item.[1][2]
Predict operations that change state
Suppose take() removes the next item from a shared queue. The expression compare(take(), take()) has a result depending on which items are removed in which order. For a queue containing first, second, and third, an ordinary Python positional call evaluates the first take() to first and the next to second before compare begins. Only third remains when the comparison body starts. The comparator's parameter names are irrelevant to which removal happened first.
The queue helps illustrate another detail. If only first was available and the second removal raises an exception, the comparison never starts. The first removal already changed the queue. A caller whose operation requires consuming both items together needs a different partial-failure contract. It can, for example, use an operation providing a complete pair as one documented action.
Move observable steps into names when useful
Writing one statement for each take makes the order visible and gives you both values for inspection before the call. A trace can put queue contents and retained names in different columns. When comparing two interpretations, choose distinct elements and an input where the first acquisition succeeds but the second fails. Inputs with duplicate labels would obscure which value reached which argument.
A comparison operator has grouping and evaluation rules too. A short-circuit test can skip a later operand entirely. If one subexpression must happen for every accepted run, put that action at a deliberate point instead of relying on its appearance in the text. Test both a complete call and one where an earlier operation prevents later work.