Quarry School

Trace a local name — quick review

In plain words

A workshop lends each visitor a tray of tools at the door.

Rule

A parameter, and any name assigned anywhere in a function's body, is local to one call of that function. A name that is neither a parameter nor assigned in the body is looked up among the global names, and after those among Python's built-in names. An assignment in the body makes or changes a local name and leaves a global name of the same spelling as it was. Outside the function the local names do not exist.

Step

  1. Draw two columns for names: one for the file's global names and one for the call's local names.

  2. At a call, start a fresh local column and write each parameter in it with the argument it received.

  3. When the body uses a parameter or a name that it assigns, read it from the local column. If that local name has no value yet on that line, the program stops with an UnboundLocalError. For any other name, read the global column, and after that Python's built-in names such as print.

  4. At an assignment inside the body, first work out the right side, reading each name as the step before says. Then write or change the name on the left in the local column. Leave the global column alone.

  5. At a return line, work out the value to give back while the local column is still there.

  6. When the call ends, cross out the whole local column. If the rest of the program needs the returned value, give it a name at the call.

Trap

The common surprise is expecting an assignment inside a function to change a global name. In the counter program the global count still holds 5 after reset() has run. To change a value for the rest of the program, have the function return the new value and assign it at the call. With a reset whose body ends in return 0, the line count = reset() gives the global count the value 0.

A sharper form of the same slip is a line such as count = count + 1 inside a function, with count assigned only at the margin. The assignment makes count local, so the right side asks for a local name that has no value yet, and the program stops with an UnboundLocalError, which is a kind of NameError. Pass the value in as an argument and return the result.