Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 *?

update: clarified to emphasize access as const char *.

like image 492
Mark Harrison Avatar asked Mar 18 '11 19:03

Mark Harrison


People also ask

How do you print a string representation in Python?

Python __str__() This method returns the string representation of the object. This method is called when print() or str() function is invoked on an object.

What is PyObject in Python?

PyObject is an object structure that you use to define object types for Python. All Python objects share a small number of fields that are defined using the PyObject structure. All other object types are extensions of this type. PyObject tells the Python interpreter to treat a pointer to an object as an object.

What is string representation in Python?

Strings are Arrays Like many other popular programming languages, strings in Python are arrays of bytes representing unicode characters. However, Python does not have a character data type, a single character is simply a string with a length of 1.


2 Answers

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); 
like image 136
piokuc Avatar answered Oct 05 '22 23:10

piokuc


Here is the correct answer if you are using Python 3:

static void reprint(PyObject *obj) {     PyObject* repr = PyObject_Repr(obj);     PyObject* str = PyUnicode_AsEncodedString(repr, "utf-8", "~E~");     const char *bytes = PyBytes_AS_STRING(str);      printf("REPR: %s\n", bytes);      Py_XDECREF(repr);     Py_XDECREF(str); } 
like image 30
Romuald Brunet Avatar answered Oct 05 '22 23:10

Romuald Brunet