Quark's Outlines: Python Execution Model
Source: Dev.to
An Overview of the Python Execution Model
What is the Python execution model?
When you run a Python program, Python follows a process to decide what happens and in what order. This process is called the Python execution model. It controls how code is grouped, how values are stored, and what happens when things go wrong.
- Code blocks – logical groupings of statements.
- Execution frames – objects that store a block’s state and link to the next block.
- Name spaces – mappings that hold names and their associated values.
- Exceptions – objects raised when an error occurs.
These four ideas—code blocks, execution frames, name spaces, and exceptions—constitute the execution model.
Python lets you run code using a frame that manages blocks, names, and errors.
def greet():
name = "Ada"
print("Hello,", name)
greet()
# prints:
# Hello, AdaIn the example above, greet() runs inside a new code block and a new execution frame. The variable name lives in the local name space for that frame.
A Historical Timeline of the Python Execution Model
Where did Python’s execution model come from?
Python’s execution model draws on ideas from earlier languages (ALGOL, Lisp) while adding safe name handling and flexible error control. The timeline below shows how the four core concepts evolved.
| Year | Milestone |
|---|---|
| 1960 | Code blocks and scopes introduced in ALGOL – nested blocks with clear local vs. global rules. |
| 1970s | Stack‑based frames become common in Lisp and C – call stacks and local scope rules. |
| 1991 | Code blocks and frames added in Python 0.9.0 to support safe function calls and modular design. |
| 1995 | Exceptions and try/except introduced (try, except, raise). |
| 2001 | Dynamic name‑space access via globals() and locals(). |
| 2006 | exec and eval gain optional name‑space arguments. |
| 2025 | Execution model stabilised – strong support for interactive, script, and module‑based code. |
Problems & Solutions with the Python Execution Model
How do you use the Python execution model the right way?
Python runs code step‑by‑step, creating code blocks, building frames, using name spaces, and raising exceptions as needed. Below are common problems and how to solve them using the model.
1. Seeing Where Python Runs Your Code
Problem: You want to trace how Python enters and exits each code block (i.e., view the active frames).
Solution: Inspect the call stack with sys._getframe() (or the higher‑level inspect module).
import sys
def outer():
def inner():
frame = sys._getframe()
print("Now running:", frame.f_code.co_name)
inner()
outer()
# prints:
# Now running: innerEach time Python enters a new block, it creates a new execution frame that holds the code object and its name spaces.
2. Separating Local and Global Names
Problem: You have a variable value inside a function and another value at module level. Which one does Python use?
Solution: Each frame has two name spaces – local and global. Python looks in the local name space first, then the global one.
value = "global"
def show():
value = "local"
print("Value is:", value)
show()
# prints:
# Value is: localInside show(), the local value masks the global one.
3. Reusing a Block of Code with Its Own Scope
Problem: You need to run a set of statements repeatedly without affecting variables outside the block.
Solution: Define a function (or another callable) – each call gets a fresh local name space.
x = 1
def block():
x = 2
print("Inside block:", x)
block()
print("Outside block:", x)
# prints:
# Inside block: 2
# Outside block: 1The function’s local name space isolates its variables from the surrounding module.
4. Handling Errors Without Stopping the Program
Problem: You want to attempt an operation that might fail, but you don’t want the whole program to crash.
Solution: Use exceptions with try/except blocks.
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero.")
# prints:
# Cannot divide by zero.Python raises an exception; the except block catches it, allowing the program to continue.
5. Inspecting the Current Global and Local Names
Problem: You need to see what names and values are currently defined in the global and local scopes.
Solution: Use the built‑in globals() and locals() functions.
def demo():
a = 10
b = 20
print("Local names:", locals())
print("Global names:", globals().keys())
demo()locals()returns a dictionary of the current local name space.globals()returns a dictionary of the module‑level name space.
Summary
The Python execution model is built around code blocks, execution frames, name spaces, and exceptions. Understanding how these pieces interact lets you:
- Trace program flow with frames.
- Distinguish between local and global variables.
- Isolate code in its own scope.
- Gracefully handle errors.
- Inspect the current execution environment.
Armed with this knowledge, you can write clearer, more robust Python code that leverages the language’s underlying execution mechanics.
The Current Namespaces and How to Print Their Names and Values
Problem
You want to view the contents of the global and local namespaces.
Solution
Python provides the built‑in functions globals() and locals() for this purpose.
Python lets you read namespaces using built‑in lookup tools.
x = 42
def show():
y = "Ada"
print("Globals:", list(globals().keys()))
print("Locals:", list(locals().keys()))
show()
# prints:
# Globals: ['__name__', '__doc__', ..., 'x']
# Locals: ['y']You can use these tools to see what names are defined in each scope.
Call to Action
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 – an American software engineer and app developer from Los Angeles, California.
More about Mike Vincent