Question presented to candidate:
"What is the walrus operator, :=? Show me one place where it makes code genuinely better, and one place where you would not use it."
What a strong answer should cover:
:=is an assignment expression (PEP 572, Python 3.8): it binds a name and evaluates to the value, so it can sit insideif,while, comprehensions and calls, where a normal=statement cannot.- The good uses: a read loop
while (chunk := f.read(n)):, keeping a regex match you just tested, and computing a value once in a comprehension that both filters on it and keeps it. - Precedence: it binds more loosely than comparisons, so
if n := len(a) > 3stores a boolean; parenthesise(n := len(a)) > 3. - Scope: inside a comprehension the target binds in the enclosing function or module scope (the loop variable does not leak, the walrus target does).
- Restrictions: not a bare statement, only plain names as targets (no attributes or subscripts), cannot rebind a comprehension iteration variable, not inside a comprehension in a class body.
Code / implementation expected: Yes β a short before/after, for example a comprehension that calls an expensive function once instead of twice.