Error messages from format()

Steven D'Aprano steve+comp.lang.python at pearwood.info
Tue Nov 13 19:38:25 CET 2012


On Tue, 13 Nov 2012 10:08:59 -0500, Colin J. Williams wrote:

> Is there some way to get more informative error messages from the
> builtin format?

Yes -- post a feature request on the Python bug tracker, then wait until 
Python 3.4 comes out in about 16 months.

:(


> Most messages are such as:
> Traceback (most recent call last):
>    File "<interactive input>", line 1, in <module>
> ValueError: Invalid conversion specification
> 
> This example doesn't point to the first invalid case.

Better error messages would be valuable.


> [Dbg]>>> format((25, 31),'{0^9o} a(1:9x}')
> Traceback (most recent call last):
>    File "<interactive input>", line 1, in <module>
> ValueError: Invalid conversion specification

I see at least three problems.

(1) The first brace substitution is missing the colon between the 
argument selector "0" and the format spec "^9o": should be "{0:^9o}".

(2) The second format string has an opening round bracket instead of 
brace: (1:9x}

(3) But you are confusing the str.format method with the format function. 
The format function doesn't take brace substitutions!

The string format method takes a template including brace substitutions, 
plus multiple "objects to be substituted", like this:

py> '{0:^9o} a{1:9x}'.format(25, 31)
'   31     a       1f'

In this case, the template '{0:^9o} a{1:9x}' requires two arguments since 
it has two substitutions, {0} and {1}. Each substitution has a format 
spec following the colon: {0:^9o} and {1:9x}

But the format function only takes a single "object to be substituted", 
and so doesn't take a brace substitution. Instead, it just takes the 
format spec part:


py> format(25, '^9o')
'   31    '
py> format(31, '^9o')
'   37    '

format will not split a tuple into multiple arguments for you, since the 
tuple is considered a single object.



-- 
Steven


More information about the Python-list mailing list