Search code examples
pythonpython-c-apipython-c-extension

How to check if a PyObject is a String or Unicode for a Python C Extension


In Python(2), the idiomatic way to check if a variable is of str or unicode type is

isinstance(var, basestr)

In the Concrete Object Layer documentation, I did not see anything resembling basestr.

Currently I am validating variables like the following:

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

Is there a more concise way to check if a PyObject is of type str or unicode?


Solution

  • There is a PyBaseString_Type (see for example stringobject.h, strangely I also couldn't find it in the documentation...) which is identical to basestring:

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