Question presented to candidate:
"Inside a function, how do you change a variable that was defined outside it? Explain what global and nonlocal do and when you would β or would not β use them."
What a strong answer should cover:
- Assignment inside a function binds a local name by default;
global xmakes assignments rebind the module-levelx, andnonlocal xrebindsxin the nearest enclosing function. - The difference between rebinding a name (needs a keyword) and mutating the object it points to (
items.append(1)needs none);x += 1is a rebinding. nonlocalrequires an existing binding in an enclosing function (never the module) and is checked at compile time;globalcan even create a new module name.- They are declarations for the whole function body: using the name before the declaration is a
SyntaxError, and a parameter cannot also be declared global or nonlocal. - Design trade-offs:
globalhides shared state and is not thread safe on its own; prefer parameters and return values, a class, or a closure withnonlocalfor private state.
Code / implementation expected: Optional β a counter with nonlocal, or spotting the UnboundLocalError in a function that does total += n.