Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

More ruff #1074

Merged
merged 3 commits into from
Jul 29, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion accounts/admin.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
from __future__ import annotations


__copyright__ = "Copyright (C) 2014 Andreas Kloeckner"

__license__ = """
Expand Down Expand Up @@ -46,7 +49,7 @@ def lookups(self, request, model_admin):
course_identifiers = (
_filter_courses_for_user(Course.objects, request.user)
.values_list("identifier", flat=True))
return zip(course_identifiers, course_identifiers)
return zip(course_identifiers, course_identifiers, strict=True)

def queryset(self, request, queryset):
if self.value():
Expand Down
2 changes: 2 additions & 0 deletions accounts/apps.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from __future__ import annotations

from django.apps import AppConfig
from django.utils.translation import gettext_lazy as _

Expand Down
3 changes: 3 additions & 0 deletions accounts/models.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
from __future__ import annotations


__copyright__ = "Copyright (C) 2014 Andreas Kloeckner"

__license__ = """
Expand Down
5 changes: 4 additions & 1 deletion accounts/utils.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
from __future__ import annotations


__copyright__ = "Copyright (C) 2018 Dong Zhuang"

__license__ = """
Expand Down Expand Up @@ -143,7 +146,7 @@ def check_email_appellation_priority_list(self):
if not custom_email_appellation_priority_list:
return errors

if not isinstance(custom_email_appellation_priority_list, (list, tuple)):
if not isinstance(custom_email_appellation_priority_list, list | tuple):
errors.append(Warning(
msg=("{}, {}".format(
INSTANCE_ERROR_PATTERN
Expand Down
9 changes: 6 additions & 3 deletions course/admin.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
from __future__ import annotations


__copyright__ = "Copyright (C) 2014 Andreas Kloeckner"

__license__ = """
Expand All @@ -20,7 +23,7 @@
THE SOFTWARE.
"""

from typing import Any, Tuple
from typing import Any

from django import forms
from django.contrib import admin
Expand Down Expand Up @@ -85,7 +88,7 @@ def _filter_participation_linked_obj_for_user(queryset, user):

# {{{ list filter helper

def _filter_related_only(filter_arg: str) -> Tuple[str, Any]:
def _filter_related_only(filter_arg: str) -> tuple[str, Any]:
return (filter_arg, admin.RelatedOnlyFieldListFilter)

# }}}
Expand Down Expand Up @@ -573,7 +576,7 @@ def lookups(self, request, model_admin):
flow_session__course__participations__roles__permissions__permission=pperm.use_admin_interface)

flow_ids = qs.values_list("flow_session__flow_id", flat=True).distinct()
return zip(flow_ids, flow_ids)
return zip(flow_ids, flow_ids, strict=True)

def queryset(self, request, queryset):
if self.value():
Expand Down
5 changes: 4 additions & 1 deletion course/analytics.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
from __future__ import annotations


__copyright__ = "Copyright (C) 2014 Andreas Kloeckner"

__license__ = """
Expand Down Expand Up @@ -181,7 +184,7 @@ def get_bin_info_list(self):
100*weight/total_weight
if total_weight
else None))
for start, weight in zip(num_bin_starts, bins)]
for start, weight in zip(num_bin_starts, bins, strict=True)]

