The header is 8 bytes: a magic number that identifies the bytecode, and the modification time of the source file. The code object follows straight after it. Both are 4-byte little-endian numbers. CPython writes the magic number, then a time of 0, then the code object, and goes back to fill in the real time last.
Magic number
Offset 0, 4 bytes. The low two bytes are the number that names the bytecode, and the
high two are always 0D 0A, a carriage return and a line feed. CPython
compares the whole value and recompiles if it differs. The table lists every value
from the known list in CPython’s source, with the note that source gives.
| Magic number | Bytes in the file | Release | What the source says it changed |
|---|---|---|---|
| 3000 | B8 0B 0D 0A | Python 3000 | None given |
| 3010 | C2 0B 0D 0A | Python 3000 | removed UNARY_CONVERT |
| 3020 | CC 0B 0D 0A | Python 3000 | added BUILD_SET |
| 3030 | D6 0B 0D 0A | Python 3000 | added keyword-only parameters |
| 3040 | E0 0B 0D 0A | Python 3000 | added signature annotations |
| 3050 | EA 0B 0D 0A | Python 3000 | print becomes a function |
| 3060 | F4 0B 0D 0A | Python 3000 | PEP 3115 metaclass syntax |
| 3061 | F5 0B 0D 0A | Python 3000 | string literals become unicode |
| 3071 | FF 0B 0D 0A | Python 3000 | PEP 3109 raise changes |
| 3081 | 09 0C 0D 0A | Python 3000 | PEP 3137 make __file__ and __name__ unicode |
| 3091 | 13 0C 0D 0A | Python 3000 | kill str8 interning |
| 3101 | 1D 0C 0D 0A | Python 3000 | merge from 2.6a0, see 62151 |
| 3103 | 1F 0C 0D 0A | Python 3000 | __file__ points to source file |
| 3111 | 27 0C 0D 0A | 3.0a4 | WITH_CLEANUP optimization |
| 3131 | 3B 0C 0D 0A | 3.0 | lexical exception stacking, including POP_EXCEPT |
| 3141 | 45 0C 0D 0A | 3.1a1 | optimize list, set and dict comprehensions: change LIST_APPEND and SET_ADD, add MAP_ADD |
| 3151 | 4F 0C 0D 0A | 3.1 | optimize conditional branches: introduce POP_JUMP_IF_FALSE and POP_JUMP_IF_TRUE |
| 3160 | 58 0C 0D 0A | 3.2a1 | add SETUP_WITH |
| 3170 | 62 0C 0D 0A | 3.2a2 | add DUP_TOP_TWO, remove DUP_TOPX and ROT_FOUR |
| 3180 | 6C 0C 0D 0A | 3.2 | add DELETE_DEREF |
Files from before 3030, which are all early pre-releases, have no
co_kwonlyargcount field, and the explorer reads them without it.
Source modification time
Offset 4, 4 bytes: the modification time of the .py file that was
compiled, in seconds since 1970, as a 32-bit field. When Python imports the module it
compares this with the source file’s time, and if they are not equal the source is
compiled again. The explorer shows the field as a date and time in UTC.
File names and folders
Python 3.0 and 3.1 put the compiled file next to its source, as
foo.pyc, or foo.pyo with the -O option.
Python 3.2 keeps them in a __pycache__ folder beside the source, as
PEP 3147 describes, and puts the
interpreter’s tag in the name: __pycache__/foo.cpython-32.pyc, or
.pyo with -O.