Skip to content

Commit

Permalink
Enable ruff f-string/format rules
Browse files Browse the repository at this point in the history
  • Loading branch information
inducer committed Jul 29, 2024
1 parent 4702c41 commit b301c70
Show file tree
Hide file tree
Showing 54 changed files with 391 additions and 548 deletions.
3 changes: 1 addition & 2 deletions accounts/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -148,8 +148,7 @@ def default_fullname(first_name, last_name):
Returns the first_name plus the last_name, with a space in
between.
"""
return "{} {}".format(
verbose_blank(first_name), verbose_blank(last_name))
return f"{verbose_blank(first_name)} {verbose_blank(last_name)}"

from accounts.utils import relate_user_method_settings
format_method = relate_user_method_settings.custom_full_name_method
Expand Down
83 changes: 33 additions & 50 deletions accounts/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -81,10 +81,8 @@ def check_user_profile_mask_method(self):
except ImportError:
errors = [RelateCriticalCheckMessage(
msg=(
"%(location)s: `%(method)s` failed to be imported. "
% {"location": RELATE_USER_PROFILE_MASK_METHOD,
"method": custom_user_profile_mask_method
}
f"{RELATE_USER_PROFILE_MASK_METHOD}: "
f"`{custom_user_profile_mask_method}` failed to be imported. "
),
id="relate_user_profile_mask_method.E001"
)]
Expand All @@ -94,10 +92,8 @@ def check_user_profile_mask_method(self):
if not callable(custom_user_profile_mask_method):
errors.append(RelateCriticalCheckMessage(
msg=(
"%(location)s: `%(method)s` is not a callable. "
% {"location": RELATE_USER_PROFILE_MASK_METHOD,
"method": custom_user_profile_mask_method
}
f"{RELATE_USER_PROFILE_MASK_METHOD}: "
f"`{custom_user_profile_mask_method}` is not a callable."
),
id="relate_user_profile_mask_method.E002"
))
Expand Down Expand Up @@ -152,8 +148,8 @@ def check_email_appellation_priority_list(self):
INSTANCE_ERROR_PATTERN
% {"location": RELATE_EMAIL_APPELLATION_PRIORITY_LIST,
"types": "list or tuple"},
"default value '%s' will be used"
% repr(DEFAULT_EMAIL_APPELLATION_PRIORITY_LIST))),
f"default value '{DEFAULT_EMAIL_APPELLATION_PRIORITY_LIST!r}' "
"will be used")),
id="relate_email_appellation_priority_list.W001"))
return errors

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

if not_supported_appels:
errors.append(Warning(
msg=("%(location)s: not supported email appelation(s) found "
"and will be ignored: %(not_supported_appelds)s. "
"%(actual)s will be used as "
"relate_email_appellation_priority_list."
% {"location": RELATE_EMAIL_APPELLATION_PRIORITY_LIST,
"not_supported_appelds": ", ".join(not_supported_appels),
"actual": repr(priority_list)}),
msg=("{location}: not supported email appelation(s) found "
"and will be ignored: {not_supported_appelds}. "
"{actual} will be used as "
"relate_email_appellation_priority_list.".format(
location=RELATE_EMAIL_APPELLATION_PRIORITY_LIST,
not_supported_appelds=", ".join(not_supported_appels),
actual=repr(priority_list),
)),
id="relate_email_appellation_priority_list.W002"))
return errors

Expand All @@ -206,11 +203,10 @@ def check_custom_full_name_method(self):
except ImportError:
errors = [Warning(
msg=(
"%(location)s: `%(method)s` failed to be imported, "
f"{RELATE_USER_FULL_NAME_FORMAT_METHOD}: "
f"`{relate_user_full_name_format_method}` "
"failed to be imported, "
"default format method will be used."
% {"location": RELATE_USER_FULL_NAME_FORMAT_METHOD,
"method": relate_user_full_name_format_method
}
),
id="relate_user_full_name_format_method.W001"
)]
Expand All @@ -220,11 +216,9 @@ def check_custom_full_name_method(self):
if not callable(relate_user_full_name_format_method):
errors.append(Warning(
msg=(
"%(location)s: `%(method)s` is not a callable, "
f"{RELATE_USER_FULL_NAME_FORMAT_METHOD}: "
f"`{relate_user_full_name_format_method}` is not a callable, "
"default format method will be used."
% {"location": RELATE_USER_FULL_NAME_FORMAT_METHOD,
"method": relate_user_full_name_format_method
}
),
id="relate_user_full_name_format_method.W002"
))
Expand All @@ -237,17 +231,13 @@ def check_custom_full_name_method(self):
from traceback import format_exc
errors.append(Warning(
msg=(
"%(location)s: `%(method)s` called with '"
f"{RELATE_USER_FULL_NAME_FORMAT_METHOD}: "
f"`{relate_user_full_name_format_method}` called with '"
"args 'first_name', 'last_name' failed with"
"exception below:\n"
"%(err_type)s: %(err_str)s\n"
"%(format_exc)s\n\n"
f"{type(e).__name__}: {e!s}\n"
f"{format_exc()}\n\n"
"Default format method will be used."
% {"location": RELATE_USER_FULL_NAME_FORMAT_METHOD,
"method": relate_user_full_name_format_method,
"err_type": type(e).__name__,
"err_str": str(e),
"format_exc": format_exc()}
),
id="relate_user_full_name_format_method.W003"
))
Expand All @@ -258,17 +248,14 @@ def check_custom_full_name_method(self):
if not isinstance(returned_name, str):
unexpected_return_value = type(returned_name).__name__
elif not returned_name.strip():
unexpected_return_value = "empty string %s" % returned_name
unexpected_return_value = f"empty string {returned_name}"
if unexpected_return_value:
errors.append(Warning(
msg=("%(location)s: `%(method)s` is expected to "
"return a non-empty string, got `%(result)s`, "
"default format method will be used."
% {
"location": RELATE_USER_FULL_NAME_FORMAT_METHOD,
"method": relate_user_full_name_format_method,
"result": unexpected_return_value,
}),
msg=(f"{RELATE_USER_FULL_NAME_FORMAT_METHOD}: "
f"`{relate_user_full_name_format_method}` is expected to "
"return a non-empty string, "
f"got `{unexpected_return_value}`, "
"default format method will be used."),
id="relate_user_full_name_format_method.W004"
))
else:
Expand All @@ -277,15 +264,11 @@ def check_custom_full_name_method(self):
"last_name2"))
if returned_name == returned_name2:
errors.append(Warning(
msg=("%(location)s: `%(method)s` is expected to "
msg=(f"{RELATE_USER_FULL_NAME_FORMAT_METHOD}: "
f"`{relate_user_full_name_format_method}` "
"is expected to "
"return different value with different "
"input, default format method will be used."
% {
"location":
RELATE_USER_FULL_NAME_FORMAT_METHOD,
"method":
relate_user_full_name_format_method
}),
"input, default format method will be used."),
id="relate_user_full_name_format_method.W005"
))

Expand Down
14 changes: 6 additions & 8 deletions course/admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -190,7 +190,7 @@ class EventAdmin(admin.ModelAdmin):
def __unicode__(self): # pragma: no cover # not used
return "{}{} in {}".format(
self.kind,
" (%s)" % str(self.ordinal) if self.ordinal is not None else "",
f" ({self.ordinal!s})" if self.ordinal is not None else "",
self.course)

__str__ = __unicode__
Expand Down Expand Up @@ -319,9 +319,8 @@ def get_user(self, obj):
"</a>"
) % {
"link": reverse(
"admin:%s_change"
% settings.AUTH_USER_MODEL.replace(".", "_")
.lower(),
"admin:{}_change".format(
settings.AUTH_USER_MODEL.replace(".", "_").lower()),
args=(obj.user.id,)),
"user_fullname": obj.user.get_full_name(
force_verbose_blank=True),
Expand Down Expand Up @@ -611,10 +610,9 @@ def get_page_id(self, obj):
obj.page_data.group_id,
obj.page_data.page_id)
else:
return "{}/{} ({})".format(
obj.page_data.group_id,
obj.page_data.page_id,
obj.page_data.page_ordinal)
return (
f"{obj.page_data.group_id}/{obj.page_data.page_id} "
f"({obj.page_data.page_ordinal})")

@admin.display(
description=_("Owner"),
Expand Down
22 changes: 6 additions & 16 deletions course/auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -183,20 +183,11 @@ class UserSearchWidget(ModelSelect2Widget):
def label_from_instance(self, u):
if u.first_name and u.last_name:
return (
"%(full_name)s (%(username)s - %(email)s)"
% {
"full_name": u.get_full_name(),
"email": u.email,
"username": u.username
})
f"{u.get_full_name()} ({u.username} - {u.email})")
else:
# for users with "None" fullname
return (
"%(username)s (%(email)s)"
% {
"email": u.email,
"username": u.username
})
f"{u.username} ({u.email})")


class ImpersonateForm(StyledForm):
Expand Down Expand Up @@ -512,7 +503,7 @@ def sign_up(request):

from django.core.mail import EmailMessage
msg = EmailMessage(
string_concat("[%s] " % _(get_site_name()),
string_concat(f"[{_(get_site_name())}] ",
_("Verify your email")),
message,
getattr(settings, "NO_REPLY_EMAIL_FROM",
Expand Down Expand Up @@ -651,7 +642,7 @@ def reset_password(request, field="email"):
})
from django.core.mail import EmailMessage
msg = EmailMessage(
string_concat("[%s] " % _(get_site_name()),
string_concat(f"[{_(get_site_name())}] ",
_("Password reset")),
message,
getattr(settings, "NO_REPLY_EMAIL_FROM",
Expand Down Expand Up @@ -966,8 +957,7 @@ def __init__(self, *args, **kwargs):
self.helper.add_input(
Button("signout", _("Sign out"), css_class="btn btn-danger",
onclick=(
"window.location.href='%s'"
% reverse("relate-logout"))))
"window.location.href='{}'".format(reverse("relate-logout")))))

# }}}

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

Expand Down
6 changes: 3 additions & 3 deletions course/calendar.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,14 +50,14 @@ def __init__(self, data_list, name, *args, **kwargs):
super().__init__(*args, **kwargs)
self._name = name
self._list = data_list
self.attrs.update({"list": "list__%s" % self._name})
self.attrs.update({"list": f"list__{self._name}"})

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

return mark_safe(text_html + data_list)
Expand Down
21 changes: 10 additions & 11 deletions course/content.py
Original file line number Diff line number Diff line change
Expand Up @@ -1139,7 +1139,7 @@ def handle_starttag(self, tag, attrs):
_attr_to_string(k, v) for k, v in attrs.items())))

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

def handle_startendtag(self, tag, attrs):
attrs = dict(attrs)
Expand All @@ -1152,23 +1152,23 @@ def handle_data(self, data):
self.out_file.write(data)

def handle_entityref(self, name):
self.out_file.write("&%s;" % name)
self.out_file.write(f"&{name};")

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

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

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

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

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


class PreserveFragment:
Expand Down Expand Up @@ -1686,7 +1686,7 @@ def apply_postprocs(dtime: datetime.datetime) -> datetime.datetime:

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

if course is None:
return now()
Expand Down Expand Up @@ -1883,7 +1883,7 @@ def get_flow_desc(
"""

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

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

