Matthew Moisen
Matthew Moisen

Reputation: 18279

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?

Upvotes: 2

Views: 2271

Answers (1)

MSeifert
MSeifert

Reputation: 152597

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;
}

Upvotes: 1

Related Questions