[Python-3000] str.format vs. string.Formatter exceptions
Eric Smith
eric+python-dev at trueblade.com
Tue Sep 4 22:05:53 CEST 2007
Guido van Rossum wrote:
> Since IndexError and KeyError are conceptually like ValueError but in
> a more narrowly defined context, I think IndexError and KeyError
> actually make sense here (even though they don't inherit from
> ValueError).
>
> --Guido
Okay, I'll change these to IndexError and KeyError.
Eric.
>
> On 9/3/07, Eric Smith <eric+python-dev at trueblade.com> wrote:
>> Ron Adam points out some differences in which exceptions are thrown by
>> str.format and string.Formatter. For example, on a missing positional
>> argument:
>>
>> >>> "{0}".format()
>> Traceback (most recent call last):
>> File "<stdin>", line 1, in <module>
>> ValueError: Not enough positional arguments in format string
>>
>> >>> Formatter().format("{0}")
>> Traceback (most recent call last):
>> File "<stdin>", line 1, in <module>
>> File "/shared/src/python/py3k/Lib/string.py", line 201, in format
>> return self.vformat(format_string, args, kwargs)
>> File "/shared/src/python/py3k/Lib/string.py", line 220, in vformat
>> obj, arg_used = self.get_field(field_name, args, kwargs)
>> File "/shared/src/python/py3k/Lib/string.py", line 278, in get_field
>> obj = self.get_value(first, args, kwargs)
>> File "/shared/src/python/py3k/Lib/string.py", line 235, in get_value
>> return args[key]
>> IndexError: tuple index out of range
>>
>> The PEP says: In general, exceptions generated by the formatter code
>> itself are of the "ValueError" variety -- there is an error in the
>> actual "value" of the format string.
>>
>> I can easily change string.Formatter to make this a ValueError, and I
>> think that's probably the right thing to do. For example, if the string
>> comes from a translation module, then there might be an extra parameter
>> added by mistake, in which case ValueError seems right to me.
>>
>> But I'd like to hear if anyone else thinks this should be an IndexError,
>> or maybe they both should be some other exception.
>>
>> Similarly "{x}".format()' currently raises ValueError, but
>> 'Formatter().format("{x}")' raises KeyError.
>> _______________________________________________
>> Python-3000 mailing list
>> Python-3000 at python.org
>> http://mail.python.org/mailman/listinfo/python-3000
>> Unsubscribe: http://mail.python.org/mailman/options/python-3000/guido%40python.org
>>
>
>
More information about the Python-3000
mailing list