Skip to content

Commit 965110f

Browse files
authored
Use comprehensions (#83)
1 parent b3a0376 commit 965110f

File tree

16 files changed

+73
-78
lines changed

16 files changed

+73
-78
lines changed

.github/workflows/ci.yml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ jobs:
2525
2626
- name: Analysing the code with pylint
2727
run: |
28-
python -m pylint -E partitionmanager
28+
python -m pylint --errors-only partitionmanager
2929
3030
- name: Lint Python code with Ruff
3131
run: |

partitionmanager/cli.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -182,8 +182,8 @@ def _extract_single_column(row):
182182
def list_tables(conf):
183183
"""List all tables for the current database."""
184184
rows = conf.dbcmd.run("SHOW TABLES;")
185-
table_names = map(lambda row: _extract_single_column(row), rows)
186-
table_objects = map(lambda name: partitionmanager.types.Table(name), table_names)
185+
table_names = (_extract_single_column(row) for row in rows)
186+
table_objects = (partitionmanager.types.Table(name) for name in table_names)
187187
return list(table_objects)
188188

189189

@@ -287,7 +287,7 @@ def do_partition(conf):
287287
log.info("Database is read-only, only emitting statistics")
288288
if conf.prometheus_stats_path:
289289
do_stats(conf)
290-
return dict()
290+
return {}
291291

292292
if conf.noop:
293293
log.info("Running in noop mode, no changes will be made")
@@ -304,7 +304,7 @@ def do_partition(conf):
304304
type_name="counter",
305305
)
306306

307-
all_results = dict()
307+
all_results = {}
308308
for table in conf.tables:
309309
time_start = None
310310
try:
@@ -384,7 +384,7 @@ def do_stats(conf, metrics=partitionmanager.stats.PrometheusMetrics()):
384384

385385
log = logging.getLogger("do_stats")
386386

387-
all_results = dict()
387+
all_results = {}
388388
for table in list_tables(conf):
389389
table_problems = pm_tap.get_table_compatibility_problems(conf.dbcmd, table)
390390
if table_problems:
@@ -476,7 +476,7 @@ def drop_cmd(args):
476476

477477

478478
def do_find_drops_for_tables(conf):
479-
all_results = dict()
479+
all_results = {}
480480
for table in conf.tables:
481481
log = logging.getLogger(f"do_find_drops_for_tables:{table.name}")
482482

partitionmanager/cli_test.py

Lines changed: 22 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -127,7 +127,7 @@ def test_partition_cmd_several_tables(self):
127127
output = partition_cmd(args)
128128

129129
self.assertEqual(len(output), 2)
130-
self.assertSetEqual(set(output), set(["testtable", "another_table"]))
130+
self.assertSetEqual(set(output), {"testtable", "another_table"})
131131

132132
def test_partition_unpartitioned_table(self):
133133
o = run_partition_cmd_yaml(
@@ -186,7 +186,7 @@ def test_partition_cmd_two_tables(self):
186186
mariadb: {str(fake_exec)}
187187
"""
188188
)
189-
self.assertSetEqual(set(o), set(["test", "test_with_retention"]))
189+
self.assertSetEqual(set(o), {"test", "test_with_retention"})
190190

191191
def test_partition_period_daily(self):
192192
o = run_partition_cmd_yaml(
@@ -201,7 +201,7 @@ def test_partition_period_daily(self):
201201
"""
202202
)
203203
self.assertSequenceEqual(
204-
set(o), set(["partitioned_last_week", "partitioned_yesterday"])
204+
set(o), {"partitioned_last_week", "partitioned_yesterday"}
205205
)
206206

207207
def test_partition_period_seven_days(self):
@@ -221,16 +221,14 @@ def test_partition_period_seven_days(self):
221221

