Objetos código¶
Os objetos código são um detalhe de baixo nível da implementação do CPython. Cada um representa um pedaço de código executável que ainda não foi vinculado a uma função.
-
type PyCodeObject¶
A estrutura C dos objetos usados para descrever objetos código. Os campos deste tipo estão sujeitos a alterações a qualquer momento.
-
PyTypeObject PyCode_Type¶
Esta é uma instância de
PyTypeObject
representando o tipo Pythoncode
.
-
int PyCode_Check(PyObject *co)¶
Retorna verdadeiro se co for um objeto
code
. Esta função sempre tem sucesso.
-
int PyCode_GetNumFree(PyCodeObject *co)¶
Retorna o número de variáveis livres em co.
-
PyCodeObject *PyUnstable_Code_New(int argcount, int kwonlyargcount, int nlocals, int stacksize, int flags, PyObject *code, PyObject *consts, PyObject *names, PyObject *varnames, PyObject *freevars, PyObject *cellvars, PyObject *filename, PyObject *name, PyObject *qualname, int firstlineno, PyObject *linetable, PyObject *exceptiontable)¶
- This is Unstable 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 complex ways, meaning that subtle changes to values are likely to result in incorrect execution or VM crashes. Use this function only with extreme care.
Alterado na versão 3.11: Added
qualname
andexceptiontable
parameters.Alterado na versão 3.12: Renamed from
PyCode_New
as part of Unstable C API. The old name is deprecated, but will remain available until the signature changes again.
-
PyCodeObject *PyUnstable_Code_NewWithPosOnlyArgs(int argcount, int posonlyargcount, int kwonlyargcount, int nlocals, int stacksize, int flags, PyObject *code, PyObject *consts, PyObject *names, PyObject *varnames, PyObject *freevars, PyObject *cellvars, PyObject *filename, PyObject *name, PyObject *qualname, int firstlineno, PyObject *linetable, PyObject *exceptiontable)¶
- This is Unstable 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_New
also apply to this function.Novo na versão 3.8: as
PyCode_NewWithPosOnlyArgs
Alterado na versão 3.11: Added
qualname
andexceptiontable
parameters.Alterado na versão 3.12: Renamed to
PyUnstable_Code_NewWithPosOnlyArgs
. The old name is deprecated, but will remain available until the signature changes again.
-
PyCodeObject *PyCode_NewEmpty(const char *filename, const char *funcname, int firstlineno)¶
- Retorna valor: Nova referência.
Retorna um novo objeto código vazio com o nome de arquivo, nome da função e número da primeira linha especificados. O objeto código resultante irá levantar uma
Exception
se executado.
-
int PyCode_Addr2Line(PyCodeObject *co, int byte_offset)¶
Retorna o número da linha da instrução que ocorre em ou antes de
byte_offset
e termina depois disso. Se você só precisa do número da linha de um quadro, usePyFrame_GetLineNumber()
.Para iterar eficientemente sobre os números de linha em um objeto código, use a API descrita em PEP 626 .
-
int PyCode_Addr2Location(PyObject *co, int byte_offset, int *start_line, int *start_column, int *end_line, int *end_column)¶
Define os ponteiros
int
passados para a linha do código-fonte e os números da coluna para a instrução embyte_offset
. Define o valor como0
quando as informações não estão disponíveis para nenhum elemento em particular.Retorna
1
se a função for bem-sucedida e 0 caso contrário.Novo na versão 3.11.
-
PyObject *PyCode_GetCode(PyCodeObject *co)¶
Equivalente ao código Python
getattr(co, 'co_code')
. Retorna uma referência forte a umPyBytesObject
representando o bytecode em um objeto código. Em caso de erro,NULL
é retornado e uma exceção é levantada.Este
PyBytesObject
pode ser criado sob demanda pelo interpretador e não representa necessariamente o bytecode realmente executado pelo CPython. O caso de uso primário para esta função são depuradores e criadores de perfil.Novo na versão 3.11.
-
PyObject *PyCode_GetVarnames(PyCodeObject *co)¶
Equivalente ao código Python
getattr(co, 'co_varnames')
. Retorna uma nova referência a umPyTupleObject
contendo os nomes das variáveis locais. Em caso de erro,NULL
é retornado e uma exceção é levantada.Novo na versão 3.11.
-
PyObject *PyCode_GetCellvars(PyCodeObject *co)¶
Equivalente ao código Python
getattr(co, 'co_cellvars')
. Retorna uma nova referência a umPyTupleObject
contendo os nomes das variáveis locais referenciadas por funções aninhadas. Em caso de erro,NULL
é retornado e uma exceção é levantada.Novo na versão 3.11.
-
PyObject *PyCode_GetFreevars(PyCodeObject *co)¶
Equivalente ao código Python
getattr(co, 'co_freevars')
. Retorna uma nova referência a umPyTupleObject
contendo os nomes das variáveis livres. Em caso de erro,NULL
é retornado e uma exceção é levantada.Novo na versão 3.11.
-
int PyCode_AddWatcher(PyCode_WatchCallback callback)¶
Register callback 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-1
and set an exception.Novo na versão 3.12.
-
int PyCode_ClearWatcher(int watcher_id)¶
Clear watcher identified by watcher_id previously returned from
PyCode_AddWatcher()
for the current interpreter. Return0
on success, or-1
and set an exception on error (e.g. if the given watcher_id was never registered.)Novo na versão 3.12.
-
type PyCodeEvent¶
Enumeration of possible code object watcher events: -
PY_CODE_EVENT_CREATE
-PY_CODE_EVENT_DESTROY
Novo na versão 3.12.
-
typedef int (*PyCode_WatchCallback)(PyCodeEvent event, PyCodeObject *co)¶
Type of a code object watcher callback function.
If event is
PY_CODE_EVENT_CREATE
, then the callback is invoked after co has been fully initialized. Otherwise, the callback is invoked before the destruction of co takes place, so the prior state of co can be inspected.If event is
PY_CODE_EVENT_DESTROY
, taking a reference in the callback to the about-to-be-destroyed code object will resurrect it and prevent it from being freed at this time. When the resurrected object is destroyed later, any watcher callbacks active at that time will be called again.Users of this API should not rely on internal runtime implementation details. Such details may include, but are not limited to, the exact order and timing of creation and destruction of code objects. While changes in these details may result in differences observable by watchers (including whether a callback is invoked or not), it does not change the semantics of the Python code being executed.
Se a função de retorno definir uma exceção, ela deverá retornar
-1
; essa exceção será impressa como uma exceção não reprovável usandoPyErr_WriteUnraisable()
. Caso contrário, deverá retornar0
.É possível que já exista uma exceção pendente definida na entrada da chamada de retorno. Nesse caso, a função de retorno deve retornar
0
com a mesma exceção ainda definida. Isso significa que a callback não pode chamar nenhuma outra API que possa definir uma exceção, a menos que salve e limpe o estado da exceção primeiro e o restaure antes de retornar.Novo na versão 3.12.
Extra information¶
To support low-level extensions to frame evaluation, such as external just-in-time compilers, it is possible to attach arbitrary extra data to code objects.
These functions are part of the unstable C API tier: this functionality is a CPython implementation detail, and the API may change without deprecation warnings.
-
Py_ssize_t PyUnstable_Eval_RequestCodeExtraIndex(freefunc free)¶
- This is Unstable 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 result with
PyCode_GetExtra
andPyCode_SetExtra
to manipulate data on individual code objects.If free is not
NULL
: when a code object is deallocated, free will be called on non-NULL
data stored under the new index. UsePy_DecRef()
when storingPyObject
.Novo na versão 3.6: as
_PyEval_RequestCodeExtraIndex
Alterado na versão 3.12: Renamed to
PyUnstable_Eval_RequestCodeExtraIndex
. The old private name is deprecated, but will be available until the API changes.
-
int PyUnstable_Code_GetExtra(PyObject *code, Py_ssize_t index, void **extra)¶
- This is Unstable API. It may change without warning in minor releases.
Set extra 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, set extra to
NULL
and return 0 without setting an exception.Novo na versão 3.6: as
_PyCode_GetExtra
Alterado na versão 3.12: Renamed to
PyUnstable_Code_GetExtra
. The old private name is deprecated, but will be available until the API changes.
-
int PyUnstable_Code_SetExtra(PyObject *code, Py_ssize_t index, void *extra)¶
- This is Unstable API. It may change without warning in minor releases.
Set the extra data stored under the given index to extra. Return 0 on success. Set an exception and return -1 on failure.
Novo na versão 3.6: as
_PyCode_SetExtra
Alterado na versão 3.12: Renamed to
PyUnstable_Code_SetExtra
. The old private name is deprecated, but will be available until the API changes.