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 of
PyTypeObjectrepresenting 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 from
PyCode_GetFirstFreeas 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,use
PyCode_NewEmpty()instead.Since the definition of the bytecode changes often, calling
PyUnstable_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:Added
qualnameandexceptiontableparameters.Changed in version 3.12:Renamed from
PyCode_Newas 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 to
PyUnstable_Code_New(), but with an extra “posonlyargcount” for positional-only arguments.The same caveats that apply toPyUnstable_Code_Newalso apply to this function.Added in version 3.8:as
PyCode_NewWithPosOnlyArgsChanged in version 3.11:Added
qualnameandexceptiontableparameters.Changed in version 3.12:Renamed to
PyUnstable_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 an
Exceptionif executed.
- intPyCode_Addr2Line(PyCodeObject*co,intbyte_offset)¶
Return the line number of the instruction that occurs on or before
byte_offsetand 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 passed
intpointers to the source code line and column numbersfor the instruction atbyte_offset. Sets the value to0wheninformation is not available for any particular element.Returns
1if the function succeeds and 0 otherwise.Added in version 3.11.
- PyObject*PyCode_GetCode(PyCodeObject*co)¶
Equivalent to the Python code
getattr(co,'co_code').Returns a strong reference to aPyBytesObjectrepresenting thebytecode in a code object. On error,NULLis returned and an exceptionis raised.This
PyBytesObjectmay 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 code
getattr(co,'co_varnames').Returns a new reference to aPyTupleObjectcontaining the names ofthe local variables. On error,NULLis returned and an exceptionis raised.Added in version 3.11.
- PyObject*PyCode_GetCellvars(PyCodeObject*co)¶
Equivalent to the Python code
getattr(co,'co_cellvars').Returns a new reference to aPyTupleObjectcontaining 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 code
getattr(co,'co_freevars').Returns a new reference to aPyTupleObjectcontaining the names ofthefree (closure) variables. On error,NULLis 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 to
PyCode_ClearWatcher().In case of error (e.g. no more watcher IDs available),return-1and set an exception.Added in version 3.12.
- intPyCode_ClearWatcher(intwatcher_id)¶
Clear watcher identified bywatcher_id previously returned from
PyCode_AddWatcher()for the current interpreter.Return0on success, or-1and 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_DESTROYAdded in version 3.12.
- typedefint(*PyCode_WatchCallback)(PyCodeEventevent,PyCodeObject*co)¶
Type of a code object watcher callback function.
Ifevent is
PY_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 is
PY_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 return
0with 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.
Code Object Flags¶
Code objects contain a bit-field of flags, which can be retrieved as theco_flags Python attribute (for example usingPyObject_GetAttrString()), and set using aflags argument toPyUnstable_Code_New() and similar functions.
Flags whose names start withCO_FUTURE_ correspond to features normallyselectable byfuture statements. These flags can be used inPyCompilerFlags.cf_flags.Note that manyCO_FUTURE_ flags are mandatory in current versions ofPython, and setting them has no effect.
The following flags are available.For their meaning, see the linked documentation of their Python equivalents.
Flag | Meaning |
|---|---|
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| no effect ( |
| no effect ( |
| no effect ( |
| no effect ( |
| no effect ( |
| no effect ( |
|
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 opaque index value used to adding data to code objects.
You generally call this function once (per interpreter) and use the resultwith
PyCode_GetExtraandPyCode_SetExtrato manipulatedata on individual code objects.Iffree is not
NULL: when a code object is deallocated,free will be called on non-NULLdata stored under the new index.UsePy_DecRef()when storingPyObject.Added in version 3.6:as
_PyEval_RequestCodeExtraIndexChanged in version 3.12:Renamed to
PyUnstable_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 to
NULLand return0 without setting an exception.Added in version 3.6:as
_PyCode_GetExtraChanged in version 3.12:Renamed to
PyUnstable_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_SetExtraChanged in version 3.12:Renamed to
PyUnstable_Code_SetExtra.The old private name is deprecated, but will be available until the APIchanges.