pyupgrade icon indicating copy to clipboard operation
pyupgrade copied to clipboard

constant fold literals in f", .format and % formatting

Open graingert opened this issue 3 years ago • 6 comments

I have a project with a bunch of tests that check logging messages (with testfixtures.LogCapture) they look like this:

log.check((module.__name__, "INFO", "the user {user!r} did a bad".format(user=u"user")))

The reason - because the repr of u"user" is different on py3 and py2. I'd like to see pyupgrade --py3-plus rewrite them all to:

log.check((module.__name__, "INFO", "the user 'user' did a bad"))

graingert avatar Nov 03 '20 18:11 graingert

It might also be good to hit the explicit str concat "the user" + repr(u"user") + "did a bad". and %r formatting

graingert avatar Nov 03 '20 18:11 graingert

this also applies to numeric literals, I just noticed pyupgrade apply this change:

-                        "hostname": "{}:{}".format(dc, 636),
+                        "hostname": f"{dc}:{636}",

but I'd expect f"{dc}:636"

graingert avatar Apr 19 '21 11:04 graingert

Also found this issue when upgrading a codebase with --py36-plus, using pyupgrade 2.29.0:

-BROKER_URL = "{redis}/{db}".format(redis=REDIS_URL, db=0)
+BROKER_URL = f"{REDIS_URL}/{0}"

adamantike avatar Oct 23 '21 01:10 adamantike

Different issue but possibly similar fix:

f"{repr(x)}"

Could be converted to:

f"{x!r}"

These happen to be common from "{0}".format(repr(x)) conversions.

henryiii avatar Dec 10 '21 17:12 henryiii

Different issues but also regarding f-strings and % formatting in --py36-plus. I was suggested to add to the existing issue:

# this is not changed
s = "Value is %s" % a

but I'd expect s = "Value is {a}"

And these are fixed by running twice pyupgrade --py36-plus

# this takes 2 iterations to get stable: percent -> .format() -> f-string
-s = "Value is %s" % (a, )
-s = "Value is %s" % (a)
-s = "Value is %s - %s" % (a, b)
+s = "Value is {}".format(a)
+s = "Value is {}".format(a)
+s = "Value is {} - {}".format(a, b)

I'd expect directly:

s = "Value is {a}"
+s = "Value is {a}"
+s = "Value is {a} - {b}"

mambelli avatar Nov 29 '22 14:11 mambelli

"different issue" then be a good open source citizen and don't comment on this old unrelated issue with off topic

asottile avatar Nov 29 '22 14:11 asottile