Better error message for string formatting

what about throwing an exception as argument is provided without any format specifier for scenarios like below`

str = "jkg" 
ch = "ft"

new_str = str % ch 

➜  cpython git:(main) ✗ ./python.exe l.py
Traceback (most recent call last):
  File "/Users/agent-hellboy/cpython/l.py", line 5, in <module>
    s = l % (p,k)
TypeError: argument is provided without any format specifier

Currently, the message instead says: TypeError: not all arguments converted during string formatting.

I don’t see why the proposal is any better. If anything, it’s less accurate: it could be that the string does contain format specifiers - just not enough for the format arguments.

I’m not claiming that the current message is the best it could be. But fixing this kind of issue seems like something that would be part of a larger project, rather than something where people independently propose wording for one-off changes.

(Also: I assume this is considered a TypeError by analogy with the one caused by calling a function with the wrong number of arguments. But that case already seems questionable to me; and the string formatting issue definitely seems to me like it should be a ValueError instead. It’s caused, ultimately, by the contents of a string.)


By the way, if you use new-style formatting, you don’t get an error from this, although you do get an error for not enough format arguments (equivalently, too many specifiers in the format string).

>>> 'jkg'.format('ft')
'jkg'
>>> 'jkg{}{}'.format('ft')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: Replacement index 1 out of range for positional args tuple

That latter message is… pretty bad, honestly. But using IndexError (which is indeed a subclass of ValueError) makes sense, at least.

1 Like

Thanks, got your points, btw, the current exception smees a debug log to the person who has developed it, I don’t know if it’s targeting the user. pretty inexperienced to comment , but just sharing my thoughts.