Namespaces and Scope in Python (original) (raw)

Every variable, function and class is associated with a name. As programs grows, Python needs a systematic way to manage these names and determine where they can be accessed. This is achieved through namespaces and scope, which help organize names within different parts of a program.

Namespace

A namespace is a collection of names and their associated objects. Python stores the names of variables, functions and classes in namespaces. This helps organize names and prevents conflicts when the same name is used in different parts of a program. Internally, namespaces are implemented using dictionaries.

Python `

name = "Emma" def greet(): message = "Hello"

greet()

`

**Explanation:

Types of Namespaces

Python mainly uses three types of namespaces. Each namespace is created for a specific purpose and stores names in different parts of a program.

type_of_namespaces

**1. Built-in Namespace: contains names that are available automatically in every Python program. These names are provided by Python itself, so you can use them without defining them.

Python `

print("Hello") print(len("Python"))

`

**Explanation:

**2. Global Namespace: contains names that are created at the top level of a program, outside all functions and classes. These names can usually be accessed from anywhere within the same module.

Python `

score = 95 def show_score(): print(score)

show_score()

`

**Explanation:

**3. Local Namespace: created whenever a function is called. Variables defined inside the function are stored in this namespace. These variables are available only while the function is executing.

Python `

def show_age(): age = 25 print(age)

show_age()

`

**Explanation:

Lifetime of a Namespace

The lifetime of a namespace refers to how long that namespace exists in memory. Different namespaces have different lifetimes:

x = 5 def outer(): y = 10

def inner():
    z = 15

inner()

outer()

`

**Explanation:

Accessing Global Variables Inside a Function

A function can directly read a global variable. However, if you want to modify the global variable inside a function, you must use the global keyword.

Python `

count = 5 def update(): global count count += 1 print(count)

update()

`

**Explanation:

Scope of Objects

A scope is the region of a program where a name can be accessed. Even if a variable exists in a program, it cannot always be accessed everywhere. Its accessibility depends on the scope in which it was created.

Python `

def outer(): def inner(): num = 10 print("Inside inner:", num)

inner()
print(num)

outer()

`

**Output

ERROR!
Inside inner: 10
Traceback (most recent call last):
File "<main.py>", line 9, in
File "<main.py>", line 7, in outer
NameError: name 'num' is not defined. Did you mean: 'sum'?

**Explanation:

LEGB Rule

When Python encounters a variable name, it searches for that name in a specific order known as the LEGB Rule. LEGB stands for:

Python searches these scopes one by one and uses the first matching name it finds.

Python `

x = "Global" def outer(): x = "Enclosing"

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

inner()

outer()

`