Skip to content

Commit

Permalink
Satisfy ruff's demand for f-strings
Browse files Browse the repository at this point in the history
  • Loading branch information
philgyford committed Aug 13, 2024
1 parent dd4ef8c commit 69cb53b
Show file tree
Hide file tree
Showing 32 changed files with 138 additions and 140 deletions.
4 changes: 2 additions & 2 deletions ditto/core/apps.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ def enabled(self):

def is_installed(self, app_name):
"Is this Ditto app installed?"
return apps.is_installed("ditto.%s" % app_name)
return apps.is_installed(f"ditto.{app_name}")

def is_enabled(self, app_name):
"""Determine if a particular Ditto app is installed and enabled.
Expand All @@ -52,7 +52,7 @@ def is_enabled(self, app_name):
Doesn't offer much over apps.is_installed() yet, but would let us add other
conditions in future, like being able to enable/disable installed apps.
"""
return apps.is_installed("ditto.%s" % app_name)
return apps.is_installed(f"ditto.{app_name}")


ditto_apps = Apps()
2 changes: 1 addition & 1 deletion ditto/core/management/commands/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ def output_results(self, results, verbosity=1):
return

for result in results:
prefix = "%s: " % result["account"] if "account" in result else ""
prefix = f"{result['account']}: " if "account" in result else ""
if "fetched" in result:
noun = (
self.singular_noun if result["fetched"] == 1 else self.plural_noun
Expand Down
13 changes: 6 additions & 7 deletions ditto/core/templatetags/ditto_core.py
Original file line number Diff line number Diff line change
Expand Up @@ -88,19 +88,18 @@ def display_time(dt, *, link_to_day=False, granularity=0, case=None):
"""

if granularity == 8:
visible_time = "circa %s" % dt.strftime(app_settings.CORE_DATE_YEAR_FORMAT)
year = dt.strftime(app_settings.CORE_DATE_YEAR_FORMAT)
visible_time = f"circa {year}"
stamp = dt.strftime("%Y")

elif granularity == 6:
visible_time = "sometime in %s" % dt.strftime(
app_settings.CORE_DATE_YEAR_FORMAT
)
year = dt.strftime(app_settings.CORE_DATE_YEAR_FORMAT)
visible_time = f"sometime in {year}"
stamp = dt.strftime("%Y")

elif granularity == 4:
visible_time = "sometime in %s" % dt.strftime(
app_settings.CORE_DATE_YEAR_MONTH_FORMAT
)
year_month = dt.strftime(app_settings.CORE_DATE_YEAR_MONTH_FORMAT)
visible_time = f"sometime in {year_month}"
stamp = dt.strftime("%Y-%m")

else:
Expand Down
8 changes: 6 additions & 2 deletions ditto/core/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -246,7 +246,8 @@ def set_app_and_variety(self, **kwargs):
)
raise Http404(msg)
elif app_slug:
raise Http404("'%s' is not a valid app slug." % app_slug)
msg = f"'{app_slug}' is not a valid app slug."
raise Http404(msg)

self.app_slug = app_slug
self.variety_slug = variety_slug
Expand Down Expand Up @@ -558,7 +559,10 @@ def get_variety_counts(self):
date_field = self.get_date_field_for_app_variety(app_name, variety_name)
qs = self.get_queryset_for_app_variety(app_name, variety_name)
qs = qs.filter(
**{"%s__gte" % date_field: since, "%s__lt" % date_field: until}
**{
f"{date_field}__gte": since,
f"{date_field}__lt": until,
}
)
paginate_by = self.get_paginate_by(qs)
# if not allow_future:
Expand Down
4 changes: 1 addition & 3 deletions ditto/flickr/admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -133,9 +133,7 @@ class UserAdmin(admin.ModelAdmin):
)

def show_avatar(self, instance):
return mark_safe(
'<img src="%s" width="24" height="24" />' % (instance.avatar_url)
)
return mark_safe(f'<img src="{instance.avatar_url}" width="24" height="24" />')

show_avatar.short_description = ""

Expand Down
8 changes: 4 additions & 4 deletions ditto/flickr/fetch/fetchers.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ def __init__(self, account):
if account.user:
self.return_value["account"] = account.user.username
elif account.pk:
self.return_value["account"] = "Account: %s" % str(account)
self.return_value["account"] = f"Account: {account}"
else:
self.return_value["account"] = "Unsaved Account"
else:
Expand Down Expand Up @@ -115,14 +115,14 @@ def _fetch_page(self, **kwargs):
self._call_api(**kwargs)
except FetchError as e:
self.return_value["success"] = False
self.return_value["messages"] = ["Error when calling Flickr API: %s" % e]
self.return_value["messages"] = [f"Error when calling Flickr API: {e}"]
return

try:
self._fetch_extra()
except FetchError as e:
self.return_value["success"] = False
self.return_value["messages"] = ["Error when fetching extra data: %s" % e]
self.return_value["messages"] = [f"Error when fetching extra data: {e}"]
return

try:
Expand All @@ -131,7 +131,7 @@ def _fetch_page(self, **kwargs):
self.results = []
except FetchError as e:
self.return_value["success"] = False
self.return_value["messages"] = ["Error when saving data: %s" % e]
self.return_value["messages"] = [f"Error when saving data: {e}"]
return

return
Expand Down
8 changes: 4 additions & 4 deletions ditto/flickr/management/commands/fetch_flickr_account_user.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ def handle(self, *args, **options):
try:
account = Account.objects.get(id=options["id"])
except Account.DoesNotExist:
self.stderr.write("No Account found with an id of '%s'" % options["id"])
self.stderr.write(f"No Account found with an id of '{options['id']}'")

if account:
# Then get the ID of the Flicker user for this Account's API creds.
Expand All @@ -53,7 +53,7 @@ def handle(self, *args, **options):
account.save()
if options.get("verbosity", 1) > 0:
self.stdout.write(
"Fetched and saved user '%s'" % result["user"]["name"]
f"Fetched and saved user '{result['user']['name']}'"
)
else:
if options.get("verbosity", 1) > 0:
Expand All @@ -65,6 +65,6 @@ def handle(self, *args, **options):
else:
if options.get("verbosity", 1) > 0:
self.stderr.write(
"Failed to fetch a Flickr ID for this Account: %s"
% id_result["messages"][0]
"Failed to fetch a Flickr ID for this Account: "
f"{id_result["messages"][0]}"
)
11 changes: 5 additions & 6 deletions ditto/flickr/templatetags/ditto_flickr.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,9 +40,8 @@ def day_photos(date, nsid=None, time="post_time"):
time -- A string, either 'post_time' (default) or 'taken_time'.
"""
if time not in ["post_time", "taken_time"]:
raise ValueError(
"`time` must be either 'post_time' or " "'taken_time', not '%s'." % time
)
msg = f"`time` must be either 'post_time' or 'taken_time', not '{time}'."
raise ValueError(msg)

start = datetime.combine(date, datetime_time.min).replace(tzinfo=timezone.utc)
end = datetime.combine(date, datetime_time.max).replace(tzinfo=timezone.utc)
Expand Down Expand Up @@ -107,10 +106,10 @@ def annual_photo_counts(nsid=None, count_by="post_time"):
"""

if count_by not in ["post_time", "taken_time"]:
raise ValueError(
"`count_by` must be either 'post_time' or "
"'taken_time', not '%s'." % count_by
msg = (
f"`count_by` must be either 'post_time' or 'taken_time', not '{count_by}'."
)
raise ValueError(msg)

qs = Photo.public_photo_objects

Expand Down
9 changes: 4 additions & 5 deletions ditto/lastfm/fetch.py
Original file line number Diff line number Diff line change
Expand Up @@ -81,16 +81,15 @@ def fetch(self, fetch_type="recent", days=None):
if self.account and self.account.is_active is False:
self.return_value["success"] = False
self.return_value["messages"] = [
"The Account %s is currently marked as inactive."
% self.account.username
f"The Account {self.account.username} is currently marked as inactive."
]
return self.return_value

valid_fetch_types = ["all", "days", "recent"]
if fetch_type not in valid_fetch_types:
raise ValueError(
"fetch_type should be one of %s" % ", ".join(valid_fetch_types)
)
types_str = ", ".join(valid_fetch_types)
msg = f"fetch_type should be one of {types_str}"
raise ValueError(msg)

if fetch_type == "days":
try:
Expand Down
25 changes: 12 additions & 13 deletions ditto/lastfm/managers.py
Original file line number Diff line number Diff line change
Expand Up @@ -79,31 +79,30 @@ def with_scrobble_counts(self, **kwargs):
raise ValueError(msg)

if account is not None and account.__class__.__name__ != "Account":
raise TypeError(
"account must be an Account instance, " "not a %s" % type(account)
)
msg = f"account must be an Account instance, not a {type(account)}"
raise TypeError(msg)

if album is not None and album.__class__.__name__ != "Album":
raise TypeError(
"album must be an Album instance, " "not a %s" % type(album)
)
msg = f"album must be an Album instance, not a {type(album)}"
raise TypeError(msg)

if artist is not None and artist.__class__.__name__ != "Artist":
raise TypeError(
"artist must be an Artist instance, " "not a %s" % type(account)
)
msg = f"artist must be an Artist instance, not a {type(account)}"
raise TypeError(msg)

if min_post_time is not None and type(min_post_time) is not datetime:
raise TypeError(
msg = (
"min_post_time must be a datetime.datetime, "
"not a %s" % type(min_post_time)
f"not a {type(min_post_time)}"
)
raise TypeError(msg)

if max_post_time is not None and type(max_post_time) is not datetime:
raise TypeError(
msg = (
"max_post_time must be a datetime.datetime, "
"not a %s" % type(max_post_time)
f"not a {type(max_post_time)}"
)
raise TypeError(msg)

filter_kwargs = {}

Expand Down
40 changes: 21 additions & 19 deletions ditto/lastfm/templatetags/ditto_lastfm.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,8 @@ def check_top_kwargs(**kwargs):
period = kwargs["period"]

if account is not None and not isinstance(account, Account):
raise TypeError(
"`account` must be an Account instance, " "not a %s" % type(account)
)
msg = f"`account` must be an Account instance, not a {type(account)}"
raise TypeError(msg)

if limit != "all" and isinstance(limit, int) is False:
msg = "`limit` must be an integer or 'all'"
Expand All @@ -35,13 +34,15 @@ def check_top_kwargs(**kwargs):
and not isinstance(date, datetime.datetime)
and not isinstance(date, datetime.date)
):
raise TypeError("`date` must be a datetime or date, " "not a %s" % type(date))
msg = f"`date` must be a datetime or date, not a {type(date)}"
raise TypeError(msg)

if period not in ["day", "week", "month", "year"]:
raise TypeError(
msg = (
'`period` must be one of "day", "week", "month" or "year", '
"not %s" % type(period)
f"not {type(period)}"
)
raise TypeError(msg)


def get_period_times(date, period):
Expand Down Expand Up @@ -120,7 +121,8 @@ def top_albums(account=None, artist=None, limit=10, date=None, period="day"):
check_top_kwargs(account=account, limit=limit, date=date, period=period)

if artist is not None and not isinstance(artist, Artist):
raise TypeError("artist must be an Artist instance, " "not a %s" % type(artist))
msg = f"artist must be an Artist instance, not a {type(artist)}"
raise TypeError(msg)

qs_kwargs = {}

Expand Down Expand Up @@ -208,10 +210,12 @@ def top_tracks(
check_top_kwargs(account=account, limit=limit, date=date, period=period)

if album is not None and type(album) is not Album:
raise TypeError("album must be an Album instance, " "not a %s" % type(album))
msg = f"album must be an Album instance, not a {type(album)}"
raise TypeError(msg)

if artist is not None and type(artist) is not Artist:
raise TypeError("artist must be an Artist instance, " "not a %s" % type(artist))
msg = f"artist must be an Artist instance, not a {type(artist)}"
raise TypeError(msg)

qs_kwargs = {}

Expand Down Expand Up @@ -247,9 +251,8 @@ def recent_scrobbles(account=None, limit=10):
limit -- Maximum number to fetch. Default is 10.
"""
if account is not None and not isinstance(account, Account):
raise TypeError(
"account must be an Account instance, " "not a %s" % type(account)
)
msg = f"account must be an Account instance, not a {type(account)}"
raise TypeError(msg)

if isinstance(limit, int) is False:
msg = "`limit` must be an integer"
Expand Down Expand Up @@ -279,12 +282,12 @@ def day_scrobbles(date, account=None):
account -- An Account object or None (default, Scrobbles by all Accounts).
"""
if not isinstance(date, datetime.datetime) and not isinstance(date, datetime.date):
raise TypeError("date must be a datetime or date, " "not a %s" % type(date))
msg = f"date must be a datetime or date, not a {type(date)}"
raise TypeError(msg)

if account is not None and not isinstance(account, Account):
raise TypeError(
"account must be an Account instance, " "not a %s" % type(account)
)
msg = f"account must be an Account instance, not a {type(account)}"
raise TypeError(msg)

qs_kwargs = {}

Expand Down Expand Up @@ -322,9 +325,8 @@ def annual_scrobble_counts(account=None):
"""

if account is not None and not isinstance(account, Account):
raise TypeError(
"account must be an Account instance, " "not a %s" % type(account)
)
msg = f"account must be an Account instance, not a {type(account)}"
raise TypeError(msg)

qs = Scrobble.objects

Expand Down
4 changes: 2 additions & 2 deletions ditto/lastfm/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,12 +28,12 @@
name="track_list",
),
re_path(
r"^music/(?P<artist_slug>%s)/$" % slug_chars,
rf"^music/(?P<artist_slug>{slug_chars})/$",
view=views.ArtistDetailView.as_view(),
name="artist_detail",
),
re_path(
r"^music/(?P<artist_slug>%s)/\+albums/$" % slug_chars,
rf"^music/(?P<artist_slug>{slug_chars})/\+albums/$",
view=views.ArtistAlbumsView.as_view(),
name="artist_albums",
),
Expand Down
4 changes: 2 additions & 2 deletions ditto/pinboard/factories.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,8 @@ class Meta:
model = models.Account