222222
self.assertEqual(
223223
set(logctx.output),
224-
set(
225-
[
226-
"INFO:partition:Evaluating Table partitioned_last_week "
227-
"(duration=7 days, 0:00:00)",
228-
"DEBUG:partition:Table partitioned_last_week has no pending SQL updates.", # noqa: E501
229-
"INFO:partition:Evaluating Table partitioned_yesterday "
230-
"(duration=7 days, 0:00:00)",
231-
"DEBUG:partition:Table partitioned_yesterday has no pending SQL updates.", # noqa: E501
232-
]
233-
),
224+
{
225+
"INFO:partition:Evaluating Table partitioned_last_week "
226+
"(duration=7 days, 0:00:00)",
227+
"DEBUG:partition:Table partitioned_last_week has no pending SQL updates.", # noqa: E501
228+
"INFO:partition:Evaluating Table partitioned_yesterday "
229+
"(duration=7 days, 0:00:00)",
230+
"DEBUG:partition:Table partitioned_yesterday has no pending SQL updates.", # noqa: E501
231+
},
234232
)
235233
self.assertSequenceEqual(list(o), [])
236234

@@ -249,7 +247,7 @@ def test_partition_period_different_per_table(self):
249247
"""
250248
)
251249
self.assertSequenceEqual(
252-
set(o), set(["partitioned_yesterday", "partitioned_last_week"])
250+
set(o), {"partitioned_yesterday", "partitioned_last_week"}
253251
)
254252

255253
def test_partition_with_db_url(self):
@@ -283,7 +281,7 @@ def assert_stats_results(self, results):
283281

284282
def assert_stats_prometheus_outfile(self, prom_file):
285283
lines = prom_file.split("\n")
286-
metrics = dict()
284+
metrics = {}
287285
for line in lines:
288286
if not line.startswith("#") and len(line) > 0:
289287
key, value = line.split(" ")
@@ -350,9 +348,7 @@ def test_cli_tables_override_yaml(self):
350348
""",
351349
datetime.now(tz=timezone.utc),
352350
)
353-
self.assertEqual(
354-
{str(x.name) for x in conf.tables}, set(["table_one", "table_two"])
355-
)
351+
self.assertEqual({str(x.name) for x in conf.tables}, {"table_one", "table_two"})
356352

357353
def test_cli_mariadb_override_yaml(self):
358354
args = PARSER.parse_args(["--mariadb", "/usr/bin/true", "stats"])
@@ -651,12 +647,10 @@ def test_drop_invalid_config(self):
651647
)
652648
self.assertEqual(
653649
set(logctx.output),
654-
set(
655-
[
656-
"WARNING:do_find_drops_for_tables:unused:"
657-
"Cannot process Table unused: no retention specified"
658-
]
659-
),
650+
{
651+
"WARNING:do_find_drops_for_tables:unused:"
652+
"Cannot process Table unused: no retention specified"
653+
},
660654
)
661655

662656
def test_drop_no_sql(self):
@@ -675,10 +669,8 @@ def test_drop_no_sql(self):
675669
)
676670
self.assertEqual(
677671
set(logctx.output),
678-
set(
679-
[
680-
"WARNING:do_find_drops_for_tables:unused:"
681-
"Cannot process Table unused: no date query specified"
682-
]
683-
),
672+
{
673+
"WARNING:do_find_drops_for_tables:unused:"
674+
"Cannot process Table unused: no date query specified"
675+
},
684676
)

partitionmanager/database_helpers_test.py

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

1616
class MockDatabase(DatabaseCommand):
1717
def __init__(self):
18-
self._responses = list()
18+
self._responses = []
1919
self.num_queries = 0
2020

2121
def add_response(self, expected, response):

partitionmanager/dropper.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ def _drop_statement(table, partition_list):
1616
if not partition_list:
1717
raise ValueError("Partition list may not be empty")
1818

19-
partitions = ",".join(map(lambda x: f"`{x.name}`", partition_list))
19+
partitions = ",".join(f"`{x.name}`" for x in partition_list)
2020

2121
alter_cmd = f"ALTER TABLE `{table.name}` DROP PARTITION IF EXISTS {partitions};"
2222

partitionmanager/dropper_test.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ def _timestamp_rsp(year, mo, day):
2020

