Code Objects

Code objects are a low-level detail of the CPython implementation.Each one represents a chunk of executable code that hasn’t yet beenbound into a function.

typePyCodeObject

The C structure of the objects used to describe code objects. Thefields of this type are subject to change at any time.

PyTypeObjectPyCode_Type

This is an instance ofPyTypeObject representing the Pythoncode object.

intPyCode_Check(PyObject*co)

Return true ifco is acode object.This function always succeeds.

Py_ssize_tPyCode_GetNumFree(PyCodeObject*co)

Return the number offree (closure) variablesin a code object.

intPyUnstable_Code_GetFirstFree(PyCodeObject*co)
This isUnstable API. It may change without warning in minor releases.

Return the position of the firstfree (closure) variablein a code object.

Changed in version 3.13:Renamed fromPyCode_GetFirstFree as part ofUnstable C API.The old name is deprecated, but will remain available until thesignature changes again.

PyCodeObject*PyUnstable_Code_New(intargcount,intkwonlyargcount,intnlocals,intstacksize,intflags,PyObject*code,PyObject*consts,PyObject*names,PyObject*varnames,PyObject*freevars,PyObject*cellvars,PyObject*filename,PyObject*name,PyObject*qualname,intfirstlineno,PyObject*linetable,PyObject*exceptiontable)
This isUnstable API. It may change without warning in minor releases.

Return a new code object. If you need a dummy code object to create a frame,usePyCode_NewEmpty() instead.

Since the definition of the bytecode changes often, callingPyUnstable_Code_New() directly can bind you to a precise Python version.

The many arguments of this function are inter-dependent in complexways, meaning that subtle changes to values are likely to result in incorrectexecution or VM crashes. Use this function only with extreme care.

Changed in version 3.11:Addedqualname andexceptiontable parameters.

Changed in version 3.12:Renamed fromPyCode_New as part ofUnstable C API.The old name is deprecated, but will remain available until thesignature changes again.

PyCodeObject*PyUnstable_Code_NewWithPosOnlyArgs(intargcount,intposonlyargcount,intkwonlyargcount,intnlocals,intstacksize,intflags,PyObject*code,PyObject*consts,PyObject*names,PyObject*varnames,PyObject*freevars,PyObject*cellvars,PyObject*filename,PyObject*name,PyObject*qualname,intfirstlineno,PyObject*linetable,PyObject*exceptiontable)
This isUnstable API. It may change without warning in minor releases.

Similar toPyUnstable_Code_New(), but with an extra “posonlyargcount” for positional-only arguments.The same caveats that apply toPyUnstable_Code_New also apply to this function.

Added in version 3.8:asPyCode_NewWithPosOnlyArgs

Changed in version 3.11:Addedqualname andexceptiontable parameters.

Changed in version 3.12:Renamed toPyUnstable_Code_NewWithPosOnlyArgs.The old name is deprecated, but will remain available until thesignature changes again.

PyCodeObject*PyCode_NewEmpty(constchar*filename,constchar*funcname,intfirstlineno)
Return value: New reference.

Return a new empty code object with the specified filename,function name, and first line number. The resulting codeobject will raise anException if executed.

intPyCode_Addr2Line(PyCodeObject*co,intbyte_offset)

Return the line number of the instruction that occurs on or beforebyte_offset and ends after it.If you just need the line number of a frame, usePyFrame_GetLineNumber() instead.

For efficiently iterating over the line numbers in a code object, usethe API described in PEP 626.

intPyCode_Addr2Location(PyObject*co,intbyte_offset,int*start_line,int*start_column,int*end_line,int*end_column)

Sets the passedint pointers to the source code line and column numbersfor the instruction atbyte_offset. Sets the value to0 wheninformation is not available for any particular element.

Returns1 if the function succeeds and 0 otherwise.

Added in version 3.11.

PyObject*PyCode_GetCode(PyCodeObject*co)

Equivalent to the Python codegetattr(co,'co_code').Returns a strong reference to aPyBytesObject representing thebytecode in a code object. On error,NULL is returned and an exceptionis raised.

ThisPyBytesObject may be created on-demand by the interpreter and doesnot necessarily represent the bytecode actually executed by CPython. Theprimary use case for this function is debuggers and profilers.

Added in version 3.11.

PyObject*PyCode_GetVarnames(PyCodeObject*co)

Equivalent to the Python codegetattr(co,'co_varnames').Returns a new reference to aPyTupleObject containing the names ofthe local variables. On error,NULL is returned and an exceptionis raised.

Added in version 3.11.

