From ed80a6eaebcde94215032255e3c39980eea740d6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Edouard=20Choini=C3=A8re?= <27212526+echoix@users.noreply.github.com> Date: Sat, 4 Jan 2025 18:39:40 -0500 Subject: [PATCH] python: Use comprehensions when initializing lists and dicts (#4909) * python: Use comprehensions when initializing lists and dicts * style: Fix FURB140 [*] Use `itertools.starmap` instead of the generator --- python/grass/benchmark/results.py | 4 +- .../benchmark/testsuite/test_benchmark.py | 25 ++++---- .../benchmark/testsuite/test_benchmark_cli.py | 3 +- python/grass/grassdb/checks.py | 25 +++----- python/grass/gunittest/loader.py | 4 +- python/grass/gunittest/reporters.py | 63 +++++++++---------- python/grass/imaging/images2gif.py | 8 +-- python/grass/imaging/images2swf.py | 4 +- python/grass/jupyter/baseseriesmap.py | 4 +- python/grass/pygrass/modules/grid/grid.py | 41 +++++------- python/grass/pygrass/modules/grid/split.py | 22 +++---- .../grass/pygrass/modules/interface/module.py | 12 ++-- .../pygrass/modules/interface/typedict.py | 6 +- python/grass/pygrass/rpc/__init__.py | 5 +- python/grass/pygrass/utils.py | 9 +-- python/grass/pygrass/vector/__init__.py | 10 +-- python/grass/pygrass/vector/geometry.py | 5 +- python/grass/script/core.py | 27 ++++---- python/grass/script/raster.py | 3 +- python/grass/script/task.py | 26 +++----- python/grass/semantic_label/reader.py | 12 ++-- python/grass/temporal/abstract_dataset.py | 9 ++- python/grass/temporal/list_stds.py | 8 +-- python/grass/temporal/register.py | 3 +- python/grass/temporal/stds_import.py | 15 ++--- 25 files changed, 144 insertions(+), 209 deletions(-) diff --git a/python/grass/benchmark/results.py b/python/grass/benchmark/results.py index 123e5dd8458..3815a47d7f8 100644 --- a/python/grass/benchmark/results.py +++ b/python/grass/benchmark/results.py @@ -103,9 +103,7 @@ def join_results_from_files( source_filenames, prefixes=None, select=None, prefixes_as_labels=False ): """Join multiple files into one results object.""" - to_merge = [] - for result_file in source_filenames: - to_merge.append(load_results_from_file(result_file)) + to_merge = [load_results_from_file(result_file) for result_file in source_filenames] return join_results( to_merge, prefixes=prefixes, diff --git a/python/grass/benchmark/testsuite/test_benchmark.py b/python/grass/benchmark/testsuite/test_benchmark.py index 4eaf766859a..5d883caa1e9 100644 --- a/python/grass/benchmark/testsuite/test_benchmark.py +++ b/python/grass/benchmark/testsuite/test_benchmark.py @@ -52,14 +52,10 @@ def test_resolutions(self): }, ] resolutions = [300, 200, 100] - results = [] - for benchmark in benchmarks: - results.append( - benchmark_resolutions( - **benchmark, - resolutions=resolutions, - ) - ) + results = [ + benchmark_resolutions(**benchmark, resolutions=resolutions) + for benchmark in benchmarks + ] plot_file = "test_res_plot.png" num_cells_plot(results, filename=plot_file) self.assertTrue(Path(plot_file).is_file()) @@ -76,9 +72,9 @@ def test_single(self): "label": label, } ] - results = [] - for benchmark in benchmarks: - results.append(benchmark_single(**benchmark, repeat=repeat)) + results = [ + benchmark_single(**benchmark, repeat=repeat) for benchmark in benchmarks + ] self.assertEqual(len(results), len(benchmarks)) for result in results: self.assertTrue(hasattr(result, "all_times")) @@ -100,9 +96,10 @@ def test_nprocs(self): "max_nprocs": 4, } ] - results = [] - for benchmark in benchmarks: - results.append(benchmark_nprocs(**benchmark, repeat=repeat, shuffle=True)) + results = [ + benchmark_nprocs(**benchmark, repeat=repeat, shuffle=True) + for benchmark in benchmarks + ] self.assertEqual(len(results), len(benchmarks)) for result in results: self.assertTrue(hasattr(result, "times")) diff --git a/python/grass/benchmark/testsuite/test_benchmark_cli.py b/python/grass/benchmark/testsuite/test_benchmark_cli.py index 8e963245250..a50192c2d1d 100644 --- a/python/grass/benchmark/testsuite/test_benchmark_cli.py +++ b/python/grass/benchmark/testsuite/test_benchmark_cli.py @@ -43,8 +43,7 @@ class TestBenchmarkCLI(TestCase): """Tests that benchmarkin CLI works""" json_filename = "plot_test.json" - png_filenames = [f"plot_test1_{i}.png" for i in range(4)] - png_filenames.append("plot_test2.png") + png_filenames = [*[f"plot_test1_{i}.png" for i in range(4)], "plot_test2.png"] def tearDown(self): """Remove test files""" diff --git a/python/grass/grassdb/checks.py b/python/grass/grassdb/checks.py index 9024ac33517..39dd1081fdf 100644 --- a/python/grass/grassdb/checks.py +++ b/python/grass/grassdb/checks.py @@ -20,6 +20,7 @@ import grass.grassdb.config as cfg import grass.script as gs from grass.script import gisenv +from itertools import starmap def mapset_exists(path: str | os.PathLike[str], location=None, mapset=None) -> bool: @@ -536,10 +537,7 @@ def get_reasons_locations_not_removable(locations): Returns messages as list if there were any failed checks, otherwise empty list. """ - messages = [] - for grassdb, location in locations: - messages += get_reasons_location_not_removable(grassdb, location) - return messages + return list(starmap(get_reasons_location_not_removable, locations)) def get_reasons_location_not_removable(grassdb, location): @@ -570,9 +568,7 @@ def get_reasons_location_not_removable(grassdb, location): ) # Append to the list of tuples - mapsets = [] - for g_mapset in g_mapsets: - mapsets.append((grassdb, location, g_mapset)) + mapsets = [(grassdb, location, g_mapset) for g_mapset in g_mapsets] # Concentenate both checks messages += get_reasons_mapsets_not_removable(mapsets, check_permanent=False) @@ -601,9 +597,7 @@ def get_reasons_grassdb_not_removable(grassdb): g_locations = get_list_of_locations(grassdb) # Append to the list of tuples - locations = [] - for g_location in g_locations: - locations.append((grassdb, g_location)) + locations = [(grassdb, g_location) for g_location in g_locations] return get_reasons_locations_not_removable(locations) @@ -614,12 +608,11 @@ def get_list_of_locations(dbase): :return: list of locations (sorted) """ - locations = [] - for location in glob.glob(os.path.join(dbase, "*")): - if os.path.join(location, "PERMANENT") in glob.glob( - os.path.join(location, "*") - ): - locations.append(os.path.basename(location)) + locations = [ + os.path.basename(location) + for location in glob.glob(os.path.join(dbase, "*")) + if os.path.join(location, "PERMANENT") in glob.glob(os.path.join(location, "*")) + ] locations.sort(key=lambda x: x.lower()) diff --git a/python/grass/gunittest/loader.py b/python/grass/gunittest/loader.py index 50fa368f62a..2e8eaee7f95 100644 --- a/python/grass/gunittest/loader.py +++ b/python/grass/gunittest/loader.py @@ -228,9 +228,7 @@ def discover(self, start_dir, pattern="test*.py", top_level_dir=None): universal_location_value=self.universal_tests_value, import_modules=True, ) - tests = [] - for module in modules: - tests.append(self.loadTestsFromModule(module.module)) + tests = [self.loadTestsFromModule(module.module) for module in modules] return self.suiteClass(tests) diff --git a/python/grass/gunittest/reporters.py b/python/grass/gunittest/reporters.py index 48d5392afe2..5b468ac1d91 100644 --- a/python/grass/gunittest/reporters.py +++ b/python/grass/gunittest/reporters.py @@ -853,41 +853,34 @@ def finish(self): svn_info = get_svn_info() svn_revision = "" if not svn_info else svn_info["revision"] - summary = {} - summary["files_total"] = self.test_files - summary["files_successes"] = self.files_pass - summary["files_failures"] = self.files_fail - - summary["names"] = self.names - summary["tested_dirs"] = self.tested_dirs - # TODO: we don't have a general mechanism for storing any type in text - summary["files_returncodes"] = [str(item) for item in self.files_returncodes] - - # let's use seconds as a universal time delta format - # (there is no standard way how to store time delta as string) - summary["time"] = self.main_time.total_seconds() - - status = "failed" if self.files_fail else "succeeded" - summary["status"] = status - - summary["total"] = self.total - summary["successes"] = self.successes - summary["failures"] = self.failures - summary["errors"] = self.errors - summary["skipped"] = self.skipped - summary["expected_failures"] = self.expected_failures - summary["unexpected_successes"] = self.unexpected_success - - summary["test_files_authors"] = self.test_files_authors - summary["tested_modules"] = self.modules - summary["svn_revision"] = svn_revision - # ignoring issues with time zones - summary["timestamp"] = self.main_start_time.strftime("%Y-%m-%d %H:%M:%S") - # TODO: add some general metadata here (passed in constructor) - - # add additional information - for key, value in self._info.items(): - summary[key] = value + summary = { + "files_total": self.test_files, + "files_successes": self.files_pass, + "files_failures": self.files_fail, + "names": self.names, + "tested_dirs": self.tested_dirs, + # TODO: we don't have a general mechanism for storing any type in text + "files_returncodes": [str(item) for item in self.files_returncodes], + # let's use seconds as a universal time delta format + # (there is no standard way how to store time delta as string) + "time": self.main_time.total_seconds(), + "status": "failed" if self.files_fail else "succeeded", + "total": self.total, + "successes": self.successes, + "failures": self.failures, + "errors": self.errors, + "skipped": self.skipped, + "expected_failures": self.expected_failures, + "unexpected_successes": self.unexpected_success, + "test_files_authors": self.test_files_authors, + "tested_modules": self.modules, + "svn_revision": svn_revision, + # ignoring issues with time zones + "timestamp": self.main_start_time.strftime("%Y-%m-%d %H:%M:%S"), + # TODO: add some general metadata here (passed in constructor) + # add additional information + **dict(self._info.items()), + } summary_filename = os.path.join(self.result_dir, "test_keyvalue_result.txt") text = keyvalue_to_text(summary, sep="=", vsep="\n", isep=",") diff --git a/python/grass/imaging/images2gif.py b/python/grass/imaging/images2gif.py index 89dfcb92eed..5c4e9dec3cb 100644 --- a/python/grass/imaging/images2gif.py +++ b/python/grass/imaging/images2gif.py @@ -508,9 +508,7 @@ def writeGifPillow(filename, images, duration=0.1, repeat=True): """ loop = 0 if repeat else 1 - quantized = [] - for im in images: - quantized.append(im.quantize()) + quantized = [im.quantize() for im in images] quantized[0].save( filename, save_all=True, @@ -667,9 +665,7 @@ def readGif(filename, asNumpy=True): # Convert to normal PIL images if needed if not asNumpy: images2 = images - images = [] - for im in images2: - images.append(PIL.Image.fromarray(im)) + images = [PIL.Image.fromarray(im) for im in images2] # Done return images diff --git a/python/grass/imaging/images2swf.py b/python/grass/imaging/images2swf.py index d108c96b684..1ea1a4e8413 100644 --- a/python/grass/imaging/images2swf.py +++ b/python/grass/imaging/images2swf.py @@ -987,9 +987,7 @@ def readSwf(filename, asNumpy=True): # Convert to normal PIL images if needed if not asNumpy: images2 = images - images = [] - for im in images2: - images.append(PIL.Image.fromarray(im)) + images = [PIL.Image.fromarray(im) for im in images2] # Done return images diff --git a/python/grass/jupyter/baseseriesmap.py b/python/grass/jupyter/baseseriesmap.py index 4497b16593d..00ee394d119 100644 --- a/python/grass/jupyter/baseseriesmap.py +++ b/python/grass/jupyter/baseseriesmap.py @@ -239,9 +239,7 @@ def save( if not self._layers_rendered: self.render() - input_files = [] - for index in self._indices: - input_files.append(self._base_filename_dict[index]) + input_files = [self._base_filename_dict[index] for index in self._indices] save_gif( input_files, diff --git a/python/grass/pygrass/modules/grid/grid.py b/python/grass/pygrass/modules/grid/grid.py index fd980766ba0..5df1cb3aca7 100644 --- a/python/grass/pygrass/modules/grid/grid.py +++ b/python/grass/pygrass/modules/grid/grid.py @@ -319,12 +319,10 @@ def get_cmd(cmdd): >>> get_cmd(slp.get_dict()) # doctest: +ELLIPSIS ['r.slope.aspect', 'elevation=ele', 'format=degrees', ..., '--o'] """ - cmd = [ + return [ cmdd["name"], - ] - cmd.extend(("%s=%s" % (k, v) for k, v in cmdd["inputs"] if not isinstance(v, list))) - cmd.extend( - ( + *("%s=%s" % (k, v) for k, v in cmdd["inputs"] if not isinstance(v, list)), + *( "%s=%s" % ( k, @@ -332,21 +330,16 @@ def get_cmd(cmdd): ) for k, vals in cmdd["inputs"] if isinstance(vals, list) - ) - ) - cmd.extend( - ("%s=%s" % (k, v) for k, v in cmdd["outputs"] if not isinstance(v, list)) - ) - cmd.extend( - ( + ), + *("%s=%s" % (k, v) for k, v in cmdd["outputs"] if not isinstance(v, list)), + *( "%s=%s" % (k, ",".join([repr(v) for v in vals])) for k, vals in cmdd["outputs"] if isinstance(vals, list) - ) - ) - cmd.extend(f"-{flg}" for flg in cmdd["flags"] if len(flg) == 1) - cmd.extend(f"--{flg[0]}" for flg in cmdd["flags"] if len(flg) > 1) - return cmd + ), + *(f"-{flg}" for flg in cmdd["flags"] if len(flg) == 1), + *(f"--{flg[0]}" for flg in cmdd["flags"] if len(flg) > 1), + ] def cmd_exe(args): @@ -385,10 +378,7 @@ def cmd_exe(args): sub.Popen(["g.region", "raster=%s" % key], shell=shell, env=env).wait() else: # set the computational region - lcmd = [ - "g.region", - ] - lcmd.extend(["%s=%s" % (k, v) for k, v in bbox.items()]) + lcmd = ["g.region", *["%s=%s" % (k, v) for k, v in bbox.items()]] sub.Popen(lcmd, shell=shell, env=env).wait() if groups: copy_groups(groups, gisrc_src, gisrc_dst) @@ -602,9 +592,12 @@ def get_works(self): for key in self.inlist: inms[key] = "%s@%s" % (self.inlist[key][indx], self.mset.name) # set the computational region, prepare the region parameters - bbox = {k[0]: str(v) for k, v in box.items()[:-2]} - bbox["nsres"] = "%f" % reg.nsres - bbox["ewres"] = "%f" % reg.ewres + bbox = { + **{k[0]: str(v) for k, v in box.items()[:-2]}, + "nsres": "%f" % reg.nsres, + "ewres": "%f" % reg.ewres, + } + new_mset = ( self.msetstr % (self.start_row + row, self.start_col + col), ) diff --git a/python/grass/pygrass/modules/grid/split.py b/python/grass/pygrass/modules/grid/split.py index cac604327d8..17aa4905467 100644 --- a/python/grass/pygrass/modules/grid/split.py +++ b/python/grass/pygrass/modules/grid/split.py @@ -99,10 +99,9 @@ def split_region_in_overlapping_tiles(region=None, width=100, height=100, overla box_list = [] # print reg for row in range(nrows): - row_list = [] - for col in range(ncols): - # print 'c', c, 'r', r - row_list.append(get_bbox(reg, row, col, width, height, overlap)) + row_list = [ + get_bbox(reg, row, col, width, height, overlap) for col in range(ncols) + ] box_list.append(row_list) return box_list @@ -123,9 +122,10 @@ def split_region_tiles(region=None, width=100, height=100): nrows = (reg.rows + height - 1) // height box_list = [] for row in range(nrows): - row_list = [] - for col in range(ncols): - row_list.append(get_tile_start_end_row_col(reg, row, col, width, height)) + row_list = [ + get_tile_start_end_row_col(reg, row, col, width, height) + for col in range(ncols) + ] box_list.append(row_list) return box_list @@ -146,11 +146,9 @@ def get_overlap_region_tiles(region=None, width=100, height=100, overlap=0): ncols = (reg.cols + width - 1) // width nrows = (reg.rows + height - 1) // height box_list = [] - # print reg for row in range(nrows): - row_list = [] - for col in range(ncols): - # print 'c', c, 'r', r - row_list.append(get_bbox(reg, row, col, width, height, -overlap)) + row_list = [ + get_bbox(reg, row, col, width, height, -overlap) for col in range(ncols) + ] box_list.append(row_list) return box_list diff --git a/python/grass/pygrass/modules/interface/module.py b/python/grass/pygrass/modules/interface/module.py index 10c38a12990..eebb081cada 100644 --- a/python/grass/pygrass/modules/interface/module.py +++ b/python/grass/pygrass/modules/interface/module.py @@ -774,12 +774,12 @@ def get_dict(self): """Return a dictionary that includes the name, all valid inputs, outputs and flags """ - dic = {} - dic["name"] = self.name - dic["inputs"] = [(k, v.value) for k, v in self.inputs.items() if v.value] - dic["outputs"] = [(k, v.value) for k, v in self.outputs.items() if v.value] - dic["flags"] = [flg for flg in self.flags if self.flags[flg].value] - return dic + return { + "name": self.name, + "inputs": [(k, v.value) for k, v in self.inputs.items() if v.value], + "outputs": [(k, v.value) for k, v in self.outputs.items() if v.value], + "flags": [flg for flg in self.flags if self.flags[flg].value], + } def make_cmd(self): """Create the command string that can be executed in a shell diff --git a/python/grass/pygrass/modules/interface/typedict.py b/python/grass/pygrass/modules/interface/typedict.py index fb3ddb368eb..3fe9d59aabf 100644 --- a/python/grass/pygrass/modules/interface/typedict.py +++ b/python/grass/pygrass/modules/interface/typedict.py @@ -62,8 +62,4 @@ def __reduce__(self): ) def used(self): - key_dict = {} - for key in self: - if getattr(self, key): - key_dict[key] = getattr(self, key) - return key_dict + return {key: getattr(self, key) for key in self if getattr(self, key)} diff --git a/python/grass/pygrass/rpc/__init__.py b/python/grass/pygrass/rpc/__init__.py index 9685b279b0e..a0737288d88 100644 --- a/python/grass/pygrass/rpc/__init__.py +++ b/python/grass/pygrass/rpc/__init__.py @@ -116,9 +116,8 @@ def _get_vector_table_as_dict(lock, conn, data): table = layer.table_to_dict(where=where) layer.close() - ret = {} - ret["table"] = table - ret["columns"] = columns + ret = {"table": table, "columns": columns} + finally: # Send even if an exception was raised. conn.send(ret) diff --git a/python/grass/pygrass/utils.py b/python/grass/pygrass/utils.py index e66e421eeca..b28f01e3fa0 100644 --- a/python/grass/pygrass/utils.py +++ b/python/grass/pygrass/utils.py @@ -74,10 +74,11 @@ def find_in_location(type, pattern, location): return res def find_in_gisdbase(type, pattern, gisdbase): - res = [] - for loc in gisdbase.locations(): - res.extend(find_in_location(type, pattern, Location(loc, gisdbase.name))) - return res + return [ + a + for loc in gisdbase.locations() + for a in find_in_location(type, pattern, Location(loc, gisdbase.name)) + ] if gisdbase and location and mapset: mset = Mapset(mapset, location, gisdbase) diff --git a/python/grass/pygrass/vector/__init__.py b/python/grass/pygrass/vector/__init__.py index b36fae9fa4f..696abb84532 100644 --- a/python/grass/pygrass/vector/__init__.py +++ b/python/grass/pygrass/vector/__init__.py @@ -210,10 +210,7 @@ def write(self, geo_obj, cat=None, attrs=None): if cat is not None and cat not in self._cats: self._cats.append(cat) if self.table is not None and attrs is not None: - attr = [ - cat, - ] - attr.extend(attrs) + attr = [cat, *attrs] cur = self.table.conn.cursor() cur.execute(self.table.columns.insert_str, attr) cur.close() @@ -403,10 +400,7 @@ def number_of(self, vtype): @must_be_open def num_primitives(self): """Return dictionary with the number of all primitives""" - output = {} - for prim in VTYPE.keys(): - output[prim] = self.num_primitive_of(prim) - return output + return {prim: self.num_primitive_of(prim) for prim in VTYPE.keys()} @must_be_open def viter(self, vtype, idonly=False): diff --git a/python/grass/pygrass/vector/geometry.py b/python/grass/pygrass/vector/geometry.py index 04d57d7a204..e0cae2c4fc0 100644 --- a/python/grass/pygrass/vector/geometry.py +++ b/python/grass/pygrass/vector/geometry.py @@ -221,10 +221,7 @@ def __setitem__(self, keys, values): def __dict__(self): """Return a dict of the attribute table row.""" - dic = {} - for key, val in zip(self.keys(), self.values()): - dic[key] = val - return dic + return dict(zip(self.keys(), self.values())) def values(self): """Return the values of the attribute table row. diff --git a/python/grass/script/core.py b/python/grass/script/core.py index 0436ca02751..b1c12ed37b9 100644 --- a/python/grass/script/core.py +++ b/python/grass/script/core.py @@ -1464,20 +1464,19 @@ def list_strings(type, pattern=None, mapset=None, exclude=None, flag="", env=Non if type == "cell": verbose(_('Element type should be "raster" and not "%s"') % type, env=env) - result = [] - for line in read_command( - "g.list", - quiet=True, - flags="m" + flag, - type=type, - pattern=pattern, - exclude=exclude, - mapset=mapset, - env=env, - ).splitlines(): - result.append(line.strip()) - - return result + return [ + line.strip() + for line in read_command( + "g.list", + quiet=True, + flags="m" + flag, + type=type, + pattern=pattern, + exclude=exclude, + mapset=mapset, + env=env, + ).splitlines() + ] def list_pairs(type, pattern=None, mapset=None, exclude=None, flag="", env=None): diff --git a/python/grass/script/raster.py b/python/grass/script/raster.py index aaf9e0179b0..f3507cd48b0 100644 --- a/python/grass/script/raster.py +++ b/python/grass/script/raster.py @@ -255,8 +255,7 @@ def raster_what(map, coord, env=None, localized=False): for item in ret.splitlines(): line = item.split(sep)[3:] for i, map_name in enumerate(map_list): - tmp_dict = {} - tmp_dict[map_name] = {} + tmp_dict = {map_name: {}} for j in range(len(labels)): tmp_dict[map_name][labels[j]] = line[i * len(labels) + j] diff --git a/python/grass/script/task.py b/python/grass/script/task.py index 5d7355efacb..495ff7d17d2 100644 --- a/python/grass/script/task.py +++ b/python/grass/script/task.py @@ -114,22 +114,14 @@ def get_list_params(self, element="name"): :param str element: element name """ - params = [] - for p in self.params: - params.append(p[element]) - - return params + return [p[element] for p in self.params] def get_list_flags(self, element="name"): """Get list of flags :param str element: element name """ - flags = [] - for p in self.flags: - flags.append(p[element]) - - return flags + return [p[element] for p in self.flags] def get_param(self, value, element="name", raiseError=True): """Find and return a param by name @@ -548,12 +540,14 @@ def command_info(cmd): :param str cmd: the command to query """ task = parse_interface(cmd) - cmdinfo = {} - - cmdinfo["description"] = task.get_description() - cmdinfo["keywords"] = task.get_keywords() - cmdinfo["flags"] = flags = task.get_options()["flags"] - cmdinfo["params"] = params = task.get_options()["params"] + flags = task.get_options()["flags"] + params = task.get_options()["params"] + cmdinfo = { + "description": task.get_description(), + "keywords": task.get_keywords(), + "flags": flags, + "params": params, + } usage = task.get_name() flags_short = [] diff --git a/python/grass/semantic_label/reader.py b/python/grass/semantic_label/reader.py index 1a9e60bf0a0..358e7fafdf9 100644 --- a/python/grass/semantic_label/reader.py +++ b/python/grass/semantic_label/reader.py @@ -190,9 +190,9 @@ def get_bands(self): :return list: list of valid band identifiers """ - bands = [] - for root in self.config.values(): - for item in root.values(): - for band in item["bands"]: - bands.append("{}_{}".format(item["shortcut"], band)) - return bands + return [ + "{}_{}".format(item["shortcut"], band) + for root in self.config.values() + for item in root.values() + for band in item["bands"] + ] diff --git a/python/grass/temporal/abstract_dataset.py b/python/grass/temporal/abstract_dataset.py index fefef525216..b8e0856ca77 100644 --- a/python/grass/temporal/abstract_dataset.py +++ b/python/grass/temporal/abstract_dataset.py @@ -104,11 +104,10 @@ def is_topology_build(self): :return: A dictionary with "spatial" and "temporal" as keys that have boolean values """ - d = {} - d["spatial"] = self.is_spatial_topology_build() - d["temporal"] = self.is_temporal_topology_build() - - return d + return { + "spatial": self.is_spatial_topology_build(), + "temporal": self.is_temporal_topology_build(), + } def print_topology_info(self) -> None: if self.is_temporal_topology_build(): diff --git a/python/grass/temporal/list_stds.py b/python/grass/temporal/list_stds.py index c8517545aeb..9a62a420930 100644 --- a/python/grass/temporal/list_stds.py +++ b/python/grass/temporal/list_stds.py @@ -188,9 +188,7 @@ def default(self, o): dict_rows = [] for row in rows: - new_row = {} - for key, value in zip(column_names, row): - new_row[key] = value + new_row = dict(zip(column_names, row)) dict_rows.append(new_row) meta = {"column_names": column_names} with _open_output_file(file) as stream: @@ -221,9 +219,7 @@ def increase_indent(self, flow: bool = False, indentless: bool = False): dict_rows = [] for row in rows: - new_row = {} - for key, value in zip(column_names, row): - new_row[key] = value + new_row = dict(zip(column_names, row)) dict_rows.append(new_row) meta = {"column_names": column_names} with _open_output_file(file) as stream: diff --git a/python/grass/temporal/register.py b/python/grass/temporal/register.py index 0868b1a2386..b00d6631619 100644 --- a/python/grass/temporal/register.py +++ b/python/grass/temporal/register.py @@ -126,8 +126,7 @@ def register_maps_in_space_time_dataset( # create new stds only in the current mapset # remove all connections to any other mapsets # ugly hack ! - currcon = {} - currcon[mapset] = dbif.connections[mapset] + currcon = {mapset: dbif.connections[mapset]} dbif.connections = currcon # The name of the space time dataset is optional diff --git a/python/grass/temporal/stds_import.py b/python/grass/temporal/stds_import.py index f7030b66d31..6cf64ac6012 100644 --- a/python/grass/temporal/stds_import.py +++ b/python/grass/temporal/stds_import.py @@ -411,13 +411,14 @@ def import_stds( mapname = filename mapid = mapname + "@" + mapset - row = {} - row["filename"] = filename - row["name"] = mapname - row["id"] = mapid - row["start"] = line_list[1].strip() - row["end"] = line_list[2].strip() - row["semantic_label"] = line_list[3].strip() if len(line_list) == 4 else "" + row = { + "filename": filename, + "name": mapname, + "id": mapid, + "start": line_list[1].strip(), + "end": line_list[2].strip(), + "semantic_label": line_list[3].strip() if len(line_list) == 4 else "", + } new_list_file.write( f"{mapname}{fs}{row['start']}{fs}{row['end']}"