[Python-3000] str.format vs. string.Formatter exceptions (original) (raw)

Guido van Rossum guido at python.org
Tue Sep 4 05:09:28 CEST 2007


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

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 "", line 1, in ValueError: Not enough positional arguments in format string >>> Formatter().format("{0}") Traceback (most recent call last): File "", line 1, in File "/shared/src/python/py3k/Lib/string.py", line 201, in format return self.vformat(formatstring, args, kwargs) File "/shared/src/python/py3k/Lib/string.py", line 220, in vformat obj, argused = self.getfield(fieldname, args, kwargs) File "/shared/src/python/py3k/Lib/string.py", line 278, in getfield obj = self.getvalue(first, args, kwargs) File "/shared/src/python/py3k/Lib/string.py", line 235, in getvalue 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

-- --Guido van Rossum (home page: http://www.python.org/~guido/)



More information about the Python-3000 mailing list