Skip to content

Commit 8a4ff27

Browse files
committed
Enable ruff f-string/format rules
1 parent 4702c41 commit 8a4ff27

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

54 files changed

+391
-548
lines changed

accounts/models.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -148,8 +148,7 @@ def default_fullname(first_name, last_name):
148148
Returns the first_name plus the last_name, with a space in
149149
between.
150150
"""
151-
return "{} {}".format(
152-
verbose_blank(first_name), verbose_blank(last_name))
151+
return f"{verbose_blank(first_name)} {verbose_blank(last_name)}"
153152

154153
from accounts.utils import relate_user_method_settings
155154
format_method = relate_user_method_settings.custom_full_name_method

accounts/utils.py

Lines changed: 33 additions & 50 deletions
Original file line numberDiff line numberDiff line change
@@ -81,10 +81,8 @@ def check_user_profile_mask_method(self):
8181
except ImportError:
8282
errors = [RelateCriticalCheckMessage(
8383
msg=(
84-
"%(location)s: `%(method)s` failed to be imported. "
85-
% {"location": RELATE_USER_PROFILE_MASK_METHOD,
86-
"method": custom_user_profile_mask_method
87-
}
84+
f"{RELATE_USER_PROFILE_MASK_METHOD}: "
85+
f"`{custom_user_profile_mask_method}` failed to be imported. "
8886
),
8987
id="relate_user_profile_mask_method.E001"
9088
)]
@@ -94,10 +92,8 @@ def check_user_profile_mask_method(self):
9492
if not callable(custom_user_profile_mask_method):
9593
errors.append(RelateCriticalCheckMessage(
9694
msg=(
97-
"%(location)s: `%(method)s` is not a callable. "
98-
% {"location": RELATE_USER_PROFILE_MASK_METHOD,
99-
"method": custom_user_profile_mask_method
100-
}
95+
f"{RELATE_USER_PROFILE_MASK_METHOD}: "
96+
f"`{custom_user_profile_mask_method}` is not a callable."
10197
),
10298
id="relate_user_profile_mask_method.E002"
10399
))
@@ -152,8 +148,8 @@ def check_email_appellation_priority_list(self):
152148
INSTANCE_ERROR_PATTERN
153149
% {"location": RELATE_EMAIL_APPELLATION_PRIORITY_LIST,
154150
"types": "list or tuple"},
155-
"default value '%s' will be used"
156-
% repr(DEFAULT_EMAIL_APPELLATION_PRIORITY_LIST))),
151+
f"default value '{DEFAULT_EMAIL_APPELLATION_PRIORITY_LIST!r}' "
152+
"will be used")),
157153
id="relate_email_appellation_priority_list.W001"))
158154
return errors
159155

@@ -178,13 +174,14 @@ def check_email_appellation_priority_list(self):
178174

179175
if not_supported_appels:
180176
errors.append(Warning(
181-
msg=("%(location)s: not supported email appelation(s) found "
182-
"and will be ignored: %(not_supported_appelds)s. "
183-
"%(actual)s will be used as "
184-
"relate_email_appellation_priority_list."
185-
% {"location": RELATE_EMAIL_APPELLATION_PRIORITY_LIST,
186-
"not_supported_appelds": ", ".join(not_supported_appels),
187-
"actual": repr(priority_list)}),
177+
msg=("{location}: not supported email appelation(s) found "
178+
"and will be ignored: {not_supported_appelds}. "
179+
"{actual} will be used as "
180+
"relate_email_appellation_priority_list.".format(
181+
location=RELATE_EMAIL_APPELLATION_PRIORITY_LIST,
182+
not_supported_appelds=", ".join(not_supported_appels),
183+
actual=repr(priority_list),
184+
)),
188185
id="relate_email_appellation_priority_list.W002"))
189186
return errors
190187

@@ -206,11 +203,10 @@ def check_custom_full_name_method(self):
206203
except ImportError:
207204
errors = [Warning(
208205
msg=(
209-
"%(location)s: `%(method)s` failed to be imported, "
206+
f"{RELATE_USER_FULL_NAME_FORMAT_METHOD}: "
207+
f"`{relate_user_full_name_format_method}` "
208+
"failed to be imported, "
210209
"default format method will be used."
211-
% {"location": RELATE_USER_FULL_NAME_FORMAT_METHOD,
212-
"method": relate_user_full_name_format_method
213-
}
214210
),
215211
id="relate_user_full_name_format_method.W001"
216212
)]
@@ -220,11 +216,9 @@ def check_custom_full_name_method(self):
220216
if not callable(relate_user_full_name_format_method):
221217
errors.append(Warning(
222218
msg=(
223-
"%(location)s: `%(method)s` is not a callable, "
219+
f"{RELATE_USER_FULL_NAME_FORMAT_METHOD}: "
220+
f"`{relate_user_full_name_format_method}` is not a callable, "
224221
"default format method will be used."
225-
% {"location": RELATE_USER_FULL_NAME_FORMAT_METHOD,
226-
"method": relate_user_full_name_format_method
227-
}
228222
),
229223
id="relate_user_full_name_format_method.W002"
230224
))
@@ -237,17 +231,13 @@ def check_custom_full_name_method(self):
237231
from traceback import format_exc
238232
errors.append(Warning(
239233
msg=(
240-
"%(location)s: `%(method)s` called with '"
234+
f"{RELATE_USER_FULL_NAME_FORMAT_METHOD}: "
235+
f"`{relate_user_full_name_format_method}` called with '"
241236
"args 'first_name', 'last_name' failed with"
242237
"exception below:\n"
243-
"%(err_type)s: %(err_str)s\n"
244-
"%(format_exc)s\n\n"
238+
f"{type(e).__name__}: {e!s}\n"
239+
f"{format_exc()}\n\n"
245240
"Default format method will be used."
246-
% {"location": RELATE_USER_FULL_NAME_FORMAT_METHOD,
247-
"method": relate_user_full_name_format_method,
248-
"err_type": type(e).__name__,
249-
"err_str": str(e),
250-
"format_exc": format_exc()}
251241
),
252242
id="relate_user_full_name_format_method.W003"
253243
))
@@ -258,17 +248,14 @@ def check_custom_full_name_method(self):
258248
if not isinstance(returned_name, str):
259249
unexpected_return_value = type(returned_name).__name__
260250
elif not returned_name.strip():
261-
unexpected_return_value = "empty string %s" % returned_name
251+
unexpected_return_value = f"empty string {returned_name}"
262252
if unexpected_return_value:
263253
errors.append(Warning(
264-
msg=("%(location)s: `%(method)s` is expected to "
265-
"return a non-empty string, got `%(result)s`, "
266-
"default format method will be used."
267-
% {
268-
"location": RELATE_USER_FULL_NAME_FORMAT_METHOD,
269-
"method": relate_user_full_name_format_method,
270-
"result": unexpected_return_value,
271-
}),
254+
msg=(f"{RELATE_USER_FULL_NAME_FORMAT_METHOD}: "
255+
f"`{relate_user_full_name_format_method}` is expected to "
256+
"return a non-empty string, "
257+
f"got `{unexpected_return_value}`, "
258+
"default format method will be used."),
272259
id="relate_user_full_name_format_method.W004"
273260
))
274261
else:
@@ -277,15 +264,11 @@ def check_custom_full_name_method(self):
277264
"last_name2"))
278265
if returned_name == returned_name2:
279266
errors.append(Warning(
280-
msg=("%(location)s: `%(method)s` is expected to "
267+
msg=(f"{RELATE_USER_FULL_NAME_FORMAT_METHOD}: "
268+
f"`{relate_user_full_name_format_method}` "
269+
"is expected to "
281270
"return different value with different "
282-
"input, default format method will be used."
283-
% {
284-
"location":
285-
RELATE_USER_FULL_NAME_FORMAT_METHOD,
286-
"method":
287-
relate_user_full_name_format_method
288-
}),
271+
"input, default format method will be used."),
289272
id="relate_user_full_name_format_method.W005"
290273
))
291274

course/admin.py

Lines changed: 6 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -190,7 +190,7 @@ class EventAdmin(admin.ModelAdmin):
190190
def __unicode__(self): # pragma: no cover # not used
191191
return "{}{} in {}".format(
192192
self.kind,
193-
" (%s)" % str(self.ordinal) if self.ordinal is not None else "",
193+
f" ({self.ordinal!s})" if self.ordinal is not None else "",
194194
self.course)
195195

196196
__str__ = __unicode__
@@ -319,9 +319,8 @@ def get_user(self, obj):
319319
"</a>"
320320
) % {
321321
"link": reverse(
322-
"admin:%s_change"
323-
% settings.AUTH_USER_MODEL.replace(".", "_")
324-
.lower(),
322+
"admin:{}_change".format(
323+
settings.AUTH_USER_MODEL.replace(".", "_").lower()),
325324
args=(obj.user.id,)),
326325
"user_fullname": obj.user.get_full_name(
327326
force_verbose_blank=True),
@@ -611,10 +610,9 @@ def get_page_id(self, obj):
611610
obj.page_data.group_id,
612611
obj.page_data.page_id)
613612
else:
614-
return "{}/{} ({})".format(
615-
obj.page_data.group_id,
616-
obj.page_data.page_id,
617-
obj.page_data.page_ordinal)
613+
return (
614+
f"{obj.page_data.group_id}/{obj.page_data.page_id} "
615+
f"({obj.page_data.page_ordinal})")
618616

619617
@admin.display(
620618
description=_("Owner"),

course/auth.py

Lines changed: 6 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -183,20 +183,11 @@ class UserSearchWidget(ModelSelect2Widget):
183183
def label_from_instance(self, u):
184184
if u.first_name and u.last_name:
185185
return (
186-
"%(full_name)s (%(username)s - %(email)s)"
187-
% {
188-
"full_name": u.get_full_name(),
189-
"email": u.email,
190-
"username": u.username
191-
})
186+
f"{u.get_full_name()} ({u.username} - {u.email})")
192187
else:
193188
# for users with "None" fullname
194189
return (
195-
"%(username)s (%(email)s)"
196-
% {
197-
"email": u.email,
198-
"username": u.username
199-
})
190+
f"{u.username} ({u.email})")
200191

201192

202193
class ImpersonateForm(StyledForm):
@@ -512,7 +503,7 @@ def sign_up(request):
512503

513504
from django.core.mail import EmailMessage
514505
msg = EmailMessage(
515-
string_concat("[%s] " % _(get_site_name()),
506+
string_concat(f"[{_(get_site_name())}] ",
516507
_("Verify your email")),
517508
message,
518509
getattr(settings, "NO_REPLY_EMAIL_FROM",
@@ -651,7 +642,7 @@ def reset_password(request, field="email"):
651642
})
652643
from django.core.mail import EmailMessage
653644
msg = EmailMessage(
654-
string_concat("[%s] " % _(get_site_name()),
645+
string_concat(f"[{_(get_site_name())}] ",
655646
_("Password reset")),
656647
message,
657648
getattr(settings, "NO_REPLY_EMAIL_FROM",
@@ -966,8 +957,7 @@ def __init__(self, *args, **kwargs):
966957
self.helper.add_input(
967958
Button("signout", _("Sign out"), css_class="btn btn-danger",
968959
onclick=(
969-
"window.location.href='%s'"
970-
% reverse("relate-logout"))))
960+
"window.location.href='{}'".format(reverse("relate-logout")))))
971961

972962
# }}}
973963

@@ -1348,7 +1338,7 @@ def auth_course_with_token(method, func, request,
13481338
realm = _(f"Relate direct git access for {course_identifier}")
13491339
response = http.HttpResponse("Forbidden: " + str(e),
13501340
content_type="text/plain")
1351-
response["WWW-Authenticate"] = 'Basic realm="%s"' % (realm)
1341+
response["WWW-Authenticate"] = f'Basic realm="{realm}"'
13521342
response.status_code = 401
13531343
return response
13541344

course/calendar.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -50,14 +50,14 @@ def __init__(self, data_list, name, *args, **kwargs):
5050
super().__init__(*args, **kwargs)
5151
self._name = name
5252
self._list = data_list
53-
self.attrs.update({"list": "list__%s" % self._name})
53+
self.attrs.update({"list": f"list__{self._name}"})
5454

5555
def render(self, name, value, attrs=None, renderer=None):
5656
text_html = super().render(
5757
name, value, attrs=attrs, renderer=renderer)
58-
data_list = '<datalist id="list__%s">' % self._name
58+
data_list = f'<datalist id="list__{self._name}">'
5959
for item in self._list:
60-
data_list += '<option value="{}">{}</option>'.format(item[0], item[1])
60+
data_list += f'<option value="{item[0]}">{item[1]}</option>'
6161
data_list += "</datalist>"
6262

6363
return mark_safe(text_html + data_list)

course/content.py

Lines changed: 10 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1139,7 +1139,7 @@ def handle_starttag(self, tag, attrs):
11391139
_attr_to_string(k, v) for k, v in attrs.items())))
11401140

11411141
def handle_endtag(self, tag):
1142-
self.out_file.write("</%s>" % tag)
1142+
self.out_file.write(f"</{tag}>")
11431143

11441144
def handle_startendtag(self, tag, attrs):
11451145
attrs = dict(attrs)
@@ -1152,23 +1152,23 @@ def handle_data(self, data):
11521152
self.out_file.write(data)
11531153

11541154
def handle_entityref(self, name):
1155-
self.out_file.write("&%s;" % name)
1155+
self.out_file.write(f"&{name};")
11561156

11571157
def handle_charref(self, name):
1158-
self.out_file.write("&#%s;" % name)
1158+
self.out_file.write(f"&#{name};")
11591159

11601160
def handle_comment(self, data):
1161-
self.out_file.write("<!--%s-->" % data)
1161+
self.out_file.write(f"<!--{data}-->")
11621162

11631163
def handle_decl(self, decl):
1164-
self.out_file.write("<!%s>" % decl)
1164+
self.out_file.write(f"<!{decl}>")
11651165

11661166
def handle_pi(self, data):
11671167
raise NotImplementedError(
11681168
_("I have no idea what a processing instruction is."))
11691169

11701170
def unknown_decl(self, data):
1171-
self.out_file.write("<![%s]>" % data)
1171+
self.out_file.write(f"<![{data}]>")
11721172

11731173

11741174
class PreserveFragment:
@@ -1686,7 +1686,7 @@ def apply_postprocs(dtime: datetime.datetime) -> datetime.datetime:
16861686

16871687
if vctx is not None:
16881688
from course.validation import validate_identifier
1689-
validate_identifier(vctx, "%s: event kind" % location, event_kind)
1689+
validate_identifier(vctx, f"{location}: event kind", event_kind)
16901690

16911691
if course is None:
16921692
return now()
@@ -1883,7 +1883,7 @@ def get_flow_desc(
18831883
"""
18841884

