Skip to content

Commit

Permalink
lint: introduce pyupgrade (with ruff)
Browse files Browse the repository at this point in the history
  • Loading branch information
mattwang44 committed Apr 9, 2024
1 parent d0992e3 commit c49548d
Show file tree
Hide file tree
Showing 26 changed files with 51 additions and 73 deletions.
1 change: 1 addition & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@ select = [
"I001", # isort
"N", # pep8-naming
"B", # bugbear
"UP", # pyupgrade
]

[tool.ruff.lint.isort]
Expand Down
3 changes: 1 addition & 2 deletions src/ccip/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,8 +77,7 @@ def __bool__(self):

@property
def speakers(self):
for s in self._speakers:
yield s
yield from self._speakers

Check warning on line 80 in src/ccip/views.py

View check run for this annotation

Codecov / codecov/patch

src/ccip/views.py#L80

Added line #L80 was not covered by tests


def _get_empty_event_info(event):
Expand Down
2 changes: 1 addition & 1 deletion src/core/context_processors.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@


def _build_google_form_url(uid):
return 'https://docs.google.com/forms/d/e/{uid}/viewform'.format(uid=uid)
return f'https://docs.google.com/forms/d/e/{uid}/viewform'


def script_prefix(request):
Expand Down
4 changes: 2 additions & 2 deletions src/core/difftools.py
Original file line number Diff line number Diff line change
Expand Up @@ -91,12 +91,12 @@ def dump_equal(a, b, loa, lob, hia, hib):

def dump_delete(a, b, loa, lob, hia, hib):
for line in a[loa:hia]:
yield mark_safe('<del>{}</del>'.format(conditional_escape(line)))
yield mark_safe(f'<del>{conditional_escape(line)}</del>')

Check warning on line 94 in src/core/difftools.py

View check run for this annotation

Codecov / codecov/patch

src/core/difftools.py#L94

Added line #L94 was not covered by tests


def dump_insert(a, b, loa, lob, hia, hib):
for line in b[lob:hib]:
yield mark_safe('<ins>{}</ins>'.format(conditional_escape(line)))
yield mark_safe(f'<ins>{conditional_escape(line)}</ins>')

Check warning on line 99 in src/core/difftools.py

View check run for this annotation

Codecov / codecov/patch

src/core/difftools.py#L99

Added line #L99 was not covered by tests


