Detect invalid string literal formatting

Bug #1361849 reported by asmeurer
6
This bug affects 1 person
Affects Status Importance Assigned to Milestone
Pyflakes
Confirmed
Wishlist
Unassigned

Bug Description

It would be nice if pyflakes could detect invalid formatting errors on string literals. Something like

'abc' % stuff
'%s' % (a, b)
'{}'.format(1, 2)
'{x} {y}'.format(x=1, y=2, z=3)

It would only operate on string literals, so there's no type inferencing or anything.

Revision history for this message
Ian Cordasco (icordasc) wrote :

So while the first two are certainly wrong, the last one can be difficult realistically.

>>> '{}'.format(1, 2)
'1'
>>> '{a} {b}'.format(a=1, b=2, c=3)
'1 2'

It doesn't balk at the fact that you provided more parameters than necessary. (Not say like '%s' % (1, 2).)

This can also be tricky because you could build up a dictionary and then do '{a} {b}'.format(**my_dict).

I definitely agree that the simpler cases (using %) should be somewhat easy to handle. I'm not sure about the latter two since str.format seems to allow more arguments than necessary.

Florent (florent.x)
Changed in pyflakes:
importance: Undecided → Wishlist
Revision history for this message
asmeurer (asmeurer) wrote :

Ah, that was a mistake on my part. I didn't realize that new-style formatting allows too many arguments. It doesn't allow too few arguments, so that could still be checked.

Regarding format(**mydict), it shouldn't bother with it. It should only check the easy obvious case where it 100% definitely *will* raise an exception, i.e., string _literal_ with a % operator or .format method, and explicit arguments in either case. For % if the rhs is not a tuple literal we can only detect no format strings as we can't know if the rhs will be a tuple or not. Similarly, if .format() is used with * or ** we cannot do anything.

Revision history for this message
Phil Frost (bitglue) wrote :

Agreed, this would be a nice addition.

Changed in pyflakes:
status: New → Confirmed
To post a comment you must log in.
This report contains Public information  
Everyone can see this information.

Other bug subscribers

Remote bug watches

Bug watches keep track of this bug in other bug trackers.