A namespace in Python refers to the naming system used to ensure that names are unique and won't lead to conflicts. Namespaces map names to objects. Python uses different types of namespaces, including:
Python resolves variable names using the LEGB rule, which stands for:
len
, sum
, etc.A Local scope is the innermost scope. It refers to names defined inside the current function. When Python executes a function, it creates a local namespace specific to that function.
An Enclosing scope occurs when functions are nested. The enclosing function's variables can be accessed by the inner function unless shadowed or overridden.
The Global scope refers to names defined at the top level of a script or module. These names are accessible anywhere in the module unless overridden by a local name.
The Built-in scope is the outermost scope that contains names predefined by Python. These are always available, such as print
, type
, int
, len
, and more.
x = "global"
def outer():
x = "enclosing"
def inner():
x = "local"
print(x)
inner()
outer() # Output: local
x = "global"
def outer():
x = "enclosing"
def inner():
print(x)
inner()
outer() # Output: enclosing
The nonlocal
keyword is used to modify a variable in the enclosing (E) scope inside a nested function. It tells Python not to treat the variable as local.
def outer():
message = "outer"
def inner():
nonlocal message
message = "modified"
print("Inner:", message)
inner()
print("Outer:", message)
outer()
Variable shadowing occurs when a variable in a local scope has the same name as a variable in an outer scope. The inner one hides the outer one.
x = 5
def func():
x = 10 # Shadows global x
print(x)
func() # Output: 10
print(x) # Output: 5
Python provides built-in functions to inspect namespaces:
globals()
returns a dictionary of the global namespacelocals()
returns a dictionary of the local namespacex = 42
print(globals()['x']) # Access x from global scope
def demo():
y = 99
print(locals()) # Shows local variables
demo()
list
, str
, sum
.Under the hood, Python implements namespaces using dictionaries. You can access them via:
x = 10
print(globals()) # Dictionary of all global symbols
def greet():
name = "Alice"
print("Hello", name)
greet()
language = "Python"
def show():
print("Programming in", language)
show()
count = 10
def update():
global count
count += 1
update()
print(count)
print(len("hello")) # 'len' is from built-in namespace
def outer():
x = "outer value"
def inner():
print(x) # access enclosing scope
inner()
outer()
In summary, understanding namespaces, the LEGB rule, and related tools is essential for writing clean and bug-free Python programs.