BLOCK_HANDLERS = {
Expand Down
2 changes: 1 addition & 1 deletion src/core/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -224,7 +224,7 @@ class Meta:
def save(self, *args, **kwargs):
if not self.key:
self.key = self.generate_key()
return super(Token, self).save(*args, **kwargs)
return super().save(*args, **kwargs)

@classmethod
def generate_key(cls):
Expand Down
4 changes: 2 additions & 2 deletions src/core/tests/test_views.py
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ def activate_default_language():

@pytest.fixture
def content_page_full_path(language, content_page_path):
return '/{}{}'.format(language, content_page_path)
return f'/{language}{content_page_path}'


def test_content_pages(client, parser, content_page_full_path):
Expand Down Expand Up @@ -162,7 +162,7 @@ def get_link_safty_pair(tag):

def get_error_message():
errors = [
' {0!r}'.format(*p)
f' {p[0]!r}'
for p in link_noopener_pairs
if p[1] is not True
]
Expand Down
2 changes: 1 addition & 1 deletion src/core/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ def __init__(self, seq):
self._seq = seq

def __repr__(self):
return '<SequenceQuerySet: {seq!r}>'.format(seq=self._seq)
return f'<SequenceQuerySet: {self._seq!r}>'

def __len__(self):
return len(self._seq)
Expand Down
8 changes: 4 additions & 4 deletions src/events/admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,13 +35,13 @@ class TimeRangeFilter(admin.SimpleListFilter):
title = _('time value')
parameter_name = 'time-range'
day_queries = {
'day{}'.format(i): Q(value__date=date)
f'day{i}': Q(value__date=date)
for i, date in enumerate(settings.EVENTS_DAY_NAMES, 1)
}

def lookups(self, request, model_admin):
return [
('day{}'.format(i), name)
(f'day{i}', name)
for i, name in enumerate(settings.EVENTS_DAY_NAMES.values(), 1)
]

Expand Down Expand Up @@ -84,13 +84,13 @@ def get_minute(self, instance):
class EventTimeRangeFilter(admin.SimpleListFilter):

filter_kwargs_dict = {
'day{}'.format(i): day
f'day{i}': day
for i, day in enumerate(settings.EVENTS_DAY_NAMES, 1)
}

def lookups(self, request, model_admin):
return [
('day{}'.format(i), name)
(f'day{i}', name)
for i, name in enumerate(settings.EVENTS_DAY_NAMES.values(), 1)
]

Expand Down
7 changes: 2 additions & 5 deletions src/events/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,10 +44,7 @@ def select_storage():


def photo_upload_to(instance, filename):
return 'speaker/{speakername}/{filename}'.format(
speakername=slugify(instance.speaker_name, allow_unicode=True),
filename=filename,
)
return f'speaker/{slugify(instance.speaker_name, allow_unicode=True)}/{filename}'

Check warning on line 47 in src/events/models.py

View check run for this annotation

Codecov / codecov/patch

src/events/models.py#L47

Added line #L47 was not covered by tests


class TimeManager(models.Manager):
Expand Down Expand Up @@ -302,7 +299,7 @@ def __str__(self):
def get_absolute_url(self):
url = reverse('page', kwargs={'path': 'conference/keynotes'})
split = urllib.parse.urlsplit(url)
frag = 'keynote-speaker-{slug}'.format(slug=self.slug)
frag = f'keynote-speaker-{self.slug}'

Check warning on line 302 in src/events/models.py

View check run for this annotation

Codecov / codecov/patch

src/events/models.py#L302

Added line #L302 was not covered by tests
return urllib.parse.urlunsplit(split._replace(fragment=frag))

def get_static_data(self):
Expand Down
4 changes: 2 additions & 2 deletions src/events/renderers.py
Original file line number Diff line number Diff line change
Expand Up @@ -79,12 +79,12 @@ def render_sponsoredevent(e):


def render_event(e):
func_name = 'render_{cls}'.format(cls=type(e).__name__.lower())
func_name = f'render_{type(e).__name__.lower()}'

Check warning on line 82 in src/events/renderers.py

View check run for this annotation

Codecov / codecov/patch

src/events/renderers.py#L82

Added line #L82 was not covered by tests
try:
func = globals()[func_name]
except KeyError as err:

Check warning on line 85 in src/events/renderers.py

View check run for this annotation

Codecov / codecov/patch

src/events/renderers.py#L85

Added line #L85 was not covered by tests
raise ValueError(
'No suitable renderer for {!r} of {!r}'.format(e, type(e)),
f'No suitable renderer for {e!r} of {type(e)!r}',
) from err
return func(e)

Expand Down
6 changes: 2 additions & 4 deletions src/events/tests/renderers/test_render_block.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ def simple_component_renderer(mocker):
mocker.patch.multiple(
'events.renderers',
render_event=str,
render_block_location=lambda v: '{} '.format(v),
render_block_location=lambda v: f'{v} ',
)


Expand Down Expand Up @@ -108,9 +108,7 @@ def test_render_attached_period(utils, events, event_key, begin, end):
rendered = renderers.render_attached_period(e.begin_time, e.end_time)
assert utils.is_safe(rendered)
assert rendered == (
'<div class="attached time-table__time">{} &ndash; {}</div>'.format(
begin, end,
)
f'<div class="attached time-table__time">{begin} &ndash; {end}</div>'
)


Expand Down
4 changes: 2 additions & 2 deletions src/events/tests/test_views.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ def test_talk_list(client, accepted_talk_proposal, sponsored_block_event):
)
@pytest.mark.parametrize('pk,status', [(42, 200), (9, 404)])
def test_talk_detail(client, accepted_talk_proposal, pk, status):
r = client.get('/en-us/events/talk/{pk}/'.format(pk=pk))
r = client.get(f'/en-us/events/talk/{pk}/')
assert r.status_code == status


Expand All @@ -30,5 +30,5 @@ def test_talk_detail(client, accepted_talk_proposal, pk, status):
('carmona-eugene', 404),
])
def test_sponsored_event_detail(client, sponsored_block_event, slug, status):
r = client.get('/en-us/events/talk/sponsored/{slug}/'.format(slug=slug))
r = client.get(f'/en-us/events/talk/sponsored/{slug}/')
assert r.status_code == status
2 changes: 1 addition & 1 deletion src/events/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -190,7 +190,7 @@ def get_day_grouped_events(self):
try:
day_info = day_info_dict[begin.value.date()]
except KeyError:
logger.warn('Invalid time sot dropped: {}'.format(begin))
logger.warn(f'Invalid time sot dropped: {begin}')

Check warning on line 193 in src/events/views.py

View check run for this annotation

Codecov / codecov/patch

src/events/views.py#L193

