getting the culprit from an exception

Alex Martelli aleaxit at yahoo.com
Wed Aug 1 11:34:35 EDT 2001


"gyromagnetic" <gyromagnetic at excite.com> wrote in message
news:4620daca.0107281647.4a84a5c8 at posting.google.com...
> Hi,
> I'm a relative newbie to Python. Is it possible to determine the
> member of a list that caused an exception when using a 'mapped'
> function?

Unfortunately, builtin function 'map' doesn't preserve this
information anywhere, I believe (from studying the sources
of builtin_map in source file Python/bltinmodule.c).  The
relevant snippet:

  if (func == Py_None)
   value = alist;
  else {
   value = PyEval_CallObject(func, alist);
   Py_DECREF(alist);
   if (value == NULL)
    goto Fail_1;
  }

occurs within a C for-loop whose control variable is i,
so map() here 'knows' the index i for which the exception
occurred... but it jumps out of the loop, to label Fail_1,
without saving i anywhere.

I agree your request is quite a reasonable one, but I believe
you would have to phrase it as an enhancement request of
some sort (generally done by opening it as 'a bug' on
sourceforge, I think -- somebody more knowledgeable about
the process pls correct me... what IS the proper way to
submit a minor feature request such as this one?).  It's
hard (for me at least) to think of a suitable way for map
to preserve this useful information so that interested
Python code might access it.  Perhaps map() might just
try to add an exception_index attribute to the exception
object (giving up if the exception object does not let
such a supplementary attribute be added to it -- normally
exceptions are class instances, so it's no problem to
add an attribute to them).  I can imagine problems with this:

def mepper(sequence):
    return map(float, sequence)

try:
    x = map(mepper, sequence_of_sequences)
except ValueError, y:
    print "what now?"

it's unclear how y could usefully register both of
the relevant exception_index value -- the one for
the item of sequence_of_sequences and the one for
the item of THAT sequence.  Such nesting is not
bounded, of course.  Simplest would be for the
'outermost' map that's propagating an exception
to record ITS exception_index, I guess.


I think the required patch to bltinmodule.c would
be half a dozen lines between the
   if (value == NULL)
and the
    goto Fail_1;
(including the needed braces), but since it's unclear
whether this will be accepted by the maintainers I'm
not going to write and (more significantly:-) test
and debug those six-or-so-lines (as they're quite as
capable of writing them, or more:-).  I do suggest
that you formally record this enhancement request in
sourceforge, if it's indeed significant for you.


Alex






More information about the Python-list mailing list