File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change @@ -108,6 +108,26 @@ def __del__(self):
108108 b'<string>:7: RuntimeWarning: Testing PyErr_WarnEx' ,
109109 ])
110110
111+ def test__pyerr_setkeyerror (self ):
112+ # Test _PyErr_SetKeyError()
113+ _pyerr_setkeyerror = _testinternalcapi ._pyerr_setkeyerror
114+ for arg in (
115+ "key" ,
116+ # check that a tuple argument is not unpacked
117+ (1 , 2 , 3 ),
118+ # PyErr_SetObject(exc_type, exc_value) uses exc_value if it's
119+ # already an exception, but _PyErr_SetKeyError() always creates a
120+ # new KeyError.
121+ KeyError ('arg' ),
122+ ):
123+ with self .subTest (arg = arg ):
124+ with self .assertRaises (KeyError ) as cm :
125+ # Test calling _PyErr_SetKeyError() with an exception set
126+ # to check that the function overrides the current
127+ # exception.
128+ _pyerr_setkeyerror (arg )
129+ self .assertEqual (cm .exception .args , (arg ,))
130+
111131
112132class Test_FatalError (unittest .TestCase ):
113133
Original file line number Diff line number Diff line change @@ -928,23 +928,6 @@ def test_tp_bases_slot_none(self):
928928 _testcapi .create_heapctype_with_none_bases_slot
929929 )
930930
931- def test__pyerr_setkeyerror (self ):
932- # Test _PyErr_SetKeyError()
933- _pyerr_setkeyerror = _testinternalcapi ._pyerr_setkeyerror
934- for arg in (
935- "key" ,
936- # check that a tuple argument is not unpacked
937- (1 , 2 , 3 ),
938- KeyError ('arg' ),
939- ):
940- with self .subTest (arg = arg ):
941- with self .assertRaises (KeyError ) as cm :
942- # Test calling _PyErr_SetKeyError() with an exception set
943- # to check that the function overrides the current
944- # exception.
945- _pyerr_setkeyerror (arg )
946- self .assertEqual (cm .exception .args , (arg ,))
947-
948931
949932@requires_limited_api
950933class TestHeapTypeRelative (unittest .TestCase ):
Original file line number Diff line number Diff line change @@ -246,7 +246,11 @@ PyErr_SetObject(PyObject *exception, PyObject *value)
246246 _PyErr_SetObject (tstate , exception , value );
247247}
248248
249- /* Set a key error with the specified argument.
249+ /* Set a key error with the specified argument. This function should be used to
250+ * raise a KeyError with an argument instead of PyErr_SetObject(PyExc_KeyError,
251+ * arg) which has a special behavior. PyErr_SetObject() unpacks arg if it's a
252+ * tuple, and it uses arg instead of creating a new exception if arg is an
253+ * exception.
250254 *
251255 * If an exception is already set, override the exception. */
252256void
You can’t perform that action at this time.
0 commit comments