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.
It compiles each module, a file of Python source, into bytecode, which it caches in a directory named
__pycache__.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.
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
ctypesmodule goes further: it calls functions in any shared library, converting arguments as the programmer declares.When the program uses the operating system, through modules such as
os,socketorsubprocess, CPython makes a system call and turns an error code into an exception.
Each behavior comes from one of five layers.
The language: integers of unlimited size; indexing of lists, strings and byte strings that checks bounds and raises
IndexError; exceptions for errors; strings made of Unicode code points §12.48.The version. A new minor version (3.12, 3.13, and so on) appears every year. The
matchstatement exists from 3.10, and thedistutilspackage was removed in 3.12. Since 3.11, and in security releases of several older versions, converting a decimal string of more than 4300 digits to an integer, or back, raisesValueError. These conversions take time that grows with the square of the number of digits, so an attacker who supplied a long digit string could stall a program.The implementation. In standard CPython builds, the global interpreter lock (GIL) lets only one thread execute bytecode at a time; CPython 3.13 added an optional free-threaded build without it. CPython closes a file object as soon as the last reference to it disappears; PyPy may close it later. CPython’s
floatis a Cdouble, on all common platforms the IEEE 754 §4.49 binary64 format [271]. String hashes are randomized at each start, so a set of strings can list its members in a different order on each run.Native code uses fixed-width integers and manages memory by hand; a bug there can corrupt memory or end the process without any Python exception.
The operating system. A text file opened without an
encodingargument uses the encoding of the system’s locale settings: UTF-8 (the 8-bit Unicode Transformation Format) on most Linux systems, often an older code page on Windows. Python’s UTF-8 mode, an interpreter option, makes UTF-8 the default everywhere.os.forkexists only on Unix-like systems, and path syntax, signals, file locking and clock resolution differ between systems.
Worked example
The sum under four sets of rules, with CPython 3.12.3 and NumPy 2.3.3 on Linux:
Built-in integers:
250 + 10gives 260. A Pythoninthas no fixed width.A NumPy array of type
uint8, unsigned 8-bit integers from 0 to 255: addingnp.array([10], dtype=np.uint8)tonp.array([250], dtype=np.uint8)givesarray([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 , and .The
arraymodule with type code'B', unsigned bytes: aftera = array.array('B', [250]), the statementa[0] = a[0] + 10computes 260 with Python integers, then raisesOverflowErrorwhen it tries to store it.ctypes:ctypes.c_uint8(260).valuegives 4.ctypesdoes no overflow checking and keeps the low 8 bits, a narrowing conversion §4.19: 260 is0x104in hexadecimal, and its low 8 bits are0x04, 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.
Interpreter version and implementation: the available syntax and library (the
matchstatement from 3.10,distutilsremoved in 3.12); the 4300-digit limit on conversions between integers and decimal strings (3.11 onward, and security releases of several older versions); whether a global interpreter lock (GIL) lets only one thread run Python code at a time (yes in standard CPython builds, no in the free-threaded build of CPython 3.13 and later); when files are closed (CPython at once, PyPy possibly later); and the per-run randomized hashing of strings, which changes the order of a set of strings.Native extensions and
ctypes: fixed-width integers that wrap around or raise errors (in a NumPyuint8array, gives 4); memory safety, since a bug can corrupt memory or crash the process without an exception; and the ABI (application binary interface) of every call, whichctypescannot check: without a declaredrestype, it reads the result as a Cint.The operating system: the default encoding of text files (from the locale settings unless Python’s UTF-8 mode is on), path syntax and case sensitivity, the availability §1.10 of
os.forkand of most signals, file locking, howmultiprocessingstarts processes, clock resolution, and every error that a system call reports.
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].