A code object is the compiled form of a module, a function, a class body or a lambda.
The body of a .pyc file is the module’s code object. Each function or class
defined in it is another code object inside co_consts. In the file a code
object is the type byte c, then the fields below, in order, with nothing
between them.
Fields
The four numbers at the start and co_firstlineno are 16-bit little-endian
integers. The other fields are whole marshal
objects, each with its own type byte.
| Field | Stored as | What it holds |
|---|---|---|
co_argcount | 16-bit number | How many positional parameters the code has |
co_nlocals | 16-bit number | How many local variables, parameters included |
co_stacksize | 16-bit number | The most items the code needs on the stack at one time |
co_flags | 16-bit number | Facts about the code, as bits: see Flags |
co_code | s string | The bytes of the instructions |
co_consts | tuple | The constants the code uses. Instructions refer to them by index. Code objects of nested functions and classes are here too. For a function the first item is its documentation string, or None |
co_names | tuple of strings | Names used as attributes and as global names |
co_varnames | tuple of strings | The names of the local variables, parameters first |
co_filename | string | The path of the source file as given to the compiler |
co_name | string | The name of the function or class, or ? for a module |
co_firstlineno | 16-bit number | The source line the code starts at |
co_lnotab | s string | The line number table |
Flags
co_flags is a set of bits. CPython’s Include/compile.h in
1.5.2 and 2.0.1 defines these four.
| Bit | Name | Meaning |
|---|---|---|
| 0x0001 | CO_OPTIMIZED | The code uses fast local variables |
| 0x0002 | CO_NEWLOCALS | A new dictionary is made for the locals when the code runs |
| 0x0004 | CO_VARARGS | The code has a *args parameter |
| 0x0008 | CO_VARKEYWORDS | The code has a **kwargs parameter |
The explorer shows any other set bit by the name a later release gave it. A file from these releases should have none.