【问题标题】:finding out how many arguments a PyObject method needs找出 PyObject 方法需要多少个参数
【发布时间】:2012-11-21 11:46:30
【问题描述】:

我们可以提取一个指向 python 方法的 PyObject 使用

PyObject *method = PyDict_GetItemString(methodsDictionary,methodName.c_str());

我想知道该方法需要多少个参数。所以如果函数是

def f(x,y):
    return x+y

我如何知道它需要 2 个参数?

【问题讨论】:

  • 另外,刚刚注意到那里的.c_str() - 所以我猜你正在使用C++。你看过 Boost.Python 或其他包装库吗? - 使用原生 Python C-API 不是最愉快的体验

标签: python python-c-api pyobject


【解决方案1】:

通过 Jon 提供的链接进行操作。假设您不想(或不能)在您的应用程序中使用 Boost,以下应该会为您提供数字(很容易改编自 How to find the number of parameters to a Python function from C?):

PyObject *key, *value;
int pos = 0;
while(PyDict_Next(methodsDictionary, &pos, &key, &value)) {
    if(PyCallable_Check(value)) {
        PyObject* fc = PyObject_GetAttrString(value, "func_code");
        if(fc) {
            PyObject* ac = PyObject_GetAttrString(fc, "co_argcount");
            if(ac) {
               const int count = PyInt_AsLong(ac);
               // we now have the argument count, do something with this function
               Py_DECREF(ac);
            }
            Py_DECREF(fc);
        }
    }
}

如果您使用的是 Python 2.x,那么上述方法绝对有效。在 Python 3.0+ 中,您似乎需要在上面的 sn-p 中使用 "__code__" 而不是 "func_code"

我很欣赏无法使用 Boost(我的公司不会允许它用于我最近从事的项目),但总的来说,如果可以的话,我会尽量使用它,因为我'我们发现 Python C API 通常会在您尝试做这样复杂的事情时变得有点繁琐。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-25
    • 2014-08-30
    • 1970-01-01
    • 2012-01-05
    • 1970-01-01
    相关资源
    最近更新 更多