In CPython, a code object represents compiled executable Python code. It stores bytecode and metadata such as constants, referenced names and source positions. A function object additionally supplies the global namespace, default argument values and, when needed, a closure connecting free variables to captured values. A code object by itself does not contain that execution context.[ref]
For example, calling a function factory twice can create two functions with the same code object but different captured values. Their behavior differs because their closures differ, even though their instructions are shared. Inspecting f.__code__ therefore describes executable structure rather than a complete snapshot of f's environment. Python documents code objects as immutable; version-specific bytecode details should not be treated as a permanent cross-version file format.

Articles by others on the same topic (0)

There are currently no matching articles.