Interpreter vs bytecode
Python is compiled and interpreted. Your source is first compiled into bytecode, a compact instruction list for a virtual stack machine, and the interpreter then executes those instructions one at a time.
Detailed Explanation
"Compiled versus interpreted" is a question people ask about Python and it has no clean answer, because Python does both. The important distinction is what it compiles to. C compiles to machine code your processor runs directly. Python compiles to bytecode, which no processor understands, and a program written in C then walks through that bytecode and performs each step.
The pipeline has four stages. Your text is split into tokens. The tokens are parsed into an abstract syntax tree. A symbol table pass works out which names are local, global, or captured from an enclosing function. Finally the compiler emits bytecode and wraps it in a code object along with constants, names, and line-number information.
A code object is a normal Python value you can inspect. Every function has one on __code__. That is not a debugging trick; it is how the language works.
The interpreter then runs a loop. Fetch the next instruction, do what it says to a stack of values, repeat. total = price + tax becomes roughly: load price, load tax, add the top two stack entries, store the result under total. Each of those is one bytecode instruction.
This design buys two things. Compilation is fast enough to happen at import time, so there is no build step to run and no makefile to maintain. Bytecode is also platform-independent, so the same .py file behaves the same on Linux and Windows without recompilation.
The cost is speed. The interpreter cannot assume price is a number, so + has to look up the type at runtime and dispatch to the right implementation. A C compiler would collapse the same line into a single machine instruction. This overhead per operation is the honest reason pure-Python loops are slow, and the reason numerical libraries push the loop down into C.
Python does cache the compile step. The first time a module is imported, CPython writes a .pyc file into a __pycache__ directory next to the source. On later imports it checks a magic number for the interpreter version plus the source's size and modification time, and reuses the cached bytecode when they match. Note the limit: caching skips compilation, not execution. A .pyc file makes imports faster and makes nothing else faster.
One consequence is worth internalising. Syntax errors are found at compile time, before a single line of your module runs. Everything else — misspelled names, wrong types, missing keys — is found at runtime, only when that exact line executes. A function with a typo inside an if branch nobody takes will sit in production for months without complaint.
The dis module prints the bytecode for any function and is the best way to answer questions like "does this comprehension build an intermediate list?". Read it for understanding, not for micro-optimisation. Opcodes are an implementation detail and change in every minor release: Python 3.11 added a specialising adaptive interpreter that rewrites hot instructions into type-specialised versions at runtime, and 3.12 reshuffled opcodes again.
Code Examples
import dis
def order_total(items):
# A realistic line: attribute lookup, arithmetic, and a function call.
return sum(item["price"] * item["qty"] for item in items)
# Every function carries its compiled form.
print(type(order_total.__code__)) # <class 'code'>
print(order_total.__code__.co_varnames) # ('items',)
# Print the instruction listing. Opcode names and offsets differ between
# Python versions, so read this to understand, never to hard-code.
dis.dis(order_total)# The compiler does a little work up front. Constants are folded.
compiled = compile("total = 2 + 3", "<demo>", "exec")
print(compiled.co_consts[0]) # 5 -> the addition happened at compile time
# Syntax is checked before anything runs; names are not.
try:
compile("def broken(:\n pass", "<demo>", "exec")
except SyntaxError as exc:
# Raised by compile() itself; the wording of exc.msg improves across versions.
print("failed before running:", type(exc).__name__) # failed before running: SyntaxError
def never_called():
return undefined_name + 1 # compiles fine; NameError only if you call it
print("module loaded without touching never_called")Common Gotchas
Syntax errors and name errors happen at different times
one bad bracket stops the entire file from loading, while `custmer_id` instead of `customer_id` waits silently until that branch executes. Linters and type checkers exist to close this gap; the interpreter will not.
`.pyc` files are version-locked and cache-keyed
bytecode written by 3.11 is unusable by 3.12, and the freshness check uses source size and timestamp by default. Restoring files with rewritten timestamps, or shipping a `__pycache__` directory into an image built on another version, can produce confusing stale-code behaviour. Delete `__pycache__` when in doubt, or use `PYTHONDONTWRITEBYTECODE=1`.
Bytecode is not obfuscation
a `.pyc` still contains your names, constants, and docstrings, and decompilers reconstruct readable source. Do not ship secrets or licence checks in bytecode and call it protected.
Scripts run directly are not cached
the top-level file you pass to `python app.py` is compiled every run and gets no `.pyc`. Only imported modules are cached, which is why import-heavy startup is fast on the second run but your entry point is not.