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, and 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, referred to by index. Nested functions and classes are here as code objects. A function’s first constant 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_freevars | tuple of strings | Free variables: names this code uses but an enclosing function defines |
co_cellvars | tuple of strings | Local variables that nested functions refer to |
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. Names are from CPython’s
Include/compile.h at the 2.1.3 and 2.2.3 tags.
| Bit | Name | Meaning | Releases |
|---|---|---|---|
| 0x0001 | CO_OPTIMIZED | The code uses fast local variables | Both |
| 0x0002 | CO_NEWLOCALS | A new dictionary is made for the locals when the code runs | Both |
| 0x0004 | CO_VARARGS | The code has a *args parameter | Both |
| 0x0008 | CO_VARKEYWORDS | The code has a **kwargs parameter | Both |
| 0x0010 | CO_NESTED | The code is a nested function | Both |
| 0x0020 | CO_GENERATOR | The code is a generator function | 2.2 |
| 0x1000 | CO_GENERATOR_ALLOWED | Compiled with from __future__ import generators in effect | 2.2 |
| 0x2000 | CO_FUTURE_DIVISION | Compiled with from __future__ import division in effect | 2.2 |