str_bin_info = [
BinInfo(
Expand Down
2 changes: 2 additions & 0 deletions course/apps.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from __future__ import annotations

from django.apps import AppConfig
from django.utils.translation import gettext_lazy as _

Expand Down
3 changes: 3 additions & 0 deletions course/calendar.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
from __future__ import annotations


__copyright__ = "Copyright (C) 2014 Andreas Kloeckner"

__license__ = """
Expand Down
6 changes: 4 additions & 2 deletions course/constants.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
from __future__ import annotations


__copyright__ = "Copyright (C) 2014 Andreas Kloeckner"

__license__ = """
Expand All @@ -20,7 +23,6 @@
THE SOFTWARE.
"""

import typing

from django.utils.translation import gettext, pgettext_lazy

Expand Down Expand Up @@ -296,7 +298,7 @@ class flow_session_expiration_mode: # noqa


def is_expiration_mode_allowed(
expmode: str, permissions: typing.FrozenSet[str]
expmode: str, permissions: frozenset[str]
) -> bool:
if expmode == flow_session_expiration_mode.roll_over:
if (flow_permission.set_roll_over_expiration_mode
Expand Down
14 changes: 7 additions & 7 deletions course/content.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@
import os
import re
import sys
from typing import Union, cast
from typing import cast

import dulwich.objects
import dulwich.repo
Expand All @@ -51,10 +51,10 @@

# {{{ mypy

from collections.abc import Callable
from typing import (
TYPE_CHECKING,
Any,
Callable,
)


Expand All @@ -67,8 +67,8 @@
from course.validation import FileSystemFakeRepoTree, ValidationContext
from relate.utils import Repo_ish

Date_ish = Union[datetime.datetime, datetime.date]
Datespec = Union[datetime.datetime, datetime.date, str]
Date_ish = datetime.datetime | datetime.date
Datespec = datetime.datetime | datetime.date | str


class ChunkRulesDesc(Struct):
Expand Down Expand Up @@ -662,7 +662,7 @@ def look_up_git_object(repo: dulwich.repo.Repo,

from stat import S_ISLNK
while name_parts:
if not isinstance(cur_lookup, (Tree, FileSystemFakeRepoTree)):
if not isinstance(cur_lookup, Tree | FileSystemFakeRepoTree):
raise ObjectDoesNotExist(
_("'%s' is not a directory, cannot lookup nested names")
% os.sep.join(processed_name_parts))
Expand Down Expand Up @@ -719,7 +719,7 @@ def get_repo_tree(repo: Repo_ish, full_name: str, commit_sha: bytes) -> Tree_ish

msg_full_name = full_name if full_name else _("(repo root)")

if isinstance(git_obj, (Tree, FileSystemFakeRepoTree)):
if isinstance(git_obj, Tree | FileSystemFakeRepoTree):
return git_obj
else:
raise ObjectDoesNotExist(_("resource '%s' is not a tree") % msg_full_name)
Expand Down Expand Up @@ -749,7 +749,7 @@ def get_repo_blob(repo: Repo_ish, full_name: str, commit_sha: bytes) -> Blob_ish

msg_full_name = full_name if full_name else _("(repo root)")

if isinstance(git_obj, (Blob, FileSystemFakeRepoFile)):
if isinstance(git_obj, Blob | FileSystemFakeRepoFile):
return git_obj
else:
raise ObjectDoesNotExist(_("resource '%s' is not a file") % msg_full_name)
Expand Down
5 changes: 3 additions & 2 deletions course/flow.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,8 @@
THE SOFTWARE.
"""

from typing import TYPE_CHECKING, Any, Iterable, List, Optional
from collections.abc import Iterable
from typing import TYPE_CHECKING, Any

from crispy_forms.helper import FormHelper
from crispy_forms.layout import Submit
Expand Down Expand Up @@ -1304,7 +1305,7 @@ def regrade_session(

if session.in_progress:
with transaction.atomic():
answer_visits: List[Optional[FlowPageVisit]] = assemble_answer_visits(session) # noqa
answer_visits: list[FlowPageVisit | None] = assemble_answer_visits(session)

for i in range(len(answer_visits)):
answer_visit = answer_visits[i]
Expand Down
19 changes: 10 additions & 9 deletions course/grades.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,9 +28,6 @@
from typing import (
TYPE_CHECKING,
Any,
List,
Optional,
Tuple,
cast,
)

Expand Down Expand Up @@ -301,7 +298,7 @@ def grade_key(entry):
return (participation.user.last_name.lower(),
participation.user.first_name.lower())

grade_table = sorted(zip(participations, grade_table), key=grade_key)
grade_table = sorted(zip(participations, grade_table, strict=True), key=grade_key)

return render_course_page(pctx, "course/gradebook.html", {
"grade_table": grade_table,
Expand Down Expand Up @@ -330,7 +327,7 @@ def export_gradebook_csv(pctx):

writer.writerow(fieldnames)

for participation, grades in zip(participations, grade_table):
for participation, grades in zip(participations, grade_table, strict=True):
writer.writerow([
participation.user.username,
participation.user.last_name,
Expand Down Expand Up @@ -651,11 +648,14 @@ def view_grades_by_opportunity(
page_numbers = list(range(1, 1 + max_page_count))

from course.flow import assemble_page_grades
page_grades: List[List[Optional[FlowPageVisitGrade]]] = assemble_page_grades(all_flow_sessions) # noqa
page_grades: list[list[FlowPageVisitGrade | None]] \
= assemble_page_grades(all_flow_sessions)

for (_dummy2, grade_info), grade_list in zip(grade_table, page_grades): # type: ignore
for (_dummy2, grade_info), grade_list in \
zip(grade_table, page_grades, strict=True): # type: ignore
# Not all pages exist in all sessions
grades: List[Tuple[Optional[int], Optional[FlowPageVisitGrade]]] = list(enumerate(grade_list)) # noqa
grades: list[tuple[int | None, FlowPageVisitGrade | None]] \
= list(enumerate(grade_list))
if len(grades) < max_page_count:
grades.extend([(None, None)] * (max_page_count - len(grades)))
grade_info.grades = grades
Expand Down Expand Up @@ -999,7 +999,8 @@ def view_single_grade(pctx: CoursePageContext, participation_id: str,
flow_desc = get_flow_desc(pctx.repo, pctx.course,
opportunity.flow_id, pctx.course_commit_sha)
except ObjectDoesNotExist:
flow_sessions_and_session_properties: Optional[List[Tuple[Any, SessionProperties]]] = None # noqa
flow_sessions_and_session_properties: \
list[tuple[Any, SessionProperties]] | None = None
else:
flow_sessions_and_session_properties = []
for session in flow_sessions:
Expand Down
3 changes: 2 additions & 1 deletion course/grading.py
Original file line number Diff line number Diff line change
Expand Up @@ -517,7 +517,8 @@ def commit_grade_info(grade):
"flow_id": flow_id,
"pages": pages,
"graders": graders,
"pages_stats_counts": list(zip(pages, stats_table, page_counts)),
"pages_stats_counts":
list(zip(pages, stats_table, page_counts, strict=True)),
"grader_counts": grader_counts,
})

Expand Down
2 changes: 2 additions & 0 deletions course/management/commands/bulktofiles.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from __future__ import annotations

from django.core.exceptions import ObjectDoesNotExist
from django.core.management.base import BaseCommand, CommandError # noqa
from django.db import transaction
Expand Down
2 changes: 2 additions & 0 deletions course/management/commands/test.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from __future__ import annotations

from django.core.management.commands.test import Command as DjangoTestCommand


Expand Down
1 change: 1 addition & 0 deletions course/mdx_mathjax.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
# Downloaded from https://github.com/mayoff/python-markdown-mathjax/issues/3
from __future__ import annotations

import markdown
from markdown.postprocessors import Postprocessor
Expand Down
4 changes: 2 additions & 2 deletions course/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,10 @@
THE SOFTWARE.
"""

from collections.abc import Iterable
from typing import (
TYPE_CHECKING,
Any,
Iterable,
cast,
)

Expand Down Expand Up @@ -1354,7 +1354,7 @@ def validate_stipulations(stip): # pragma: no cover (deprecated and not tested)
% ", ".join(set(stip.keys()) - allowed_keys))

if "credit_percent" in stip and not isinstance(
stip["credit_percent"], (int, float)):
stip["credit_percent"], int | float):
raise ValidationError(_("credit_percent must be a float"))
if ("allowed_session_count" in stip
and (
Expand Down
3 changes: 3 additions & 0 deletions course/page/__init__.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
from __future__ import annotations


__copyright__ = "Copyright (C) 2014 Andreas Kloeckner"

__license__ = """
Expand Down
3 changes: 2 additions & 1 deletion course/page/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,8 @@
THE SOFTWARE.
"""

from typing import TYPE_CHECKING, Any, Callable
from collections.abc import Callable
from typing import TYPE_CHECKING, Any

import django.forms as forms
import django.http
Expand Down
3 changes: 3 additions & 0 deletions course/page/choice.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
from __future__ import annotations


__copyright__ = "Copyright (C) 2014 Andreas Kloeckner"

__license__ = """
Expand Down
6 changes: 4 additions & 2 deletions course/page/code.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
from __future__ import annotations


__copyright__ = "Copyright (C) 2014 Andreas Kloeckner"

__license__ = """
Expand Down Expand Up @@ -186,7 +189,6 @@ def request_run(run_req, run_timeout, image=None):
import errno
import http.client as http_client
import json
import socket

import docker
from docker.errors import APIError as DockerAPIError
Expand Down Expand Up @@ -346,7 +348,7 @@ def check_timeout():

return result

except socket.timeout:
except TimeoutError:
return {
"result": "timeout",
"exec_host": connect_host_ip,
Expand Down
5 changes: 4 additions & 1 deletion course/page/code_feedback.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
from __future__ import annotations


__copyright__ = "Copyright (C) 2014 Andreas Kloeckner"

__license__ = """
Expand Down Expand Up @@ -132,7 +135,7 @@ def check_scalar(self, name, ref, data, accuracy_critical=True,
rtol=1e-5, atol=1e-8, report_success=True, report_failure=True):
import numpy as np

if not isinstance(data, (complex, float, int, np.number)):
if not isinstance(data, complex | float | int | np.number):
try:
# Check whether data is a sympy number because sympy
# numbers do not follow the typical interface
Expand Down
Loading
Loading