Python Code Objects: co_varnames, co_consts, co_names

When Python compiles source code into bytecode, it encapsulates the executable instructions and execution context into an immutable structure called a code object (types.CodeType). Key attributes within this object—specifically co_varnames, co_consts, and co_names—act as indexed lookup tables that the Python Virtual Machine (PVM) relies on to execute operations with high efficiency. Instead of repeatedly resolving variable and constant names dynamically at runtime via slow string searches, the PVM uses these tuples to map bytecode instructions directly to precomputed memory offsets.

How the Python Virtual Machine Uses Lookup Tables

Python bytecode runs on an evaluation loop where instructions operate on an evaluation stack. Bytecode operations take integer arguments that represent indices into arrays stored in the code object. When an instruction like LOAD_CONST 1 executes, the PVM does not evaluate a value directly; it retrieves the item located at index 1 from the code object's internal constant table.

This design drastically reduces memory overhead through string interning and deduplication, while making lookups an \(O(1)\) array-indexing operation.


co_consts: Managing Literals and Nested Code

The co_consts tuple stores every literal value defined within the scope of the code block.


co_varnames: Fast Local Variable Resolution

The co_varnames tuple contains the names of all local variables used within a code object, starting with the function arguments.


co_names: Resolving Globals, Built-ins, and Attributes

The co_names tuple contains names referenced in the code block that are not local variables.


Practical Example

Consider the following function:

import math

def calculate_area(radius):
    factor = 2
    return factor * math.pi * radius

Inspecting its code object (calculate_area.__code__) reveals how the compiler distributes symbols across these three tuples:

By separating identifiers into local indices (co_varnames), literal values (co_consts), and dynamic symbols (co_names), Python balances static execution performance with the dynamism of a runtime-evaluated language.