pythonstringpyobject

Python: get string representation of PyObject?


I've got a C python extension, and I would like to print out some diagnostics.

I'm receiving a string as a PyObject*.

What's the canonical way to obtain a string representation of this object, such that it usable as a const char *?


Solution

  • Use PyObject_Repr (to mimic Python's repr function) or PyObject_Str (to mimic str), and then call PyString_AsString to get char * (you can, and usually should, use it as const char*, for example:

    PyObject* objectsRepresentation = PyObject_Repr(yourObject);
    const char* s = PyString_AsString(objectsRepresentation);
    

    This method is OK for any PyObject. If you are absolutely sure yourObject is a Python string and not something else, like for instance a number, you can skip the first line and just do:

    const char* s = PyString_AsString(yourObject);