utility to get a nice printable string from any object. (reference neutral)
| 1129 | |
| 1130 | // utility to get a nice printable string from any object. (reference neutral) |
| 1131 | CString GetReprText( PyObject *objectUse ) |
| 1132 | { |
| 1133 | PyObject *s; |
| 1134 | CString csRet; |
| 1135 | #ifdef UNICODE |
| 1136 | // PyObject_Unicode disappeared in Py3k, where PyObject_Str returns unicode object |
| 1137 | #if (PY_VERSION_HEX < 0x03000000) |
| 1138 | s=PyObject_Unicode(objectUse); |
| 1139 | #else |
| 1140 | s=PyObject_Str(objectUse); |
| 1141 | #endif |
| 1142 | if (s){ |
| 1143 | csRet = CString(PyUnicode_AsUnicode(s)); |
| 1144 | Py_DECREF(s); |
| 1145 | return csRet; |
| 1146 | } |
| 1147 | #else |
| 1148 | // Assumes that this will always be compiled with UNICODE defined for py3k |
| 1149 | s=PyObject_Str(objectUse); |
| 1150 | if (s){ |
| 1151 | csRet = CString(PyString_AsString(s)); |
| 1152 | Py_DECREF(s); |
| 1153 | return csRet; |
| 1154 | } |
| 1155 | #endif |
| 1156 | |
| 1157 | PyErr_Clear(); |
| 1158 | s = PyObject_Repr(objectUse); |
| 1159 | if (s==NULL){ |
| 1160 | PyErr_Clear(); |
| 1161 | csRet.Format(_T("<type %s> (no string representation)"), objectUse->ob_type->tp_name); |
| 1162 | return csRet; |
| 1163 | } |
| 1164 | |
| 1165 | // repr() should return either a string or unicode object, but not sure if this is enforced. |
| 1166 | if (PyUnicode_Check(s)) |
| 1167 | csRet = CString(PyUnicode_AS_UNICODE(s)); |
| 1168 | else if (PyString_Check(s)) |
| 1169 | csRet = CString(PyString_AS_STRING(s)); |
| 1170 | else |
| 1171 | csRet.Format(_T("??? repr() for type %s returned type %s ???"), objectUse->ob_type->tp_name, s->ob_type->tp_name); |
| 1172 | Py_DECREF(s); |
| 1173 | return csRet; |
| 1174 | |
| 1175 | /* This was apparently trying to remove enclosing quotes, parens, and brackets but will only succeed for quotes |
| 1176 | Forget about it for now |
| 1177 | Py_ssize_t len=strlen(szRepr); |
| 1178 | if (len > 2 && strchr("\"'[(", *szRepr)) { |
| 1179 | if (szRepr[len-1]==*szRepr) { |
| 1180 | ++szRepr; |
| 1181 | len-=2; // drop first and last chars. |
| 1182 | } |
| 1183 | } |
| 1184 | csRet= CString( szRepr, PyWin_SAFE_DOWNCAST(len, Py_ssize_t, int) ); |
| 1185 | */ |
| 1186 | } |
no test coverage detected