Skip to content

Commit

Permalink
Apply some autofixes by ruff
Browse files Browse the repository at this point in the history
These were audited by hand, and fix violations of a number of `ruff`
rules proactively.
  • Loading branch information
DavidCain committed Jun 4, 2023
1 parent ce65ec5 commit d497ac6
Show file tree
Hide file tree
Showing 11 changed files with 21 additions and 20 deletions.
5 changes: 3 additions & 2 deletions ws/forms.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ def _bind_input(
if initial:
if isinstance(initial, bool):
js_expr = 'true' if initial else 'false'
elif isinstance(initial, (str, int)):
elif isinstance(initial, str | int):
js_expr = f"'{initial}'" # (integers get string values)
else:
raise TypeError(f'Unexpected initial value {initial}')
Expand Down Expand Up @@ -445,7 +445,8 @@ def _allowed_program_choices(self, allowed_program_enums):
allowed_program_enums = [self.instance.program_enum, *allowed_program_enums]

for category, choices in enums.Program.choices():
assert isinstance(category, str) and isinstance(choices, list)
assert isinstance(category, str)
assert isinstance(choices, list)
valid_choices = [
(value, label)
for (value, label) in choices
Expand Down
2 changes: 1 addition & 1 deletion ws/lottery/handle.py
Original file line number Diff line number Diff line change
Expand Up @@ -139,7 +139,7 @@ def _try_to_place(self, signup: models.SignUp) -> bool:
return False

def place_participant(self):
raise NotImplementedError()
raise NotImplementedError
# (Place on trip or waitlist, then):
# self.runner.mark_handled(self.participant)

Expand Down
2 changes: 1 addition & 1 deletion ws/merge.py
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ def check_fk_tables(
"""
non_handled = []
for table, col, _ftable in _fk_tables(cursor, src_table, column):
if col not in expected.get(table, tuple()):
if col not in expected.get(table, ()):
non_handled.append((table, col))
if non_handled:
missing = ','.join(f"{table}.{col}" for table, col in non_handled)
Expand Down
8 changes: 4 additions & 4 deletions ws/migrations/0051_consistent_levels.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import re
from typing import Dict, List, NamedTuple
from typing import NamedTuple

from django.db import migrations

Expand All @@ -25,7 +25,7 @@ class TripChange(NamedTuple):
'BIS',
'CIS',
}
updates: Dict[int, TripChange] = {
updates: dict[int, TripChange] = {
304: TripChange('B (below treeline), overnight', 'B'),
314: TripChange('I', 'AI'), # Flume
958: TripChange('I', 'AI'), # Flume
Expand Down Expand Up @@ -57,7 +57,7 @@ def make_levels_consistent(apps, schema_editor):
"""Change all old WS trips with a known level to have valid levels."""
Trip = apps.get_model("ws", "Trip")

def _trips_with_punctuation_changes() -> List[Trip]:
def _trips_with_punctuation_changes() -> list[Trip]:
normal_chars = set('ABCIS')
special_chars = re.compile(r'[+ ,/\.-]')
expected_chars = set('ABCIS+/,-. ').union(normal_chars)
Expand Down Expand Up @@ -88,7 +88,7 @@ def _trips_with_punctuation_changes() -> List[Trip]:

return trips

trips_to_update: List[Trip] = []
trips_to_update: list[Trip] = []

for trip in Trip.objects.filter(pk__in=updates):
assert trip.level == updates[trip.pk].old_level, f"Unexpected {trip.level}"
Expand Down
2 changes: 1 addition & 1 deletion ws/templatetags/membership_tags.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
from collections.abc import Mapping
from types import MappingProxyType
from typing import Mapping

from django import template

Expand Down
4 changes: 2 additions & 2 deletions ws/tests/templatetags/test_email_tags.py
Original file line number Diff line number Diff line change
Expand Up @@ -137,12 +137,12 @@ def test_html_template(self):
[
f'<h2 style="{inline["h2"]}">',
f' <a href="{url}" style="{inline["a"]}">Some Cool Upcoming Trip</a>',
f'</h2>',
'</h2>',
f'<h3 style="{inline["h3"]}">Sunday, December 14</h3>',
f'<p style="{inline["p"]}">',
f' <ul style="{inline["ul"]}">',
f' <li style="{inline["li"]}"><strong>Program</strong>: Winter (outside IAP)',
f' </li>',
' </li>',
f' <li style="{inline["li"]}"><strong>Type</strong>: Hiking</li>',
f' <li style="{inline["li"]}"><strong>Terrain level</strong>: C</li>',
f' <li style="{inline["li"]}"><strong>Difficulty rating:</strong> Advanced</li>',
Expand Down
2 changes: 1 addition & 1 deletion ws/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -438,4 +438,4 @@
except ImportError:
pass
else:
urlpatterns = [path('__debug__/', include(debug_toolbar.urls))] + urlpatterns
urlpatterns = [path('__debug__/', include(debug_toolbar.urls)), *urlpatterns]
6 changes: 3 additions & 3 deletions ws/utils/signups.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import contextlib

from django.contrib import messages
from django.db import transaction
from django.db.models import Q
Expand Down Expand Up @@ -86,10 +88,8 @@ def trip_or_wait(
messages.success(request, "Signed up!")

# Since the participant is now on the trip, we should be sure to remove any waitlist
try:
with contextlib.suppress(models.WaitListSignup.DoesNotExist):
signup.waitlistsignup.delete()
except models.WaitListSignup.DoesNotExist:
pass

return signup

Expand Down
6 changes: 3 additions & 3 deletions ws/views/preferences.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
paired with another participant. All of these options are deemed "preferences"
of the participant.
"""
import contextlib
import json
from datetime import datetime

Expand Down Expand Up @@ -40,10 +41,9 @@ def get_form_kwargs(self):
"""Edit existing instance, prevent user from pairing with self."""
kwargs = super().get_form_kwargs()
kwargs['participant'] = participant = self.request.participant
try:
with contextlib.suppress(models.LotteryInfo.DoesNotExist):
kwargs['instance'] = participant.lotteryinfo
except models.LotteryInfo.DoesNotExist:
pass

return kwargs

def form_valid(self, form):
Expand Down
2 changes: 1 addition & 1 deletion ws/views/trips.py
Original file line number Diff line number Diff line change
Expand Up @@ -149,7 +149,7 @@ def posted_feedback(self):
will raise ValueError or TypeError (on either 'split' or `int`)
"""
for key, comments in self.request.POST.items():
if not (key.startswith("par_") or key.startswith("flake_")):
if not (key.startswith(('par_', 'flake_'))):
continue

feedback_type, par_pk = key.split('_')
Expand Down
2 changes: 1 addition & 1 deletion ws/widgets.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ def render(self, name, value, attrs=None, renderer=None):

ng_model_init = {
'data-ng-model': ng_model,
'data-ng-init': f"{ng_model} = '{value or str()}'",
'data-ng-init': f"{ng_model} = '{value or ''}'",
'value': str(value) if value else '',
}

Expand Down

0 comments on commit d497ac6

Please sign in to comment.