[Python-3000] str.format vs. string.Formatter exceptions
Eric Smith
eric+python-dev at trueblade.com
Mon Sep 3 17:06:55 CEST 2007
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.
More information about the Python-3000
mailing list