return True
Expand Down
6 changes: 3 additions & 3 deletions course/enrollment.py
Original file line number Diff line number Diff line change
Expand Up @@ -232,7 +232,7 @@ def email_suffix_matches(email: str, suffix: str) -> bool:
if suffix.startswith("@"):
return email.endswith(suffix)
else:
return email.endswith("@%s" % suffix) or email.endswith(".%s" % suffix)
return email.endswith(f"@{suffix}") or email.endswith(f".{suffix}")

if (preapproval is None
and course.enrollment_required_email_suffix
Expand Down Expand Up @@ -484,15 +484,15 @@ def create_preapprovals(pctx):
if not ln:
continue

preapp_filter_kwargs = {"%s__iexact" % preapp_type: ln}
preapp_filter_kwargs = {f"{preapp_type}__iexact": ln}

try:
ParticipationPreapproval.objects.get(
course=pctx.course, **preapp_filter_kwargs)
except ParticipationPreapproval.DoesNotExist:

# approve if ln is requesting enrollment
user_filter_kwargs = {"user__%s__iexact" % preapp_type: ln}
user_filter_kwargs = {f"user__{preapp_type}__iexact": ln}
if preapp_type == "institutional_id":
if pctx.course.preapproval_require_verified_inst_id:
user_filter_kwargs.update(
Expand Down
Loading

0 comments on commit b301c70

Please sign in to comment.