Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I print the type of a PyObject in an error message for an embedded Python script?

Tags:

c++

python

My C++ code has this check in it:

if (1 != PyString_Check( key ))

and I'd like to get a "char*" of the type that it actually is in order to provide a more useful error message. Using the C API for Python, how would I do this?

like image 573
Tim37 Avatar asked Dec 12 '14 20:12

Tim37


2 Answers

PyTypeObject* type = key->ob_type;
const char* p = type->tp_name;
std::cout << "My type is " << p << std::endl;
like image 71
Shmil The Cat Avatar answered Nov 07 '22 06:11

Shmil The Cat


As of Python 2.6, there is a macro, Py_TYPE, which should be used to access the type object of a PythonObject. You can then fetch the tp_name field which contains the fully-qualified name of the type. This means that the type of an object obj can be fetched as a C-string with:

const char* p = Py_TYPE(obj)->tp_name;
like image 43
Milliams Avatar answered Nov 07 '22 07:11

Milliams