pyupgrade
pyupgrade copied to clipboard
constant fold literals in f", .format and % formatting
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"))
It might also be good to hit the explicit str concat "the user" + repr(u"user") + "did a bad".
and %r
formatting
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"
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}"
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.
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}"
"different issue" then be a good open source citizen and don't comment on this old unrelated issue with off topic