username = factory.Sequence(lambda n: "user%d" % n)
url = factory.LazyAttribute(lambda obj: "https://pinboard.com/%s" % obj.username)
api_token = factory.LazyAttribute(lambda obj: "%s:123ABC" % obj.username)
url = factory.LazyAttribute(lambda obj: f"https://pinboard.com/{obj.username}")
api_token = factory.LazyAttribute(lambda obj: f"{obj.username}:123ABC")


class BookmarkFactory(factory.django.DjangoModelFactory):
Expand Down
10 changes: 5 additions & 5 deletions ditto/pinboard/fetch.py
Original file line number Diff line number Diff line change
Expand Up @@ -85,9 +85,8 @@ def _get_accounts(self, username):
if account.is_active:
accounts = [account]
else:
raise FetchError(
"The account %s is curently marked as inactive." % username
)
msg = f"The account {username} is curently marked as inactive."
raise FetchError(msg)
return accounts

def _send_request(self, fetch_type, params, account):
Expand Down Expand Up @@ -141,7 +140,7 @@ def _send_request(self, fetch_type, params, account):
response.raise_for_status()
except requests.exceptions.HTTPError:
# 4xx or 5xx errors:
error_message = "HTTP Error: %s" % response.status_code
error_message = f"HTTP Error: {response.status_code}"
except NameError:
if error_message == "":
error_message = "Something unusual went wrong."
Expand Down Expand Up @@ -251,7 +250,8 @@ def fetch(self, post_date, username=None):
try:
dt = datetime.strptime(post_date, "%Y-%m-%d").astimezone(timezone.utc)
except ValueError as err:
raise FetchError("Invalid date format ('%s')" % post_date) from err
msg = f"Invalid date format ('{post_date}')"
raise FetchError(msg) from err
else:
return self._fetch(fetch_type="date", params={"dt": dt}, username=username)

Expand Down
Loading

0 comments on commit 69cb53b

Please sign in to comment.