我试图用PySequence_Length
来获取C语言中的Python字典的长度。我意识到我可以使用PyDict_Size
,但我有兴趣使用更通用的函数在某些情况下。Python C-API:在字典中使用'PySequence_Length'
PyObject* d = PyDict_New();
Py_ssize_t res = PySequence_Length(d);
printf("Result : %ld\n", res);
if (res == -1) PyErr_Print();
这种失败,并打印错误:
TypeError: object of type 'dict' has no len()
我的问题是:为什么会失败?虽然Python字典对象不支持的协议序列,所述documentation为PySequence_Length
说:
Py_ssize_t PySequence_Length(PyObject *o)
Returns the number of objects in sequence o on success, and -1 on failure. For objects that do not provide sequence protocol, this is equivalent to the Python expression len(o).
由于字典类型并具有__len__
属性,并且由于表达len(d)
(其中d
是一个字典)适当地返回Python的长度,我不明白为什么PySequence_Length
应该在C失败。
任何解释?文档不正确吗?