Question presented to candidate:
"When Python meets a name like total inside a function, how does it decide which variable you mean? Walk me through the LEGB rule and the cases where it surprises people."
What a strong answer should cover:
- The search order Local, Enclosing function, Global (module), Built-in; the first match wins and a miss raises
NameError. - Scope is decided at compile time: an assignment anywhere in a function makes the name local for the whole body, which is why reading it first raises
UnboundLocalError. - Only modules, functions, lambdas, comprehensions and class bodies create scopes;
if,for,withandtryblocks do not. - Class bodies are skipped: a method cannot see class attributes as bare names, it must use
self.xorClassName.x. - Reading follows LEGB, but rebinding an outer name needs
globalornonlocal; shadowing a built-in such aslistorlenhides it. - A CPython detail: the compiler emits
LOAD_FAST,LOAD_DEREForLOAD_GLOBAL, andLOAD_GLOBALchecks the module dict first and the builtins second.
Code / implementation expected: Optional β predict the output of a nested-function snippet, or explain the UnboundLocalError case.