gh-128398: improve error messages when incorrectly using with and async with (#132218)

Improve the error message with a suggestion when an object supporting the synchronous
(resp. asynchronous) context manager protocol is entered using `async with` (resp. `with`)
instead of `with` (resp. `async with`).
This commit is contained in:
Bénédikt Tran 2025-04-19 10:44:01 +02:00 committed by GitHub
parent 95800fe6e7
commit 8a9c6c4d16
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
10 changed files with 211 additions and 47 deletions

View file

@ -4425,9 +4425,14 @@
if (attr_o == NULL) {
if (!_PyErr_Occurred(tstate)) {
_PyFrame_SetStackPointer(frame, stack_pointer);
_PyErr_Format(tstate, PyExc_TypeError,
_Py_SpecialMethods[oparg].error,
Py_TYPE(owner_o)->tp_name);
const char *errfmt = _PyEval_SpecialMethodCanSuggest(owner_o, oparg)
? _Py_SpecialMethods[oparg].error_suggestion
: _Py_SpecialMethods[oparg].error;
stack_pointer = _PyFrame_GetStackPointer(frame);
assert(!_PyErr_Occurred(tstate));
assert(errfmt != NULL);
_PyFrame_SetStackPointer(frame, stack_pointer);
_PyErr_Format(tstate, PyExc_TypeError, errfmt, owner_o);
stack_pointer = _PyFrame_GetStackPointer(frame);
}
JUMP_TO_ERROR();