ódulo de extensão Python com número variável de argument
stou tentando descobrir como nos módulos de extensão C ter um número variável (e talvez) bastante grande de argumentos para uma funçã
Lendo sobre PyArg_ParseTuple parece que você precisa saber quantos aceitar, alguns obrigatórios e outros opcionais, mas todos com sua própria variável. Eu estava esperando PyArg_UnpackTuple seria capaz de lidar com isso, mas parece apenas me dar erros de barramento quando tento usá-lo da maneira que parece estar errad
Como exemplo, pegue o seguinte código python que você pode querer transformar em um módulo de extensão (em C
def hypot(*vals):
if len(vals) !=1 :
return math.sqrt(sum((v ** 2 for v in vals)))
else:
return math.sqrt(sum((v ** 2 for v in vals[0])))
Isso pode ser chamado com qualquer número de argumentos ou repetido,hypot(3,4,5)
, hypot([3,4,5])
ehypot(*[3,4,5])
odos dão a mesma respost
O início da minha função C se parece com isso
static PyObject *hypot_tb(PyObject *self, PyObject *args) {
// lots of code
// PyArg_ParseTuple or PyArg_UnpackTuple
}
Many pensa em yasar11732. Aqui, para o próximo sujeito, está um módulo de extensão totalmente funcional (_toolboxmodule.c) que simplesmente aceita qualquer número ou argumento inteiro e retorna uma lista composta por esses argumentos (com um nome ruim). Um brinquedo, mas ilustra o que precisava ser feit
#include <Python.h>
int ParseArguments(long arr[],Py_ssize_t size, PyObject *args) {
/* Get arbitrary number of positive numbers from Py_Tuple */
Py_ssize_t i;
PyObject *temp_p, *temp_p2;
for (i=0;i<size;i++) {
temp_p = PyTuple_GetItem(args,i);
if(temp_p == NULL) {return NULL;}
/* Check if temp_p is numeric */
if (PyNumber_Check(temp_p) != 1) {
PyErr_SetString(PyExc_TypeError,"Non-numeric argument.");
return NULL;
}
/* Convert number to python long and than C unsigned long */
temp_p2 = PyNumber_Long(temp_p);
arr[i] = PyLong_AsUnsignedLong(temp_p2);
Py_DECREF(temp_p2);
}
return 1;
}
static PyObject *hypot_tb(PyObject *self, PyObject *args)
{
Py_ssize_t TupleSize = PyTuple_Size(args);
long *nums = malloc(TupleSize * sizeof(unsigned long));
PyObject *list_out;
int i;
if(!TupleSize) {
if(!PyErr_Occurred())
PyErr_SetString(PyExc_TypeError,"You must supply at least one argument.");
return NULL;
}
if (!(ParseArguments(nums, TupleSize, args)) {
free(nums);
return NULL;
}
list_out = PyList_New(TupleSize);
for(i=0;i<TupleSize;i++)
PyList_SET_ITEM(list_out, i, PyInt_FromLong(nums[i]));
free(nums);
return (PyObject *)list_out;
}
static PyMethodDef toolbox_methods[] = {
{ "hypot", (PyCFunction)hypot_tb, METH_VARARGS,
"Add docs here\n"},
// NULL terminate Python looking at the object
{ NULL, NULL, 0, NULL }
};
PyMODINIT_FUNC init_toolbox(void) {
Py_InitModule3("_toolbox", toolbox_methods,
"toolbox module");
}
Em python, é:
>>> import _toolbox
>>> _toolbox.hypot(*range(4, 10))
[4, 5, 6, 7, 8, 9]