如何检查PyObject是否是Python C扩展的字符串或Unicode

时间:2017-02-01 01:33:29

标签: python python-c-api python-c-extension

在Python(2)中,检查变量是str还是unicode类型的惯用方法是

isinstance(var, basestr)

Concrete Object Layer documentation中,我没有看到任何类似于basestr的内容。

目前我正在验证以下变量:

PyObject *key;
//...
if (!PyString_Check(key) && !PyUnicode_Check(key)) {
    PyErr_SetString(PyExc_ValueError, "Key must be string");
    return NULL;
}

是否有更简洁的方法来检查PyObjectstr还是unicode

1 个答案:

答案 0 :(得分:1)

有一个PyBaseString_Type(请参阅例如stringobject.h,奇怪的是我在文档中也找不到它...)与basestring相同:

PyObject *key;
// ...
if (!PyObject_TypeCheck(key, &PyBaseString_Type)) {
    PyErr_SetString(PyExc_ValueError, "key must be a string.");
    return NULL;
}