Added line #L193 was not covered by tests
continue
for event in begin_time_event_dict[begin]:
location = event.location
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ def export_proposals_create_time(self):
# ^you can edit 'Asia/Taipei to other area.'
time = timezone.localtime(p.created_at).strftime('%Y-%m-%d %H:%M:%S')
joint_proposals.append({
'proposal_type(id)': ptype + '({})'.format(p.id),
'proposal_type(id)': ptype + f'({p.id})',
'title': p.title,
'speaker_name': p.submitter.speaker_name,
'email': p.submitter.email,
Expand Down
27 changes: 10 additions & 17 deletions src/proposals/management/commands/recent_proposals.py
Original file line number Diff line number Diff line change
Expand Up @@ -99,15 +99,11 @@ def handle(self, *args, **options):
else:
self.summary(recent_talks, recent_tutorials)
self.msg.write(
'\n\nGot total {:d} new proposals.\n'.format(
recent_talks.count() + recent_tutorials.count()
))
f'\n\nGot total {recent_talks.count() + recent_tutorials.count():d} new proposals.\n')
talk_count = TalkProposal.objects.filter(cancelled=False).count()
tutorial_count = TutorialProposal.objects.filter(cancelled=False).count()
self.msg.write(
'So far {:d} talk and {:d} tutorial proposals have been submitted.'
.format(
TalkProposal.objects.filter(cancelled=False).count(),
TutorialProposal.objects.filter(cancelled=False).count()
)
f'So far {talk_count:d} talk and {tutorial_count:d} tutorial proposals have been submitted.'
)
self.report(start_dt, end_dt, options['mailto'], options['slack'])
self.msg.close() # close the StringIO
Expand All @@ -126,8 +122,7 @@ def report(self, start_dt, end_dt, mailto=None, slack=False):
"""Report to either the stdout or mailing to some address"""
self.stdout.write(self.msg.getvalue())
title = (
'Proposal submission summary from {:%m/%d} to {:%m/%d}'
.format(start_dt, end_dt)
f'Proposal submission summary from {start_dt:%m/%d} to {end_dt:%m/%d}'
)
if mailto:
subject = '[PyConTW2016][Program] %s' % title
Expand All @@ -145,7 +140,7 @@ def report(self, start_dt, end_dt, mailto=None, slack=False):
# Create the Slack client and send message
slack = Slack(url=settings.SLACK_WEBHOOK_URL)
status, msg = slack.notify(
text='*%s*\n```\n%s\n```' % (title, self.msg.getvalue())
text=f'*{title}*\n```\n{self.msg.getvalue()}\n```'
)
if status != 200:
self.stderr.write(self.style.ERROR(
Expand Down Expand Up @@ -175,15 +170,13 @@ def create_datetime_range_lookup(self, recent_days, day_shift_hour):
) from e
if today_dt > today_utc_dt:
raise CommandError(
"Today's datetime {:%Y-%m-%d %H:%M} ({!s}) is yet present"
.format(today_dt, taiwan_tz)
f"Today's datetime {today_dt:%Y-%m-%d %H:%M} ({taiwan_tz!s}) is yet present"
)
earliest_dt = today_dt - timedelta(days=recent_days)
self.msg.write(
'Proposals submitted during the recent {:d} days\n'
'From {:%Y-%m-%d %H:%M} to {:%Y-%m-%d %H:%M}\n'
'(Timezone: {!s})\n\n'
.format(recent_days, earliest_dt, today_dt, taiwan_tz)
f'Proposals submitted during the recent {recent_days:d} days\n'
f'From {earliest_dt:%Y-%m-%d %H:%M} to {today_dt:%Y-%m-%d %H:%M}\n'
f'(Timezone: {taiwan_tz!s})\n\n'
)
recent_lookup = Q(
created_at__gte=earliest_dt,
Expand Down
10 changes: 3 additions & 7 deletions src/proposals/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ def __init__(self, *, proposal=None, user=None):
self._user = user or proposal.submitter

def __repr__(self):
return '<PrimarySpeaker: {name}>'.format(name=self.user.speaker_name)
return f'<PrimarySpeaker: {self.user.speaker_name}>'

def __eq__(self, other):
return (
Expand Down Expand Up @@ -105,10 +105,7 @@ class Meta:
verbose_name_plural = _('additional speakers')

def __str__(self):
return '{name} ({status})'.format(
name=self.user.speaker_name,
status=self.get_status_display(),
)
return f'{self.user.speaker_name} ({self.get_status_display()})'


class ProposalQuerySet(models.QuerySet):
Expand Down Expand Up @@ -231,8 +228,7 @@ def speakers(self):
.select_related('user')
)

for speaker in additionals:
yield speaker
yield from additionals

@property
def speaker_count(self):
Expand Down
2 changes: 1 addition & 1 deletion src/proposals/tests/test_management.py
Original file line number Diff line number Diff line change
Expand Up @@ -255,7 +255,7 @@ def test_default_hour_option(capsys):
call_command('recent_proposals')
out, err = capsys.readouterr()
assert re.search(
r'to {:%Y-%m-%d %H}:00$'.format(now_dt),
rf'to {now_dt:%Y-%m-%d %H}:00$',
out, re.MULTILINE
)

Expand Down
4 changes: 2 additions & 2 deletions src/proposals/tests/views/test_create.py
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ def test_talk_proposal_create_post(agreed_user, agreed_user_client):
title='Beyond the Style Guides<br>',
)
assert response.redirect_chain == [
('/en-us/proposals/talk/{pk}/edit/'.format(pk=proposal.pk), 302),
(f'/en-us/proposals/talk/{proposal.pk}/edit/', 302),
], response.context['form'].errors

msgs = [(m.level, m.message) for m in response.context['messages']]
Expand Down Expand Up @@ -135,7 +135,7 @@ def test_tutorial_proposal_create_post(agreed_user, agreed_user_client):
title='Beyond the Style Guides<br>',
)
assert response.redirect_chain == [
('/en-us/proposals/tutorial/{pk}/edit/'.format(pk=proposal.pk), 302),
(f'/en-us/proposals/tutorial/{proposal.pk}/edit/', 302),
], response.context['form'].errors

msgs = [(m.level, m.message) for m in response.context['messages']]
Expand Down
2 changes: 1 addition & 1 deletion src/proposals/tests/views/test_speakers.py
Original file line number Diff line number Diff line change
Expand Up @@ -160,7 +160,7 @@ def test_remove_speaker_post(user_client, proposal_type, additional_speaker):
follow=True,
)
assert response.redirect_chain == [
('/en-us/proposals/{}/42/manage-speakers/'.format(proposal_type), 302),
(f'/en-us/proposals/{proposal_type}/42/manage-speakers/', 302),
]


