Skip to content

Commit 6a49107

Browse files
authored
Ruff rules for comprehensions and performance (#310)
1 parent 83c10f5 commit 6a49107

File tree

21 files changed

+142
-146
lines changed

21 files changed

+142
-146
lines changed

scheduler/admin/task_admin.py

Lines changed: 15 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -27,21 +27,21 @@ def get_job_executions_for_task(queue_name: str, scheduled_task: Task) -> List[J
2727
)
2828

2929
res = sorted(
30-
list(filter(lambda j: job_execution_of(j, scheduled_task), job_list)), key=lambda j: j.created_at, reverse=True
30+
filter(lambda j: job_execution_of(j, scheduled_task), job_list), key=lambda j: j.created_at, reverse=True
3131
)
3232
return res
3333

3434

3535
class JobArgInline(GenericStackedInline):
3636
model = TaskArg
3737
extra = 0
38-
fieldsets = ((None, dict(fields=("arg_type", "val"))),)
38+
fieldsets = ((None, {"fields": ("arg_type", "val")}),)
3939

4040

4141
class JobKwargInline(GenericStackedInline):
4242
model = TaskKwarg
4343
extra = 0
44-
fieldsets = ((None, dict(fields=("key", ("arg_type", "val")))),)
44+
fieldsets = ((None, {"fields": ("key", ("arg_type", "val"))}),)
4545

4646

4747
def get_message_bit(rows_updated: int) -> str:
@@ -86,40 +86,40 @@ class Media:
8686
fieldsets = (
8787
(
8888
None,
89-
dict(
90-
fields=(
89+
{
90+
"fields": (
9191
"name",
9292
"callable",
9393
("enabled", "timeout", "result_ttl"),
9494
"task_type",
9595
)
96-
),
96+
},
9797
),
9898
(
9999
None,
100-
dict(fields=("scheduled_time",), classes=("tasktype-OnceTaskType",)),
100+
{"fields": ("scheduled_time",), "classes": ("tasktype-OnceTaskType",)},
101101
),
102102
(
103103
None,
104-
dict(fields=("cron_string",), classes=("tasktype-CronTaskType",)),
104+
{"fields": ("cron_string",), "classes": ("tasktype-CronTaskType",)},
105105
),
106106
(
107107
None,
108-
dict(
109-
fields=(
108+
{
109+
"fields": (
110110
(
111111
"interval",
112112
"interval_unit",
113113
),
114114
"repeat",
115115
),
116-
classes=("tasktype-RepeatableTaskType",),
117-
),
116+
"classes": ("tasktype-RepeatableTaskType",),
117+
},
118118
),
119-
(_("Queue settings"), dict(fields=(("queue", "at_front"), "job_name"))),
119+
(_("Queue settings"), {"fields": (("queue", "at_front"), "job_name")}),
120120
(
121121
_("Previous runs info"),
122-
dict(fields=(("successful_runs", "last_successful_run"), ("failed_runs", "last_failed_run"))),
122+
{"fields": (("successful_runs", "last_successful_run"), ("failed_runs", "last_failed_run"))},
123123
),
124124
)
125125

@@ -157,7 +157,7 @@ def change_view(self, request: HttpRequest, object_id, form_url="", extra_contex
157157
execution_list = get_job_executions_for_task(obj.queue, obj)
158158
except ConnectionErrorTypes as e:
159159
logger.warn(f"Could not get job executions: {e}")
160-
execution_list = list()
160+
execution_list = []
161161
paginator = self.get_paginator(request, execution_list, SCHEDULER_CONFIG.EXECUTIONS_IN_PAGE)
162162
page_number = request.GET.get("p", 1)
163163
page_obj = paginator.get_page(page_number)

scheduler/decorators.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
from scheduler.helpers.callback import Callback
55
from scheduler.types import ConnectionType
66

7-
JOB_METHODS_LIST: List[str] = list()
7+
JOB_METHODS_LIST: List[str] = []
88

99

1010
class job:

scheduler/helpers/queues/queue_logic.py

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -63,14 +63,14 @@ def queue_perform_job(job_model: JobModel, connection: ConnectionType) -> Any:
6363

6464

6565
class Queue:
66-
REGISTRIES = dict(
67-
finished="finished_job_registry",
68-
failed="failed_job_registry",
69-
scheduled="scheduled_job_registry",
70-
active="active_job_registry",
71-
canceled="canceled_job_registry",
72-
queued="queued_job_registry",
73-
)
66+
REGISTRIES = {
67+
"finished": "finished_job_registry",
68+
"failed": "failed_job_registry",
69+
"scheduled": "scheduled_job_registry",
70+
"active": "active_job_registry",
71+
"canceled": "canceled_job_registry",
72+
"queued": "queued_job_registry",
73+
}
7474

7575
def __init__(self, connection: ConnectionType, name: str, is_async: bool = True) -> None:
7676
"""Initializes a Queue object.
@@ -150,7 +150,7 @@ def get_registry(self, name: str) -> JobNamesRegistry:
150150
raise NoSuchRegistryError(f"Unknown registry name {name}")
151151

152152
def get_all_job_names(self) -> List[str]:
153-
all_job_names = list()
153+
all_job_names = []
154154
all_job_names.extend(self.queued_job_registry.all(self.connection))
155155
all_job_names.extend(self.finished_job_registry.all(self.connection))
156156
all_job_names.extend(self.active_job_registry.all(self.connection))

scheduler/management/commands/export.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -40,13 +40,11 @@ def add_arguments(self, parser: CommandParser) -> None:
4040

4141
def handle(self, *args: Any, **options: Any) -> None:
4242
file = open(options.get("filename"), "w") if options.get("filename") else sys.stdout
43-
res = list()
4443

4544
tasks = Task.objects.all()
4645
if options.get("enabled"):
4746
tasks = tasks.filter(enabled=True)
48-
for task in tasks:
49-
res.append(task.to_dict())
47+
res = [task.to_dict() for task in tasks]
5048

5149
if options.get("format") == "json":
5250
import json

scheduler/management/commands/import.py

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -52,9 +52,7 @@ def create_task_from_dict(task_dict: Dict[str, Any], update: bool) -> Optional[T
5252
if not settings.USE_TZ and not timezone.is_naive(target):
5353
target = timezone.make_naive(target)
5454
kwargs["scheduled_time"] = target
55-
model_fields = set(
56-
map(lambda field: field.attname, filter(lambda field: hasattr(field, "attname"), Task._meta.get_fields()))
57-
)
55+
model_fields = {field.attname for field in filter(lambda field: hasattr(field, "attname"), Task._meta.get_fields())}
5856
keys_to_ignore = list(filter(lambda _k: _k not in model_fields, kwargs.keys()))
5957
for k in keys_to_ignore:
6058
del kwargs[k]
@@ -116,7 +114,7 @@ def add_arguments(self, parser: CommandParser) -> None:
116114

117115
def handle(self, *args: Any, **options: Any) -> None:
118116
file = open(options.get("filename")) if options.get("filename") else sys.stdin # type: ignore[arg-type]
119-
jobs = list()
117+
jobs = []
120118
if options.get("format") == "json":
121119
import json
122120

scheduler/management/commands/scheduler_stats.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -66,7 +66,7 @@ def _print_stats_dashboard(
6666
click.echo(f"| {'Name':<16} | Queued | Active | Finished | Canceled | Workers |")
6767
self._print_separator()
6868
for ind, queue in enumerate(statistics["queues"]):
69-
vals = list((queue[k] for k in KEYS))
69+
vals = [queue[k] for k in KEYS]
7070
# Deal with colors
7171
if not with_color:
7272
colors = ["" for _ in KEYS]

scheduler/management/commands/scheduler_worker.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -150,7 +150,7 @@ def handle(self, **options: Any) -> None:
150150

151151
# Check whether sentry is enabled
152152
if options.get("sentry_dsn") is not None:
153-
sentry_opts = dict(ca_certs=options.get("sentry_ca_certs"), debug=options.get("sentry_debug"))
153+
sentry_opts = {"ca_certs": options.get("sentry_ca_certs"), "debug": options.get("sentry_debug")}
154154
dsn: str = options.get("sentry_dsn") # type: ignore
155155
register_sentry(dsn, **sentry_opts)
156156

scheduler/models/task.py

Lines changed: 31 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -191,7 +191,7 @@ def is_scheduled(self) -> bool:
191191
self.rqueue.queued_job_registry.exists(pipeline, self.job_name)
192192
self.rqueue.active_job_registry.exists(pipeline, self.job_name)
193193
results = pipeline.execute()
194-
res = any([item is not None for item in results])
194+
res = any(item is not None for item in results)
195195

196196
# If the job_name is not scheduled/queued/started,
197197
# update the job_id to None. (The job_id belongs to a previous run which is completed)
@@ -230,14 +230,14 @@ def _enqueue_args(self) -> Dict[str, Any]:
230230
- Set job-id to proper format
231231
- set job meta
232232
"""
233-
res = dict(
234-
meta=dict(),
235-
task_type=self.task_type,
236-
scheduled_task_id=self.id,
237-
on_success=Callback(success_callback),
238-
on_failure=Callback(failure_callback),
239-
name=self._next_job_id(),
240-
)
233+
res = {
234+
"meta": {},
235+
"task_type": self.task_type,
236+
"scheduled_task_id": self.id,
237+
"on_success": Callback(success_callback),
238+
"on_failure": Callback(failure_callback),
239+
"name": self._next_job_id(),
240+
}
241241
if self.at_front:
242242
res["at_front"] = self.at_front
243243
if self.timeout:
@@ -287,29 +287,29 @@ def _schedule_time(self) -> datetime:
287287
def to_dict(self) -> Dict[str, Any]:
288288
"""Export model to dictionary, so it can be saved as external file backup"""
289289
interval_unit = str(self.interval_unit) if self.interval_unit else None
290-
res = dict(
291-
model=str(self.task_type),
292-
name=self.name,
293-
callable=self.callable,
294-
callable_args=[dict(arg_type=arg.arg_type, val=arg.val) for arg in self.callable_args.all()],
295-
callable_kwargs=[
296-
dict(arg_type=arg.arg_type, key=arg.key, val=arg.val) for arg in self.callable_kwargs.all()
290+
res = {
291+
"model": str(self.task_type),
292+
"name": self.name,
293+
"callable": self.callable,
294+
"callable_args": [{"arg_type": arg.arg_type, "val": arg.val} for arg in self.callable_args.all()],
295+
"callable_kwargs": [
296+
{"arg_type": arg.arg_type, "key": arg.key, "val": arg.val} for arg in self.callable_kwargs.all()
297297
],
298-
enabled=self.enabled,
299-
queue=self.queue,
300-
repeat=getattr(self, "repeat", None),
301-
at_front=self.at_front,
302-
timeout=self.timeout,
303-
result_ttl=self.result_ttl,
304-
cron_string=getattr(self, "cron_string", None),
305-
scheduled_time=self._schedule_time().isoformat(),
306-
interval=getattr(self, "interval", None),
307-
interval_unit=interval_unit,
308-
successful_runs=getattr(self, "successful_runs", None),
309-
failed_runs=getattr(self, "failed_runs", None),
310-
last_successful_run=getattr(self, "last_successful_run", None),
311-
last_failed_run=getattr(self, "last_failed_run", None),
312-
)
298+
"enabled": self.enabled,
299+
"queue": self.queue,
300+
"repeat": getattr(self, "repeat", None),
301+
"at_front": self.at_front,
302+
"timeout": self.timeout,
303+
"result_ttl": self.result_ttl,
304+
"cron_string": getattr(self, "cron_string", None),
305+
"scheduled_time": self._schedule_time().isoformat(),
306+
"interval": getattr(self, "interval", None),
307+
"interval_unit": interval_unit,
308+
"successful_runs": getattr(self, "successful_runs", None),
309+
"failed_runs": getattr(self, "failed_runs", None),
310+
"last_successful_run": getattr(self, "last_successful_run", None),
311+
"last_failed_run": getattr(self, "last_failed_run", None),
312+
}
313313
return res
314314

315315
def get_absolute_url(self) -> str:

scheduler/settings.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@
1313

1414
logger = logging.getLogger("scheduler")
1515

16-
_QUEUES: Dict[str, QueueConfiguration] = dict()
16+
_QUEUES: Dict[str, QueueConfiguration] = {}
1717
SCHEDULER_CONFIG: SchedulerConfiguration = SchedulerConfiguration()
1818

1919

scheduler/tests/test_mgmt_commands/test_export.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ def tearDown(self) -> None:
2222
os.remove(self.tmpfile.name)
2323

2424
def test_export__should_export_job(self):
25-
tasks = list()
25+
tasks = []
2626
tasks.append(task_factory(TaskType.ONCE, enabled=True))
2727
tasks.append(task_factory(TaskType.REPEATABLE, enabled=True))
2828

@@ -35,7 +35,7 @@ def test_export__should_export_job(self):
3535
self.assertEqual(result[1], tasks[1].to_dict())
3636

3737
def test_export__should_export_enabled_jobs_only(self):
38-
tasks = list()
38+
tasks = []
3939
tasks.append(task_factory(TaskType.ONCE, enabled=True))
4040
tasks.append(task_factory(TaskType.REPEATABLE, enabled=False))
4141

@@ -47,7 +47,7 @@ def test_export__should_export_enabled_jobs_only(self):
4747
self.assertEqual(result[0], tasks[0].to_dict())
4848

4949
def test_export__should_export_job_yaml_without_yaml_lib(self):
50-
tasks = list()
50+
tasks = []
5151
tasks.append(task_factory(TaskType.ONCE, enabled=True))
5252
tasks.append(task_factory(TaskType.REPEATABLE, enabled=True))
5353

@@ -58,7 +58,7 @@ def test_export__should_export_job_yaml_without_yaml_lib(self):
5858
self.assertEqual(cm.exception.code, 1)
5959

6060
def test_export__should_export_job_yaml_green(self):
61-
tasks = list()
61+
tasks = []
6262
tasks.append(task_factory(TaskType.ONCE, enabled=True))
6363
tasks.append(task_factory(TaskType.REPEATABLE, enabled=True))
6464
tasks.append(task_factory(TaskType.CRON, enabled=True))

0 commit comments

Comments
 (0)