18851885
# FIXME: extension should be case-insensitive
1886-
flow_desc = get_yaml_from_repo(repo, "flows/%s.yml" % flow_id, commit_sha,
1886+
flow_desc = get_yaml_from_repo(repo, f"flows/{flow_id}.yml", commit_sha,
18871887
tolerate_tabs=tolerate_tabs)
18881888

18891889
flow_desc = normalize_flow_desc(flow_desc)
@@ -1995,9 +1995,8 @@ def is_commit_sha_valid(repo: Repo_ish, commit_sha: str) -> bool:
19951995
except KeyError:
19961996
if raise_on_nonexistent_preview_commit:
19971997
raise CourseCommitSHADoesNotExist(
1998-
_("Preview revision '%s' does not exist--"
1999-
"showing active course content instead."
2000-
% commit_sha))
1998+
_("Preview revision '{}' does not exist--"
1999+
"showing active course content instead.").format(commit_sha))
20012000
return False
20022001

20032002
return True

course/enrollment.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -232,7 +232,7 @@ def email_suffix_matches(email: str, suffix: str) -> bool:
232232
if suffix.startswith("@"):
233233
return email.endswith(suffix)
234234
else:
235-
return email.endswith("@%s" % suffix) or email.endswith(".%s" % suffix)
235+
return email.endswith(f"@{suffix}") or email.endswith(f".{suffix}")
236236

237237
if (preapproval is None
238238
and course.enrollment_required_email_suffix
@@ -484,15 +484,15 @@ def create_preapprovals(pctx):
484484
if not ln:
485485
continue
486486

487-
preapp_filter_kwargs = {"%s__iexact" % preapp_type: ln}
487+
preapp_filter_kwargs = {f"{preapp_type}__iexact": ln}
488488

489489
try:
490490
ParticipationPreapproval.objects.get(
491491
course=pctx.course, **preapp_filter_kwargs)
492492
except ParticipationPreapproval.DoesNotExist:
493493

494494
# approve if ln is requesting enrollment
495-
user_filter_kwargs = {"user__%s__iexact" % preapp_type: ln}
495+
user_filter_kwargs = {f"user__{preapp_type}__iexact": ln}
496496
if preapp_type == "institutional_id":
497497
if pctx.course.preapproval_require_verified_inst_id:
498498
user_filter_kwargs.update(

0 commit comments

Comments
 (0)