Skip to the solution
MediumDSA9 min read

What do the global and nonlocal keywords do?

1.1k views

The problem

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 x makes assignments rebind the module-level x, and nonlocal x rebinds x in 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 += 1 is a rebinding.
  • nonlocal requires an existing binding in an enclosing function (never the module) and is checked at compile time; global can 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: global hides shared state and is not thread safe on its own; prefer parameters and return values, a class, or a closure with nonlocal for private state.

Code / implementation expected: Optional β€” a counter with nonlocal, or spotting the UnboundLocalError in a function that does total += n.

  • global
  • nonlocal

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

9 min read Β· 11 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

Pythonglobal vs nonlocal, and mutation vs rebinding
PythonThe compile-time rules, and the bytecode each keyword produces

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 41 of 139 in Python

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All Python questions
Up nextMedium

What is structural pattern matching (match/case)?

Continue