Expand Down
2 changes: 1 addition & 1 deletion src/proposals/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,4 @@ def format_names(names, sep_default=SEP_DEFAULT, sep_last=SEP_LAST):
assert names
if len(names) == 1:
return names[0]
return '{}{}{}'.format(sep_default.join(names[:-1]), sep_last, names[-1])
return f'{sep_default.join(names[:-1])}{sep_last}{names[-1]}'
3 changes: 2 additions & 1 deletion src/proposals/views/mixins.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,8 @@ def dispatch(self, request, *args, **kwargs):
class CocAgreementMixin:
def dispatch(self, request, *args, **kwargs):
if not self.request.user.has_agreed_coc:
return redirect('%s?next=%s' % (reverse('coc_agreement'), request.path))
url = reverse('coc_agreement')
return redirect(f'{url}?next={request.path}')

return super().dispatch(request, *args, **kwargs)

Expand Down
4 changes: 2 additions & 2 deletions src/pycontw2016/logger.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
import logging


class NewStyleLogMessage(object):
class NewStyleLogMessage:
def __init__(self, message, *args, **kwargs):
self.message = message
self.args = args
Expand All @@ -36,7 +36,7 @@ def __str__(self):

class StyleAdapter(logging.LoggerAdapter):
def __init__(self, logger, extra=None):
super(StyleAdapter, self).__init__(logger, extra or {})
super().__init__(logger, extra or {})

def log(self, level, msg, *args, **kwargs):
if self.isEnabledFor(level):
Expand Down
5 changes: 1 addition & 4 deletions src/sponsors/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,7 @@ def select_storage():


def logo_upload_to(instance, filename):
return 'sponsors/{name}/{filename}'.format(
name=slugify(instance.name, allow_unicode=True),
filename=filename,
)
return f'sponsors/{slugify(instance.name, allow_unicode=True)}/{filename}'

Check warning on line 17 in src/sponsors/models.py

View check run for this annotation

Codecov / codecov/patch

src/sponsors/models.py#L17

Added line #L17 was not covered by tests


class Sponsor(ConferenceRelated):
Expand Down
2 changes: 1 addition & 1 deletion src/sponsors/templatetags/sponsors.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
def sponsor_jsonize(sponsors):
sponsor_lists = {level: [] for level, _ in Sponsor.LEVEL_CHOICES}
sponsor_info_dict = collections.OrderedDict(
('level-{}'.format(level), {
(f'level-{level}', {
'name': name,
'sponsors': sponsor_lists[level],
})
Expand Down
Loading

0 comments on commit c49548d

Please sign in to comment.