PyObject*PyCode_GetCellvars(PyCodeObject*co)

Equivalent to the Python codegetattr(co,'co_cellvars').Returns a new reference to aPyTupleObject containing the names ofthe local variables that are referenced by nested functions. On error,NULLis returned and an exception is raised.

Added in version 3.11.

PyObject*PyCode_GetFreevars(PyCodeObject*co)

Equivalent to the Python codegetattr(co,'co_freevars').Returns a new reference to aPyTupleObject containing the names ofthefree (closure) variables. On error,NULL is returnedand an exception is raised.

Added in version 3.11.

intPyCode_AddWatcher(PyCode_WatchCallbackcallback)

Registercallback as a code object watcher for the current interpreter.Return an ID which may be passed toPyCode_ClearWatcher().In case of error (e.g. no more watcher IDs available),return-1 and set an exception.

Added in version 3.12.

intPyCode_ClearWatcher(intwatcher_id)

Clear watcher identified bywatcher_id previously returned fromPyCode_AddWatcher() for the current interpreter.Return0 on success, or-1 and set an exception on error(e.g. if the givenwatcher_id was never registered.)

Added in version 3.12.

typePyCodeEvent

Enumeration of possible code object watcher events:-PY_CODE_EVENT_CREATE-PY_CODE_EVENT_DESTROY

Added in version 3.12.

typedefint(*PyCode_WatchCallback)(PyCodeEventevent,PyCodeObject*co)

Type of a code object watcher callback function.

Ifevent isPY_CODE_EVENT_CREATE, then the callback is invokedafterco has been fully initialized. Otherwise, the callback is invokedbefore the destruction ofco takes place, so the prior state ofcocan be inspected.

Ifevent isPY_CODE_EVENT_DESTROY, taking a reference in the callbackto the about-to-be-destroyed code object will resurrect it and prevent itfrom being freed at this time. When the resurrected object is destroyedlater, any watcher callbacks active at that time will be called again.

Users of this API should not rely on internal runtime implementationdetails. Such details may include, but are not limited to, the exactorder and timing of creation and destruction of code objects. Whilechanges in these details may result in differences observable by watchers(including whether a callback is invoked or not), it does not changethe semantics of the Python code being executed.

If the callback sets an exception, it must return-1; this exception willbe printed as an unraisable exception usingPyErr_WriteUnraisable().Otherwise it should return0.

There may already be a pending exception set on entry to the callback. Inthis case, the callback should return0 with the same exception stillset. This means the callback may not call any other API that can set anexception unless it saves and clears the exception state first, and restoresit before returning.

Added in version 3.12.

Extra information

To support low-level extensions to frame evaluation, such as externaljust-in-time compilers, it is possible to attach arbitrary extra data tocode objects.

These functions are part of the unstable C API tier:this functionality is a CPython implementation detail, and the APImay change without deprecation warnings.

Py_ssize_tPyUnstable_Eval_RequestCodeExtraIndex(freefuncfree)
This isUnstable API. It may change without warning in minor releases.

Return a new an opaque index value used to adding data to code objects.

You generally call this function once (per interpreter) and use the resultwithPyCode_GetExtra andPyCode_SetExtra to manipulatedata on individual code objects.

Iffree is notNULL: when a code object is deallocated,free will be called on non-NULL data stored under the new index.UsePy_DecRef() when storingPyObject.

Added in version 3.6:as_PyEval_RequestCodeExtraIndex

Changed in version 3.12:Renamed toPyUnstable_Eval_RequestCodeExtraIndex.The old private name is deprecated, but will be available until the APIchanges.

intPyUnstable_Code_GetExtra(PyObject*code,Py_ssize_tindex,void**extra)
This isUnstable API. It may change without warning in minor releases.

Setextra to the extra data stored under the given index.Return 0 on success. Set an exception and return -1 on failure.

If no data was set under the index, setextra toNULL and return0 without setting an exception.

Added in version 3.6:as_PyCode_GetExtra

Changed in version 3.12:Renamed toPyUnstable_Code_GetExtra.The old private name is deprecated, but will be available until the APIchanges.

intPyUnstable_Code_SetExtra(PyObject*code,Py_ssize_tindex,void*extra)
This isUnstable API. It may change without warning in minor releases.

Set the extra data stored under the given index toextra.Return 0 on success. Set an exception and return -1 on failure.

Added in version 3.6:as_PyCode_SetExtra

Changed in version 3.12:Renamed toPyUnstable_Code_SetExtra.The old private name is deprecated, but will be available until the APIchanges.