Skip to content

Commit 9e1d740

Browse files
committed
Add ruff, clean up pylint
1 parent 8055b24 commit 9e1d740

File tree

14 files changed

+288
-230
lines changed

14 files changed

+288
-230
lines changed

.gitignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
.tool-versions
44
.DS_STORE
55
.ruff_cache/
6+
.idea/
67

78
# Byte-compiled / optimized / DLL files
89
__pycache__/

.pre-commit-config.yaml

Lines changed: 17 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,18 @@
11
repos:
2-
- repo: https://github.com/pre-commit/pre-commit-hooks
3-
rev: v4.3.0
4-
hooks:
5-
- id: check-yaml
6-
args: ['--unsafe']
7-
- id: check-toml
8-
- id: end-of-file-fixer
9-
- id: trailing-whitespace
2+
- repo: https://github.com/pre-commit/pre-commit-hooks
3+
rev: v4.3.0
4+
hooks:
5+
- id: check-yaml
6+
args: ['--unsafe']
7+
- id: check-toml
8+
- id: end-of-file-fixer
9+
- id: trailing-whitespace
10+
- repo: https://github.com/ambv/black
11+
rev: 23.1.0
12+
hooks:
13+
- id: black
14+
language_version: python3.10
15+
- repo: https://github.com/charliermarsh/ruff-pre-commit
16+
rev: "v0.0.259"
17+
hooks:
18+
- id: ruff

bsag/_logging.py

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
from __future__ import annotations # necessary for loguru
22

3+
from collections.abc import Callable
34
from enum import Flag, auto
4-
from typing import Callable
55

66
import loguru
77
from pydantic import BaseModel
@@ -28,10 +28,7 @@ def private_filter(record: loguru.Record) -> bool:
2828

