[Python-3000] str.format vs. string.Formatter exceptions
Ron Adam
rrr at ronadam.com
Tue Sep 4 04:38:22 CEST 2007
Eric Smith 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.
The PEP also says the following in regards to this...
+----------------
Implementation note: The implementation of this proposal is
not required to enforce the rule about a name being a valid
Python identifier. Instead, it will rely on the getattr function
of the underlying object to throw an exception if the identifier
is not legal. The str.format() function will have a minimalist
parser which only attempts to figure out when it is "done" with an
identifier (by finding a '.' or a ']', or '}', etc.).
+----------------
If these return ValueErrors, as I think it has been suggested in the
earlier messages, then this will need to be updated as well.
_RON
> 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/rrr%40ronadam.com
>
>
More information about the Python-3000
mailing list