One of most fundamental concept a Python developer must understend is the namespace. A namespace is a composite word from “name” and “space”. It represents a memory structure that hold several names. A namespace is defined by a “scope”. A scope is a region of program that is used to define identifiers: variables or functions. In this region a namespace is accesible.
def scope_test(): def do_local(): spam = "local spam" def do_nonlocal(): nonlocal spam spam = "nonlocal spam" def do_global(): global spam spam = "global spam" spam = "test spam" do_local() print("After local assignment:", spam) do_nonlocal() print("After nonlocal assignment:", spam) do_global() print("After global assignment:", spam) scope_test() print("In global scope:", spam)
Output of the program:
After local assignment: test spam After nonlocal assignment: nonlocal spam After global assignment: nonlocal spam In global scope: global spam
Name Space Details
The namespaces are nested. The outermost scope is called “global” scope and it create a “global” namespace. Functions can be nested. Inside every function there is a local namespace. However the parent namespace is accesible.
Using “=” will create a new variable in the local scope. If a variable exists already defined in the global scope or in the parent scope it is shadowed. We create a new variable in the local scope that hide the outer scope variable.
To avoid shadowing we have to declare variables using “global” or “nonlocal” keywords. This is necesary for every single nested function that uses other variables than the local variables.
Read next: Function Attributes