bpo-30721: Show correct syntax hint in Py3 when using Py2 redirection syntax by CuriousLearner · Pull Request #2345 · python/cpython (original) (raw)
Don't include an actual format call in the error message - that was just what I used in the issue tracker to represent PyErr_Format
pllaceholders. Instead, you'll want to use the %R
format code to invoke PyObject_Repr
on the operands directly:
PyErr_Format(PyExc_TypeError,
"unsupported operand type(s) for %.100s: "
"'%.100s' and '%.100s'. Did you mean \"print(%.100R, "
"file={.100R})\"",
op_name,
v->ob_type->tp_name,
w->ob_type->tp_name,
w, v);
In the general case, you won't be able to recreate the exact text of the original input, as that's no longer available by the time we get here - we only have a reference to the final runtime objects.
We might decide it's worthwhile adding a special-case check for the RHS being exactly PySys_GetObject("stderr")
and displaying file=sys.stderr
in that case.
Alternatively, we could dispense with the idea of interpolating values entirely, and just use the hardcoded output "Did you mean \"print(<message>, file=<output_stream>)\""