Understanding Python Namespaces and Scope: global and nonlocal Keywords Explained

Namespaces

A namespace is a mapping from names to objects. In Python, most namespaces are implemented as dictionaries.

Types of Namespaces

Built-in Namespaces

These are the names built into Python itself, including built-in functions like abs() and chr(), as well as exception classes like BaseException and Exception.

Global Namespaces

These contain names defined at the module level, including functions, classes, imported modules, and module-level variables and constants.

Local Namespaces

These exist within functions and contain the function's variables, including parameters and locally defined variables. (Names defined within classes also fall into this category.)

Namespace Lookup Order:

Local → Global → Built-in

Namespace Lifespan:

The lifespan of a namespace depends on the scope of the objects it contains. When execution of an object completes, its namespace ends. In simple terms, variables defined inside a function disappear when the function finishes executting. They are temporary and recreated on each function call.

Scope

A scope is a textual region of a Python program where a namespace is directly accessible. "Directly accessible" means that an unqualified reference to a name will attempt to find that name in the relevant namespace.

Four Types of Scopes

L (Local): The innermost scope containing local variables, such as those in side a function or method.

E (Enclosing): The scope that contains non-local and non-global variables. For example, when dealing with nested functions, if function A contains function B, then for names in B, the scope of A is the enclosing scope.

G (Global): The outermost scope at the script level, containing the module's global variables.

B (Built-in): The scope containing built-in variables and keywords, searched last.

Search Order: L → E → G → B.

When a name cannot be found locally, Python searches the enclosing local scope (such as in closures), then the global scope, and finally the built-in scope.

global_var = 10

def outer_function():
    enclosing_var = 20
    
    def inner_function():
        local_var = 30
    

In essence, variables defined inside a function are not directly accessible from outside. However, external variables can be passed into functions or referenced direct using special keywords.

global and nonlocal Keywords

When you need to access or modify variables from an outer scope within an inner scope, the global and nonlocal keywords accomplish this.

Using the global Keyword:

counter = 100

def update_counter():
    global counter
    print(counter)

Using the nonlocal Keyword:

def outer():
    value = 50
    
    def inner():
        nonlocal value
        value = 100

Tags: python namespace scope global nonlocal

Posted on Mon, 08 Jun 2026 17:34:06 +0000 by mrhinman