Menu Close


Python: namespaces

Define namespace

One of most fundamental concept a Python developer must understand 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 accessible.


Output of the program:

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 accessible.


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 necessary for every single nested function that uses other variables than the local variables.


Read next:  Function Attributes