Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get string representation of PyObject in Python3?

I am debugging Python source code (CPython 3.4). I'm receiving a PyObject*. I would like to printf it.

For example (from Objects/floatobject.c of Python 3.4 source code):

PyObject *o_ndigits = NULL;
Py_ssize_t ndigits;

x = PyFloat_AsDouble(v);
if (!PyArg_ParseTuple(args, "|O", &o_ndigits))
    return NULL;

How do I printf o_ndigits? It is almost same as this question: Python: get string representation of PyObject?, but for Python3. With original solution, I got "undefined reference to PyString_AsString" error.

like image 929
arjunaskykok Avatar asked Dec 09 '13 07:12

arjunaskykok


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 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. Square brackets can be used to access elements of the string.

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.


1 Answers

Both PyObject_Repr and PyObject_ASCII return a unicode str representation of the object. If your terminal doesn't use UTF-8, you probably want the ASCII escaped representation. Get the multibyte string with PyUnicode_AsUTF8 or PyUnicode_AsUTF8AndSize. The new implementation in 3.3 caches the UTF-8 byte string, so don't deallocate it after printing.

As to PyString_AsString, that became PyBytes_AsString or PyBytes_AS_STRING for the 3.x bytes type.

like image 101
Eryk Sun Avatar answered Nov 06 '22 17:11

Eryk Sun