Lesson · Getting Started
Python Program Lifecycle
48 min readPython Program Lifecycle
Python source does not normally execute directly as machine code. Understanding parsing, bytecode, the virtual machine, and import-time execution gives you a useful high-level model without drowning in implementation details.
Learning goals
- Trace the stages a
.pyfile passes through: parse, compile to bytecode, then execution by the evaluation loop. - Explain what
compile("...", "<name>", "exec")returns and howexecruns that code object. - Say where
.pyccaches live, what they speed up, and why deleting them is safe. - Describe what happens when a module is imported for the first time and why imports can have side effects.
- Classify a failure as parse-time, import-time, or runtime, and name the stage to inspect first.
Mental model
The stages answer where questions: a missing colon fails at the first arrow, a .pyc cache sits between the second and third, and an exception while code runs belongs to the last stage.
Mental model
read it top to bottom
source text ↓ parse: grammar check, syntax errors stop here code object with bytecode ↓ exec or import: statements run, names bind live module state
Core idea
Executing a Python file has two engines: a compile step that turns source into a code object, and an evaluation loop that runs that object's instructions. Errors are easiest to diagnose once you know which engine they came from, and import adds only a trigger: the first import of a module is what sets the second engine going.
Source code
A Python source file is Unicode text containing Python syntax, conventionally stored with a .py suffix. The runtime parses this source before it can execute it.
Parsing
Parsing checks source against Python's grammar and produces an internal syntax representation. Invalid syntax fails before the program can perform ordinary runtime work.
Compilation to bytecode
CPython compiles parsed source into code objects containing bytecode instructions. This compilation is automatic and distinct from compiling directly to native machine code.
Python virtual machine
The phrase 'Python virtual machine' is a useful high-level model for the machinery that executes Python bytecode. In CPython, this corresponds to the bytecode evaluation loop and surrounding runtime.
.pyc files
CPython can cache compiled bytecode in .pyc files, commonly under __pycache__. The cache speeds loading but is an implementation detail and never replaces the source as the program's semantic definition.
Import-time execution
When a module is imported for the first time in a process, Python executes its top-level code to initialize the module namespace. This is why imports can have side effects.
Runtime execution model
At runtime, Python evaluates instructions while maintaining frames, namespaces, references to objects, and exception state. Later internals lessons make each of these components more concrete.
High-level CPython overview
CPython is the reference implementation you are most likely running: its pipeline is source to bytecode to an evaluation loop, with a .pyc cache to skip recompilation. This overview names the stages so you can place a bug in one of them, and later internals lessons open up each stage rather than replace the model.
Walkthrough
sourceis a plain string holding a function definition; binding it executes nothing.compile(source, "<demo>", "exec")parses and compiles that text in execution mode and returns acodeobject, which the first print confirms.exec(code)runs the module-level statements in the code object inside the current namespace, and thedefstatement bindsadd; that binding is why the final line can calladd(2, 3)and print5."<demo>"is only the filename that error messages and tracebacks will show; it never affects execution. Compiling a string with a missing colon makes theSyntaxErrorappear at thecompilecall, beforeexecis reached.- Predict before running: what
type(code)prints, whetheraddexists beforeexec(code), and what happens if the source string contains a syntax error.
Experiments to try
- Print
code.co_namesandcode.co_constsand find two things: the nameaddand the nested code object that represents the function. - Save a module whose top level prints a line, import it twice in one session, and explain why the message appears once; then reload it with
importlib.reloadand compare. - Compile the same string once with mode
"exec"and once with"eval"; run a source that is a single expression such as1 + 2and record which modes accept it. - Delete the
__pycache__folder next to an imported module, import the module again, and watch the.pycfile reappear. State what the cache saved and why deleting it changed no behavior.
Common mistakes
- Reading the reported line of a
SyntaxErrortoo literally: the parser complains where the grammar first becomes impossible, which can be a line or a token away from the real cause. - Believing
.pycfiles should be kept or committed: they are a regenerable cache, source edits invalidate them, and version control should ignore__pycache__. - Assuming imports are free: the first import executes the module's top-level code, so heavy work or I/O at the top of a module slows every importer and can raise at import time.
- Confusing compile time with run time for names:
compilechecks grammar, not whether a name such asaddexists, so a code object can compile cleanly and still fail withNameErrorwhen executed.
Practice: Easy
- Run the worked example, then print
code.co_namesandcode.co_consts; find the nameaddand the nested code object that represents the function. - Save a module with a top-level
printand import it twice in one session; explain why the message appears once, then reload it withimportlib.reloadand compare. - Compile a string with a deliberate syntax error and read the exception; note which argument of
compileappears in the message.
Practice: Medium
- Write
my_module.py, import it from a fresh script, delete__pycache__, and import again; record when the.pycfile reappears and what it saves. - Compile a source string that references a name you bound in the script, such as
print(value). Runexec(code)and thenexec(code, {})and explain theNameErrorthe empty namespace produces. - Compare importing a module with reloading it: describe one development situation in which
importlib.reloadis needed and one in which a fresh process is the honest answer.
Practice: Hard
- Wrap the
compileandexeccalls of the worked example in separatetry/exceptblocks and show with a broken source that theSyntaxErroris raised bycompile, beforeexecruns. - Build an import chain of three modules that each print a line at the top level; predict the print order, then run it and reconcile any mismatch with import-time execution.
- Time
python -c "import decimal"againstpython -c "pass"using your shell's timing tool; state which stage of the lifecycle dominates a trivial program's start-up.
Lesson checklist
- I can name the stages the worked example moves through: parse, compile, execute.
- I can explain what
compilechecks and what it deliberately does not check. - I can say what
.pycfiles cache and why they are safe to delete. - I can explain why the first import of a module can print or fail before my code uses it.
Remember
Python's lifecycle is short: parse the source, compile it to a code object, then run its instructions in the evaluation loop. `.pyc` files cache the second stage, imports trigger the third for module top-level code, and knowing which stage a failure belongs to tells you whether to fix grammar, imports, or runtime logic.
Interview angles
What is the main purpose of **Source code**?+
A Python source file is Unicode text containing Python syntax, conventionally stored with a .py suffix. The runtime parses this source before it can execute it.
What should you pay attention to when using **Parsing**?+
Parsing checks source against Python's grammar and produces an internal syntax representation. Invalid syntax fails before the program can perform ordinary runtime work.
How does **Compilation to bytecode** fit into this lesson?+
CPython compiles parsed source into code objects containing bytecode instructions. This compilation is automatic and distinct from compiling directly to native machine code.
Why is deleting `__pycache__` safe?+
The .pyc files are a cache of compiled bytecode; CPython regenerates them automatically from the source the next time a module is imported. The source stays the definition, so removing the cache costs one recompile and changes no behavior.