Section 12.23

Python

Definition

Python is a general-purpose, high-level programming language. Its programs work with objects whose types are checked while the program runs, and memory is reclaimed automatically. The Python Language Reference and the documentation of the standard library define the language; the Python Software Foundation maintains both. The reference implementation, CPython, is written in C: it compiles source code into bytecode §2.4, a compact instruction format, and runs the bytecode in an interpreter §2.13. Other implementations include PyPy and MicroPython. Python is a name, taken from the comedy group Monty Python, not an abbreviation.

The idea

A short script adds two numbers read from a file, stores the sum in an array §14.5 of NumPy §12.29, the most widely used Python library for numerical arrays, passes it to a function in a C library and writes the result to disk. The addition follows the rules of the language, the stored element follows NumPy’s rules for fixed-size numbers, the C function follows the rules of C and of the machine, and the file follows the rules of the operating system. The source code looks uniform, but four sets of rules decide what happens.

The core idea is a layering of guarantees. The language promises some behaviors everywhere: integers never overflow, and an index outside a list raises an exception instead of reading other memory. Each implementation and version adds behaviors of its own. Native code, machine code compiled from C or another language and loaded into the interpreter, follows its own rules, which Python’s protections do not reach. And whatever touches files, processes, clocks or text encodings depends on the operating system. To predict what a program does, find the layer whose rules govern each operation.

How it works

CPython runs a program as follows.

  1. It compiles each module, a file of Python source, into bytecode, which it caches in a directory named __pycache__.

  2. Its interpreter loop executes the bytecode one instruction at a time. Every value is an object with a type and a count of the references to it; the object is freed when the count drops to zero, and a separate cycle collector frees groups of objects that refer only to one another.

  3. When the program imports a native extension, a shared library compiled against CPython’s C API, CPython loads that machine code into its own process and calls it directly. The ctypes module goes further: it calls functions in any shared library, converting arguments as the programmer declares.

  4. When the program uses the operating system, through modules such as os, socket or subprocess, CPython makes a system call and turns an error code into an exception.

Each behavior comes from one of five layers.

Worked example

The sum 250+10250 + 10 under four sets of rules, with CPython 3.12.3 and NumPy 2.3.3 on Linux:

  1. Built-in integers: 250 + 10 gives 260. A Python int has no fixed width.

  2. A NumPy array of type uint8, unsigned 8-bit integers from 0 to 255: adding np.array([10], dtype=np.uint8) to np.array([250], dtype=np.uint8) gives array([4], dtype=uint8), with no error or warning. NumPy follows unsigned wraparound §4.16, the C rule for unsigned integers: the result is reduced modulo 28=2562^8 = 256, and (250+10)mod256=260−256=4(250 + 10) \bmod 256 = 260 - 256 = 4.

  3. The array module with type code 'B', unsigned bytes: after a = array.array('B', [250]), the statement a[0] = a[0] + 10 computes 260 with Python integers, then raises OverflowError when it tries to store it.

  4. ctypes: ctypes.c_uint8(260).value gives 4. ctypes does no overflow checking and keeps the low 8 bits, a narrowing conversion §4.19: 260 is 0x104 in hexadecimal, and its low 8 bits are 0x04, which is 4.

The same sum gives 260, 4, an exception, or 4. Each is the documented contract of its layer.

A call into C adds a second boundary, the ABI §12.47 (application binary interface): the machine-level rules for passing arguments and returning results. ctypes cannot read a C function’s declaration, so the programmer states it, and ctypes trusts the statement. Take sqrt, the square-root function of the C mathematics library libm, on x86-64 Linux. Without a declaration, libm.sqrt(2.0) raises ctypes.ArgumentError, because ctypes does not convert a Python float unless told to. With argtypes set to [ctypes.c_double] but no restype, ctypes assumes a C int result. The x86-64 calling convention returns a double in a floating-point register and an int in a general-purpose register, so ctypes reads a register that sqrt never set; one test run returned 1. With restype set to ctypes.c_double, the call returns 1.4142135623730951. The fault lay in the declared ABI, not in Python’s number rules.

Stated precisely

For code that uses only built-in types and standard-library modules other than ctypes, and apart from bugs in the interpreter, the language guarantees three things. Integer arithmetic is exact, limited only by memory; a computation that needs more memory than is available raises MemoryError, or ends the process if the operating system stops it first. Indexing a list, tuple, string, byte string or byte array outside its length raises IndexError and never reads or writes other memory. An operation that a value’s type does not support raises TypeError.

The guarantees stop at three boundaries. At a native extension or a ctypes call, the native code’s rules and the ABI apply, including undefined behavior §4.12 when the code is misused. At a system call, the operating system’s contract applies. Across versions, the guarantees are those of the running version, which sys.version_info and sys.implementation report. A statement about a program’s behavior is reproducible only if it names the implementation and version, the build (standard or free-threaded), every native package with its version, and the operating system and processor architecture.

Limits and common mistakes

Type hints §12.46, the annotations such as -> int that declare the intended type of a value, are not checked when the program runs. A function annotated to return an int can return a string; only a separate checker, such as mypy, reads the hints.

The GIL protects the interpreter’s own data, not the program’s. A statement such as counter += 1 is several bytecode instructions, and the interpreter may switch threads between them, so two threads that run it are not guaranteed to count correctly. Protect shared data with a lock.

Safety at the Python level does not extend into native packages. A memory bug in a native extension can be exploited like a bug in any C program, and a crash there ends the interpreter without an exception that the program could catch.

Python’s float is binary64, so decimal fractions are approximated: 0.1 + 0.2 == 0.3 is False, because the sum is 0.30000000000000004. Exact integers are also not cheap: input that becomes a huge integer can be made expensive to process, which is why the 4300-digit conversion limit exists.

A virtual environment §12.24 selects which packages an interpreter loads. It does not isolate the program from the operating system.

Questions answered

Which behaviors depend on interpreter version, native extensions, or the operating system?

Everything outside a small core depends on one of the three. The language itself fixes only exact integers of unlimited size, indexing that checks bounds and raises an exception instead of touching other memory, exceptions for errors, and strings made of Unicode code points.

To make a claim about a Python program reproducible, record all of these and test the behavior at each boundary that the claim crosses.

Related entries: ctypes and foreign function interface (FFI) (§16.15), NumPy (§12.29), subprocess (§12.40), Native application binary interface (ABI) (§12.47), Virtual environment (§12.24), Unsigned modular arithmetic (§4.16), Binary floating-point representation, special values, and rounding (§4.49). Further reading: [64, 115, 187, 271].