python - 如何使用 PyArg_ParseTupleAndKeywords 来解析带有可选参数和关键字的元组?

标签 python python-2.7 numpy

我到处都看过,但我找不到 PyArg_ParseTupleAndKeywords() 与元组一起使用的示例 - 包含可选参数 - 关键字。我找到的最接近的是 this question ,但答案并不是特别有用。大多数示例似乎都将关键字作为可选参数,但元组似乎也应该能够包含可选参数。

假设我正在尝试解析以下参数:

  • numpy double 组(强制)
  • numpy double 组(可选,无关键字)
  • 可选关键字参数:
    • k1 => numpy double 组
    • k2 => 整数
    • k3 => 双
    • k4 => Python类实例

看来我应该做类似的事情

static PyObject* pymod_func(PyObject* self, PyObject* args, PyObject* kwargs) {
  static char* keywords[] = {"k1", "k2", "k3", "k4", NULL};

  PyObject *arg1, *arg2, *k1, *k4
  PyObject *arr1, *arr2, *karr1;
  double *k3;
  int *k2;
  PyArg_ParseTupleAndKeywords(args, kwargs, "O!|O!OidO", keywords, &arg1, &PyArray_Type, &arg2, &PyArray_Type, &k1, &PyArray_Type, &k2, &k3, &k4);

  arr1 = PyArray_FROM_OTF(arg1, NPY_FLOAT64, NPY_ARRAY_INOUT_ARRAY);
  if (arr1 == NULL) return NULL;

  arr2 = PyArray_FROM_OTF(arg1, NPY_FLOAT64, NPY_ARRAY_INOUT_ARRAY);
  // no null check, because optional

  karr1 = PyArray_FROM_OTF(k1, NPY_FLOAT64, NPY_ARRAY_INOUT_ARRAY);
  // again, no null check, because this is optional

  // do things with k3, k2, and k4 also

  return NULL;
}

我看过的其他地方,但没有找到太多帮助:

使用 PyArg_ParseTupleAndKeywords() 的正确方法是什么?

最佳答案

从 Python 3.3 开始,您可以在格式字符串中使用 $indicate that the rest of the arguments are keyword-only , 从 Python 3.6 开始,you can indicate a positional-only parameter通过在 keywords 参数中使用空名称。

因此,在足够高版本的 Python 中,您可以使用如下代码:

static char* keywords[] = {"", "", "k1", "k2", "k3", "k4", NULL};

// [...]

PyArg_ParseTupleAndKeywords(args, kwargs,
                            "O!|O!$O!idO", keywords,
                            &PyArray_Type, &arg1, &PyArray_Type, &arg2,
                            &PyArray_Type, &k1, &k2, &k3, &k4);

关于python - 如何使用 PyArg_ParseTupleAndKeywords 来解析带有可选参数和关键字的元组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35068114/

相关文章:

python - 值错误 : attempt to get argmax of an empty sequence

Python IOError : [Errno 2] when saving captured image 错误

Python 如何关闭线程中实例化的套接字?

python - 在已经安装了 Python 2.7 的系统上从源代码编译 Python 2.7.3

python - 如何获取二维数组中指定列的唯一行的索引

multithreading - Numba 是 "only"将我的代码改进了 4 倍。它能做得更好吗?

python - 如何在 pyautoit 中带来一个始终出现在背景而不是前景中的窗口?

python - 使用 BeautifulSoup 解析具有多个根的 xml

python - 如何使用 pefile 从 PE 文件中获取 .text 部分

python - matplotlib Six.moves.urllib.request导入错误