global names1count = 102def add(n):3 total = count + n4 return total5answer = add(5)6print(answer)7print(total)add() local namescount? not hereNameError10def add510151515
Code card: scope.py; the highlighted line is the one runningBack tray: the global names of the fileFront tray: the local names of one call of add()Terminal: where print() writesPython keeps names in namespaces: a global one for the whole file (the back tray) and a fresh local one for each call of a function (the front tray). Each step lights the parts it is about. A token hops along the step's arrow: from a line into a box when = stores a name, from the global count to line 3 when the function reads it, from total to answer when add() returns. The local tray fills when add(5) is called and empties when it returns, so print(total) at the top level finds nothing and stops with a NameError.

Global names

  1. A scope is the part of a program where a name can be used. Python keeps names in namespaces: one global namespace for the whole file, plus a fresh local namespace each time a function is called.

Inside a call

After the call

Try it yourself

;; step 1/10
# global: made at the top level of the file
count = 10

def add(n):
    # local: made inside the function
    total = count + n
    return total

Python looks a name up in up to four scopes, innermost first: the local one, the enclosing functions (when a def sits inside another def), the global one (the module) and the built-in names such as print and len. People remember the order as LEGB. The Python tutorial says the local namespace is created when the function is called and deleted (better: forgotten) when it returns or raises an exception it does not handle. Each call gets its own fresh one.