Python Advance Course

Namespace and LEGB Rule in Python

Namespace and LEGB Rule in Python

A namespace is a system that maps variable names to objects.

Example:

x = 10
y = 20

Here x and y are stored in a namespace where names map to values. Python uses namespaces to avoid naming conflicts. There are four types of namespaces: local, enclosing, global, and built-in. Python follows the LEGB rule to resolve variable names.

LEGB stands for Local, Enclosing, Global, Built-in. Python searches in this order when a variable is accessed.

Local scope means variables defined inside a function.

Example:

def func():
    x = 10
    print(x)

func()

Output:

10

A mistake in local scope is trying to access a variable outside the function.

Example:

def func():
    x = 10

print(x)

Error:

NameError: name 'x' is not defined

Global scope means variables defined outside functions and accessible inside functions.

Example:

x = 100

def func():
    print(x)

func()

Output:

100

A mistake in global scope happens when modifying a global variable without declaring it global.

Example:

x = 10

def func():
    x = x + 1
    print(x)

Error:

UnboundLocalError

Correct solution using global keyword:

x = 10

def func():
    global x
    x = x + 1
    print(x)

func()

Output:

11

Enclosing scope happens in nested functions where inner functions can access outer function variables.

Example:

def outer():
    x = 50

    def inner():
        print(x)

    inner()

outer()

Output:

50

A mistake in enclosing scope is modifying outer variables without using nonlocal.

Example:

def outer():
    x = 10

    def inner():
        x = x + 1
        print(x)

    inner()

Correct solution using nonlocal:

def outer():
    x = 10

    def inner():
        nonlocal x
        x = x + 1
        print(x)

    inner()

outer()

Output:

11

Built-in scope includes Python default functions like print, len, sum, max.

Example:

print(len("Python"))

Output:

6

A mistake is overwriting built-in functions.

Example:

len = 10
print(len("Hello"))

This breaks the built-in function.

Python resolves variables using LEGB rule:

Local → Enclosing → Global → Built-in

Example:

x = "global"

def outer():
    x = "enclosing"

    def inner():
        x = "local"
        print(x)

    inner()

outer()

Output:

local

Final example combining global, enclosing, and nonlocal:

x = 10

def outer():
    x = 20

    def inner():
        nonlocal x
        x = 30

    inner()
    print(x)

outer()

Output:

30

Filters

No filters available for this view.

Reset All