Skip to content

Commit a7e2dc9

Browse files
committed
Default .throw()'s exc_context to the current exception
1 parent 5e8323a commit a7e2dc9

1 file changed

Lines changed: 16 additions & 8 deletions

File tree

‎Objects/genobject.c‎

Lines changed: 16 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -583,16 +583,20 @@ _gen_throw(PyGenObject *gen, int close_on_genexit,
583583
goto failed_throw;
584584
}
585585

586-
/* hide the current thread's exception context from the generator */
587-
PyThreadState *tstate = _PyThreadState_GET();
588-
assert(tstate != NULL);
589-
PyObject *prev_exc = tstate->exc_info->exc_value;
590-
tstate->exc_info->exc_value = (exc_context == NULL ? Py_None : exc_context);
591-
586+
/* If an exception context is provided, set it (and restore it after) */
587+
PyThreadState *tstate;
588+
PyObject *prev_exc = NULL;
589+
if (exc_context != NULL){
590+
tstate = _PyThreadState_GET();
591+
assert(tstate != NULL);
592+
prev_exc = tstate->exc_info->exc_value;
593+
tstate->exc_info->exc_value = exc_context;
594+
}
592595
PyErr_Restore(typ, val, tb);
593596
PyObject* ret = gen_send_ex(gen, Py_None, 1, 0);
594-
595-
tstate->exc_info->exc_value = prev_exc;
597+
if (prev_exc != NULL){
598+
tstate->exc_info->exc_value = prev_exc;
599+
}
596600
return ret;
597601

598602
failed_throw:
@@ -659,6 +663,10 @@ gen_throw(PyObject *op, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnam
659663
return NULL;
660664
}
661665
}
666+
/* default to current exception */
667+
if (exc_context == NULL){
668+
exc_context = _PyErr_GetTopmostException(_PyThreadState_GET())->exc_value;
669+
}
662670
return _gen_throw(gen, 1, typ, val, tb, exc_context);
663671
}
664672

0 commit comments

Comments
 (0)