Quark's Outlines: Python Name Spaces

python dev.to

Quark’s Outlines: Python Name Spaces

Overview, Historical Timeline, Problems & Solutions

An Overview of Python Name Spaces

What is a Python name space?

When you write code in Python, you give names to values. A Python name space is the place where those names are stored. It is like a labeled shelf that holds objects. When you ask for a name, Python looks in the shelf to find it.

A name space is a mapping between names and objects. In Python, that mapping is usually a dictionary. Each name space stores the current known names and their values.

Python lets you manage names by storing them in name spaces.

x = 5
print(globals()["x"])
# prints:
# 5
Enter fullscreen mode Exit fullscreen mode

The globals() function returns the current global name space. You can look up a name and find its value.

How many name spaces does Python use?

Python uses three main name spaces when running code: local, global, and built-in. Each one is searched in order when Python tries to find a name. Local is the first shelf. Global is the next shelf. Built-in is the last shelf.

Each function or block of code runs in its own execution frame. The frame sets the local and global name spaces.

Python searches for names in a fixed order: local, global, built-in.

def demo():
    x = 10
    print(locals()["x"])

demo()
# prints:
# 10
Enter fullscreen mode Exit fullscreen mode

Here, locals() returns the local name space of the demo() function. Python found the name x there.

How do names become local or global?

When Python sees a name, it decides if that name is local or global by looking at how you use it. If you assign a value to the name in a code block, Python makes it local. If you use global, Python treats it as global. The same rule applies to nonlocal for nested functions.

You cannot assign to a global name without saying so. You must declare it first with global.

Python lets you control where a name lives using global or nonlocal.

count = 0

def add():
    global count
    count += 1

add()
print(count)
# prints:
# 1
Enter fullscreen mode Exit fullscreen mode

Without the global statement, the name count would be treated as a new local name and not affect the global value.


A Historical Timeline of Python Name Spaces

Where do Python’s name space rules come from?

Python name spaces follow from long traditions in structured programming. They help manage how values are stored and found. This timeline shows how Python shaped its name space model by building on earlier systems and simplifying control.


People designed scope and name systems in programming

1960 —Block scope in ALGOL introduced local variables and nested name visibility.

1972 —Global and local stacks in C separated function-level and file-level scope.


People built Python’s three-level name space model

1991 —Python 0.9.0 introduced global, local, and built-in name spaces tied to execution frames.

2000 —Dynamic features like exec and eval worked with customizable name space dictionaries.

2003 —Global and nonlocal statements became required to rebind outer names safely.

2010 —Function scoping stabilized with improved shadowing rules and traceability.

2025 —Stable execution model kept the name space structure clear and unchanged.


Problems & Solutions with Python Name Spaces

How do you use Python name spaces the right way?

Python uses name spaces to keep values organized while code runs. Each code block runs inside a frame, and each frame has local and global name spaces. These problems show how name spaces affect what Python sees and what it cannot see.


Problem: How do you modify a name in the outer scope in Python?

You define a value and use it inside a function. But when you run the function, Python says the name does not exist. You expected Python to use your global variable, but it made a new local one.

Problem: You want to share a name between a function and the outer scope.

Solution: Python lets you mark the name as global to make it refer to the same value everywhere.

Python lets you bind names to global space using global.

counter = 0

def step():
    global counter
    counter += 1

step()
print(counter)
# prints:
# 1
Enter fullscreen mode Exit fullscreen mode

Without the global line, Python would raise an error because counter += 1 would try to read an uninitialized local name.


Problem: How do you see what names are in use in Python?

You are writing a function that changes many variables. You want to see what names are active inside the function as it runs. You also want to inspect the global names.

Problem: You want to examine the current local and global name spaces.

Solution: Python provides locals() and globals() to return the current mappings.

Python lets you see active names using built-in inspection tools.

x = 100

def report():
    y = 200
    print("Local:", locals())
    print("Global:", "x =", globals()["x"])

report()
# prints:
# Local: {'y': 200}
# Global: x = 100
Enter fullscreen mode Exit fullscreen mode

Python shows the two separate name spaces so you can know which values are in each.


Problem: How do you avoid accidental name changes in Python?

You write a helper function that uses the same name as one of your main program variables. Now your main value is changed unexpectedly after calling the helper.

Problem: You want to keep helper names separate from program names.

Solution: Python keeps local name spaces separate by default. Avoid global names inside functions unless needed.

Python keeps function names isolated using local name spaces.

value = "main"

def helper():
    value = "helper"
    print("Inside:", value)

helper()
print("Outside:", value)
# prints:
# Inside: helper
# Outside: main
Enter fullscreen mode Exit fullscreen mode

Each block has its own space. Reusing a name locally does not affect the global value unless you declare it as global.


Problem: How do you use eval() safely in Python?

You want to evaluate a string as code. You want to control what names the string sees when it runs.

Problem: You want to give custom name spaces to code run with eval().

Solution: Python lets you pass dictionaries to control global and local name spaces in eval().

Python lets you set name space mappings for dynamic code.

scope = {"x": 2, "y": 3}
print(eval("x * y", scope))
# prints:
# 6
Enter fullscreen mode Exit fullscreen mode

The string "x * y" is evaluated using the custom scope dictionary. Python does not use the default globals or locals.


Problem: handle name lookup when a name is missing

You write code that refers to a name, but you forget to define it. When Python runs, it stops with an error. You want to understand what error this is and how Python looks for names.

Problem: You want to know what happens when a name is not found.

Solution: Python looks in local, then global, then built-in name spaces. If no match is found, it raises a NameError.

Python raises an error when name lookup fails in all name spaces.

try:
    print(missing_name)
except NameError as e:
    print("Caught error:", e)
# prints:
# Caught error: name 'missing_name' is not defined
Enter fullscreen mode Exit fullscreen mode

Python checks each shelf of names in order. If the name is not on any shelf, it stops and reports the problem.


Like, Comment, Share, and Subscribe

Did you find this helpful? Let me know by clicking the like button below. I'd love to hear your thoughts in the comments, too! If you want to see more content like this, don't forget to subscribe. Thanks for reading!


Mike Vincent is an American software engineer and app developer from Los Angeles, California. More about Mike Vincent

Source: dev.to

arrow_back Back to Tutorials