2929
def private_formatter(record: loguru.Record) -> str:
3030
swc: BaseStepWithConfig | None = record["extra"].get("swc")
31-
if swc is None:
32-
name = record["file"].name
33-
else:
34-
name = swc.name()
31+
name = record["file"].name if swc is None else swc.name()
3532
return (
3633
"<green>{time:YYYY-MM-DD HH:mm:ss.SSS}</green> | "
3734
"<level>{level: >8}</level> | "

bsag/_types.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ def name() -> str:
2424
# https://github.com/python/mypy/issues/7049
2525
# The reason these aren't instance methods is that I can't enforce a constructor call that would set `config`.
2626
@classmethod
27-
def display_name(cls, config: C_co) -> str: # type: ignore
27+
def display_name(cls, _config: C_co) -> str: # type: ignore
2828
"""Returns display name of module that appears in student-facing logs."""
2929
return cls.name()
3030

bsag/bsag.py

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import itertools
22
import sys
33
from argparse import ArgumentParser
4+
from pathlib import Path
45
from typing import Any, get_args
56

67
import pluggy # type: ignore
@@ -57,6 +58,8 @@ def __init__(
5758
if not step_defs:
5859
step_defs = []
5960
pm = get_plugin_manager()
61+
# type: ignore
62+
# pylint: disable-next=no-member
6063
plugin_steps: list[type[ParamBaseStep]] = list(itertools.chain(*pm.hook.bsag_load_step_defs())) # type: ignore
6164
self._step_defs = {m.name(): m for m in plugin_steps + step_defs}
6265
self._global_config = self._load_yaml_global_config(global_config_path)
@@ -66,13 +69,13 @@ def __init__(
6669

6770
def _load_yaml_global_config(self, global_config_path: str | None) -> GlobalConfig:
6871
if global_config_path:
69-
with open(global_config_path, encoding="utf-8") as f:
72+
with Path(global_config_path).open(encoding="utf-8") as f:
7073
return GlobalConfig.parse_obj(yaml.safe_load(f))
7174
else:
7275
return GlobalConfig()
7376

7477
def _load_yaml_config(self, config_path: str) -> RunConfig:
75-
with open(config_path, encoding="utf-8") as f:
78+
with Path(config_path).open(encoding="utf-8") as f:
7679
predisc_config = ConfigPreDiscoveryYaml.parse_obj(yaml.safe_load(f))
7780

7881
config = RunConfig()

bsag/bsagio.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import contextlib
12
import sys
23
from typing import Any
34

@@ -26,10 +27,8 @@ def __init__(self, colorize_private: bool = False, log_level_private: str = "DEB
2627

2728
# TODO: `format` callable provided as argument?
2829
# TODO: log level setting, at least for private?
29-
try:
30+
with contextlib.suppress(ValueError):
3031
logger.remove(0)
31-
except ValueError:
32-
pass
3332

3433
student_sink = create_student_sink(self.step_logs)
3534
# Student logs are never formatted

bsag/steps/common/run_command.py

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@ def run(cls, bsagio: BSAGIO, config: RunCommandConfig) -> bool:
3333
results: Results = bsagio.data[RESULTS_KEY]
3434

3535
bsagio.private.debug(f"Working directory: {config.working_dir}")
36-
if type(config.command) is str:
36+
if isinstance(config.command, str):
3737
bsagio.private.debug("\n" + config.command)
3838
else:
3939
bsagio.private.debug("\n" + list2cmdline(config.command))
@@ -45,10 +45,7 @@ def run(cls, bsagio: BSAGIO, config: RunCommandConfig) -> bool:
4545
shell=config.shell,
4646
)
4747

48-
test_result = TestResult(
49-
name=config.display_name,
50-
max_score=config.points
51-
)
48+
test_result = TestResult(name=config.display_name, max_score=config.points)
5249
passed = True
5350

5451
if output.timed_out:

bsag/steps/gradescope/lateness.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ class LatenessConfig(BaseStepConfig):
1414
min_lateness_score: NonNegativeFloat = 0
1515

1616
@validator("score_decay")
17+
# pylint: disable-next=no-self-argument
1718
def halt_on_fail__score_decay_mutually_exclusive(
1819
cls,
1920
score_decay: dict[NonNegativeInt, float],
@@ -31,7 +32,7 @@ def name() -> str:
3132
return "gradescope.lateness"
3233

3334
@classmethod
34-
def display_name(cls, config: LatenessConfig) -> str:
35+
def display_name(cls, _config: LatenessConfig) -> str:
3536
return "Lateness"
3637

3738
@classmethod
@@ -48,7 +49,7 @@ def run(cls, bsagio: BSAGIO, config: LatenessConfig) -> bool:
4849
if lateness == 0:
4950
return True
5051

51-
bsagio.both.info("Your submission is %.2f hours late." % (lateness / 3600))
52+
bsagio.both.info(f"Your submission is {lateness / 3600:.2f} hours late.")
5253
if graced_lateness == 0:
5354
bsagio.both.info("This is within the grace period for late submissions on this assignment.")
5455
return True
@@ -74,7 +75,7 @@ def run(cls, bsagio: BSAGIO, config: LatenessConfig) -> bool:
7475
f"After applying a lateness penalty of {penalty * 100:.2f}%, your final score is {res.score:.3f}."
7576
)
7677
else:
77-
bsagio.both.info(f"Scores of 0 do not have lateness applied.")
78+
bsagio.both.info("Scores of 0 do not have lateness applied.")
7879
else:
7980
bsagio.private.error("Cannot apply a lateness penalty without an overall score.")
8081

bsag/steps/gradescope/limit_velocity.py

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88
from bsag.bsagio import BSAGIO
99
from bsag.utils.datetimes import ZERO_TD, format_datetime
1010

11-
from ._types import METADATA_KEY, SubmissionMetadata, Results, RESULTS_KEY
11+
from ._types import METADATA_KEY, RESULTS_KEY, Results, SubmissionMetadata
1212

1313
EXTRA_TOKENS_KEY = "extra_tokens"
1414
"""Used by `gradescope.limit_velocity` to add extra velocity tokens. If not present, then 0 tokens are added.
@@ -32,6 +32,7 @@ class LimitVelocityConfig(BaseStepConfig):
3232
windows: list[Window]
3333

3434
@validator("windows")
35+
# pylint: disable-next=no-self-argument
3536
def windows_must_be_strictly_asc(cls, windows: list[Window]) -> list[Window]:
3637
for i in range(len(windows) - 1):
3738
if windows[i + 1].start_time - windows[i].start_time <= ZERO_TD:
@@ -40,6 +41,7 @@ def windows_must_be_strictly_asc(cls, windows: list[Window]) -> list[Window]:
4041
return windows
4142

4243
@validator("windows", each_item=True)
44+
# pylint: disable-next=no-self-argument
4345
def windows_must_be_offset_aware(cls, window: Window, values: dict[str, Any]) -> Window:
4446
config_tz = timezone(values["time_zone"])
4547
if not window.start_time.tzinfo:
@@ -53,7 +55,7 @@ def name() -> str:
5355
return "gradescope.limit_velocity"
5456

5557
@classmethod
56-
def display_name(cls, config: LimitVelocityConfig) -> str:
58+
def display_name(cls, _config: LimitVelocityConfig) -> str:
5759
return "Limit Velocity"
5860

5961
@classmethod
@@ -68,8 +70,9 @@ def run(cls, bsagio: BSAGIO, config: LimitVelocityConfig) -> bool:
6870
start_time=datetime.utcfromtimestamp(0).astimezone(timezone(config.time_zone)),
6971
max_tokens=1,
7072
recharge_time=ZERO_TD,
71-
)
72-
] + config.windows
73+
),
74+
*config.windows,
75+
]
7376

7477
# Latest window with start time before current submission
7578
w_idx, active_window = [(i, w) for i, w in enumerate(windows) if w.start_time < curr_sub_create_time][-1]

bsag/steps/gradescope/results.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ def name() -> str:
1717
return "gradescope.results"
1818

1919
@classmethod
20-
def display_name(cls, config: ResultsConfig) -> str:
20+
def display_name(cls, _config: ResultsConfig) -> str:
2121
return "Results"
2222

2323
@classmethod

0 commit comments

Comments
 (0)