[Python-checkins] python/dist/src/Python exceptions.c,1.37,1.38

gvanrossum@users.sourceforge.net gvanrossum@users.sourceforge.net
Tue, 03 Sep 2002 13:24:18 -0700


Update of /cvsroot/python/python/dist/src/Python
In directory usw-pr-cvs1:/tmp/cvs-serv8495/Python

Modified Files:
	exceptions.c 
Log Message:
Add a custom __str__ method to KeyError that applies repr() to the
missing key.  (Also added a guard to SyntaxError__str__ to prevent
calling PyString_Check(NULL).)


Index: exceptions.c
===================================================================
RCS file: /cvsroot/python/python/dist/src/Python/exceptions.c,v
retrieving revision 1.37
retrieving revision 1.38
diff -C2 -d -r1.37 -r1.38
*** exceptions.c	2 Sep 2002 16:41:55 -0000	1.37
--- exceptions.c	3 Sep 2002 20:24:07 -0000	1.38
***************
*** 786,790 ****
         lineno here */
  
!     if (PyString_Check(str)) {
  	int have_filename = 0;
  	int have_lineno = 0;
--- 786,790 ----
         lineno here */
  
!     if (str != NULL && PyString_Check(str)) {
  	int have_filename = 0;
  	int have_lineno = 0;
***************
*** 845,848 ****
--- 845,886 ----
  
  
+ static PyObject *
+ KeyError__str__(PyObject *self, PyObject *args)
+ {
+     PyObject *argsattr;
+     PyObject *result;
+ 
+     if (!PyArg_ParseTuple(args, "O:__str__", &self))
+ 	return NULL;
+ 
+     if (!(argsattr = PyObject_GetAttrString(self, "args")))
+ 	return NULL;
+ 
+     /* If args is a tuple of exactly one item, apply repr to args[0].
+        This is done so that e.g. the exception raised by {}[''] prints
+          KeyError: ''
+        rather than the confusing
+          KeyError
+        alone.  The downside is that if KeyError is raised with an explanatory
+        string, that string will be displayed in quotes.  Too bad.
+        If args is anything else, use the default Exception__str__().
+     */
+     if (PyTuple_Check(argsattr) && PyTuple_GET_SIZE(argsattr) == 1) {
+ 	PyObject *key = PyTuple_GET_ITEM(argsattr, 0);
+ 	result = PyObject_Repr(key);
+     }
+     else
+ 	result = Exception__str__(self, args);
+ 
+     Py_DECREF(argsattr);
+     return result;
+ }
+ 
+ static PyMethodDef KeyError_methods[] = {
+     {"__str__",  KeyError__str__, METH_VARARGS},
+     {NULL, NULL}
+ };
+ 
+ 
  static
  int get_int(PyObject *exc, const char *name, int *value)
***************
*** 1618,1622 ****
    IndexError__doc__},
   {"KeyError",           &PyExc_KeyError,       &PyExc_LookupError,
!   KeyError__doc__},
   {"ArithmeticError",    &PyExc_ArithmeticError, 0, ArithmeticError__doc__},
   {"OverflowError",      &PyExc_OverflowError,     &PyExc_ArithmeticError,
--- 1656,1660 ----
    IndexError__doc__},
   {"KeyError",           &PyExc_KeyError,       &PyExc_LookupError,
!   KeyError__doc__, KeyError_methods},
   {"ArithmeticError",    &PyExc_ArithmeticError, 0, ArithmeticError__doc__},
   {"OverflowError",      &PyExc_OverflowError,     &PyExc_ArithmeticError,