use-f-string

Encourages the use of f-string instead of %-formatting or .format() for high code quality and efficiency.

Following two cases not covered:

  1. arguments length greater than 30 characters: for better readability reason For example:

    1: this is the answer: %d” % (a_long_function_call() + b_another_long_function_call()) 2: f”this is the answer: {a_long_function_call() + b_another_long_function_call()}” 3: result = a_long_function_call() + b_another_long_function_call() f”this is the answer: {result}”

    Line 1 is more readable than line 2. Ideally, we’d like developers to manually fix this case to line 3

  2. only %s placeholders are linted against for now. We leave it as future work to support other placeholders. For example, %d raises TypeError for non-numeric objects, whereas f”{x:d}” raises ValueError. This discrepancy in the type of exception raised could potentially break the logic in the code where the exception is handled

Message

Do not use printf style formatting or .format(). Use f-string instead to be more readable and efficient.

References

Settings

SettingDescriptionTypeDefault
simple_expression_max_length Maximum expression length to autofix inline in an f-string. int 30

Valid examples

somebody='you'; f"Hey, {somebody}."
"hey"
"hey" + "there"
b"a type %s" % var

Invalid examples

"Hey, {somebody}.".format(somebody="you")
"%s" % "hi"

Suggested fix

f"{'hi'}"
"a name: %s" % name

Suggested fix

f"a name: {name}"
Show more
"an attribute %s ." % obj.attr

Suggested fix

f"an attribute {obj.attr} ."
r"raw string value=%s" % val

Suggested fix

fr"raw string value={val}"
"{%s}" % val

Suggested fix

f"{{{val}}}"
"{%s" % val

Suggested fix

f"{{{val}"
"The type of var: %s" % type(var)

Suggested fix

f"The type of var: {type(var)}"
"%s" % obj.this_is_a_very_long_expression(parameter)["a_very_long_key"]
"%s" % abcdefghijklmnopqrstuvwxyz1234567890

Suggested fix

f"{abcdefghijklmnopqrstuvwxyz1234567890}"
"type of var: %s, value of var: %s" % (type(var), var)

Suggested fix

f"type of var: {type(var)}, value of var: {var}"
'%s" double quote is used' % var

Suggested fix

f'{var}" double quote is used'
"var1: %s, var2: %s, var3: %s, var4: %s" % (class_object.attribute, dict_lookup["some_key"], some_module.some_function(), var4)

Suggested fix

f"var1: {class_object.attribute}, var2: {dict_lookup['some_key']}, var3: {some_module.some_function()}, var4: {var4}"
"a list: %s" % " ".join(var)

Suggested fix

f"a list: {' '.join(var)}"