The purpose of this enhancement would be to get the item in a list that caused an exception when applying a mapped function. For instance, suppose that I want to detect if there is an item in a list that is not a number. For this illustration I try to map float on the list and then catch the exception. try: map(float, mylist) except ValueError: print "The item %s in mylist is not a number." % (my_item) The problem is that I do not know which item in the list caused the exception. How do I get my_item? This information could probably be useful in a number of different contexts. Thank you.
Logged In: YES user_id=357491 Well, if you were doing this with a list comprehension it isn't hard:: try: float_list = [float(x) for x in mylist] except ValueError: print "The item %s in mylist is not a number." % x Since list comprehensions are practically just a 'for' loop in a much tighter way the variables used stick around just as if you had used a 'for' loop. The other issue is the way errors propogate in C. If map were to return its own error specifying which item caused a problem it would have to overwrite the exception that was raised in the first place and overwriting exceptions on the whole is bad. If you really are in love with map you can always define your own wrapper around float to raise the exception you want:: def myfloat(num): try: return float(num) except ValueError: raise ValueError("The item %s in mylist is not a number." % num) I personally feel this RFE should be rejected. Anyone else agree?
Logged In: YES user_id=89016 I we had exception chaining (i.e. each exception can reference another exception, that is the cause for this one), this would just be a special case. A traceback could then look like this: >>> map(float, [0, 1, None, 3]) Traceback (most recent call last): File "", line 1, in ? TypeError: in entry None at position 2 Caused by: TypeError: float() argument must be a string or a number
Logged In: YES user_id=357491 Considering it will probably require changing the binary layout of exceptions I would have to agree that a PEP is in order.