2121
class MockDatabase(DatabaseCommand):
2222
def __init__(self):
23-
self._responses = list()
23+
self._responses = []
2424
self.num_queries = 0
2525

2626
def add_response(self, expected, response):

partitionmanager/migrate.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@ def write_state_info(conf, out_fp):
4848
log = logging.getLogger("write_state_info")
4949

5050
log.info("Writing current state information")
51-
state_info = {"time": conf.curtime, "tables": dict()}
51+
state_info = {"time": conf.curtime, "tables": {}}
5252
for table in conf.tables:
5353
map_data = _get_map_data_from_config(conf, table)
5454

@@ -90,7 +90,7 @@ def _plan_partitions_for_time_offsets(
9090
9191
rate_of_change: an ordered list of positions per RATE_UNIT.
9292
"""
93-
changes = list()
93+
changes = []
9494
for (i, offset), is_final in partitionmanager.tools.iter_show_end(
9595
enumerate(time_offsets)
9696
):
@@ -243,7 +243,7 @@ def calculate_sql_alters_from_state_info(conf, in_fp):
243243
f"{prior_data['time']} = {time_delta}"
244244
)
245245

246-
commands = dict()
246+
commands = {}
247247

248248
for table_name, prior_pos in prior_data["tables"].items():
249249
table = None
@@ -270,7 +270,7 @@ def calculate_sql_alters_from_state_info(conf, in_fp):
270270
delta_positions = list(
271271
map(operator.sub, ordered_current_pos, ordered_prior_pos)
272272
)
273-
rate_of_change = list(map(lambda pos: pos / time_delta, delta_positions))
273+
rate_of_change = [pos / time_delta for pos in delta_positions]
274274

275275
max_val_part = map_data["partitions"][-1]
276276
if not isinstance(max_val_part, partitionmanager.types.MaxValuePartition):

partitionmanager/migrate_test.py

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

2727
class MockDatabase(DatabaseCommand):
2828
def __init__(self):
29-
self._response = list()
29+
self._response = []
3030
self._select_response = [[{"id": 150}]]
3131
self.num_queries = 0
3232

partitionmanager/sql.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -53,15 +53,15 @@ def __init__(self):
5353
self.rows = None
5454
self.current_row = None
5555
self.current_field = None
56-
self.current_elements = list()
56+
self.current_elements = []
5757
self.statement = None
5858

5959
def parse(self, data):
6060
"""Return rows from an XML Result object."""
6161
if self.rows is not None:
6262
raise ValueError("XmlResult objects can only be used once")
6363

64-
self.rows = list()
64+
self.rows = []
6565
self.xmlparser.Parse(data)
6666

6767
if self.current_elements:
@@ -186,4 +186,4 @@ def run(self, sql_cmd):
186186
logging.debug(f"IntegratedDatabaseCommand executing {sql_cmd}")
187187
with self.connection.cursor() as cursor:
188188
cursor.execute(sql_cmd)
189-
return [row for row in cursor]
189+
return list(cursor)

partitionmanager/stats.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -22,14 +22,14 @@ class PrometheusMetrics:
2222
"""A set of metrics that can be rendered for Prometheus."""
2323

2424
def __init__(self):
25-
self.metrics = dict()
26-
self.help = dict()
27-
self.types = dict()
25+
self.metrics = {}
26+
self.help = {}
27+
self.types = {}
2828

2929
def add(self, name, table, data):
3030
"""Record metric data representing the name and table."""
3131
if name not in self.metrics:
32-
self.metrics[name] = list()
32+
self.metrics[name] = []
3333
self.metrics[name].append(PrometheusMetric(name, table, data))
3434

3535
def describe(self, name, help_text=None, type_name=None):
@@ -50,7 +50,7 @@ def render(self, fp):
5050
if n in self.types:
5151
print(f"# TYPE {name} {self.types[n]}", file=fp)
5252
for m in metrics:
53-
labels = list()
53+
labels = []
5454
if m.table:
5555
labels = [f'table="{m.table}"']
5656
print(f"{name}{{{','.join(labels)}}} {m.data}", file=fp)

0 commit comments

Comments
 (0)