From e69d0cdd5f401695c837e069b287f70eae98f178 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Edouard=20Choini=C3=A8re?=
<27212526+echoix@users.noreply.github.com>
Date: Sun, 20 Oct 2024 20:13:28 +0000
Subject: [PATCH 01/12] style: Fix if-else-block-instead-of-if-exp (SIM108) in
scripts/
Ruff rule: https://docs.astral.sh/ruff/rules/if-else-block-instead-of-if-exp
---
scripts/d.rast.edit/d.rast.edit.py | 5 +----
scripts/d.rast.leg/d.rast.leg.py | 10 ++--------
scripts/db.droptable/db.droptable.py | 10 ++--------
scripts/db.out.ogr/db.out.ogr.py | 5 +----
scripts/db.univar/db.univar.py | 5 +----
scripts/g.extension/g.extension.py | 15 +++------------
scripts/g.manual/g.manual.py | 5 +----
scripts/i.in.spotvgt/i.in.spotvgt.py | 6 +-----
scripts/i.oif/i.oif.py | 10 ++--------
scripts/i.spectral/i.spectral.py | 5 +----
scripts/m.proj/m.proj.py | 10 ++--------
scripts/r.buffer.lowmem/r.buffer.lowmem.py | 5 +----
scripts/r.in.aster/r.in.aster.py | 5 +----
scripts/r.in.srtm/r.in.srtm.py | 5 +----
scripts/r.in.wms/wms_cap_parsers.py | 10 ++--------
scripts/r.in.wms/wms_drv.py | 5 +----
scripts/r.out.xyz/r.out.xyz.py | 5 +----
scripts/r.reclass.area/r.reclass.area.py | 5 +----
scripts/r.unpack/r.unpack.py | 5 +----
scripts/r3.in.xyz/r3.in.xyz.py | 10 ++--------
scripts/v.build.all/v.build.all.py | 5 +----
scripts/v.db.reconnect.all/v.db.reconnect.all.py | 5 +----
scripts/v.dissolve/tests/conftest.py | 5 +----
.../v.dissolve/tests/v_dissolve_aggregate_test.py | 10 ++--------
.../v.dissolve/tests/v_dissolve_layers_test.py | 5 +----
scripts/v.in.e00/v.in.e00.py | 5 +----
scripts/v.in.lines/v.in.lines.py | 7 +------
scripts/v.in.mapgen/v.in.mapgen.py | 10 ++--------
scripts/v.pack/v.pack.py | 5 +----
scripts/v.rast.stats/v.rast.stats.py | 15 +++------------
scripts/v.report/v.report.py | 5 +----
scripts/v.unpack/v.unpack.py | 15 +++------------
32 files changed, 46 insertions(+), 187 deletions(-)
diff --git a/scripts/d.rast.edit/d.rast.edit.py b/scripts/d.rast.edit/d.rast.edit.py
index ea6cc1e46bf..3464941e825 100755
--- a/scripts/d.rast.edit/d.rast.edit.py
+++ b/scripts/d.rast.edit/d.rast.edit.py
@@ -295,10 +295,7 @@ def paint_cell(self, dc, r, c):
px, py = -dy, dx
r, g, b, a = wx.Colour(fill).Get()
- if r + g + b > 384:
- line = "black"
- else:
- line = "white"
+ line = "black" if r + g + b > 384 else "white"
dc.SetPen(wx.Pen(line))
dc.DrawLine(x0, y0, x1, y1)
diff --git a/scripts/d.rast.leg/d.rast.leg.py b/scripts/d.rast.leg/d.rast.leg.py
index 85cb423f9e9..74576113577 100755
--- a/scripts/d.rast.leg/d.rast.leg.py
+++ b/scripts/d.rast.leg/d.rast.leg.py
@@ -132,16 +132,10 @@ def main():
if not nlines:
nlines = None
- if rast:
- lmap = rast
- else:
- lmap = map
+ lmap = rast or map
kv = gs.raster_info(map=lmap)
- if kv["datatype"] == "CELL":
- leg_at = None
- else:
- leg_at = "%f,95,5,10" % VSpacing
+ leg_at = None if kv["datatype"] == "CELL" else "%f,95,5,10" % VSpacing
# checking for histogram causes more problems than it solves
# histfiledir = grass.find_file(lmap, 'cell_misc')['file']
diff --git a/scripts/db.droptable/db.droptable.py b/scripts/db.droptable/db.droptable.py
index 571638748cf..39408221acc 100755
--- a/scripts/db.droptable/db.droptable.py
+++ b/scripts/db.droptable/db.droptable.py
@@ -56,14 +56,8 @@ def main():
gs.run_command("db.connect", flags="c", quiet=True)
kv = gs.db_connection()
- if options["database"]:
- database = options["database"]
- else:
- database = kv["database"]
- if options["driver"]:
- driver = options["driver"]
- else:
- driver = kv["driver"]
+ database = options["database"] or kv["database"]
+ driver = options["driver"] or kv["driver"]
# schema needed for PG?
if force:
diff --git a/scripts/db.out.ogr/db.out.ogr.py b/scripts/db.out.ogr/db.out.ogr.py
index 4a840755b20..4fdfed23648 100755
--- a/scripts/db.out.ogr/db.out.ogr.py
+++ b/scripts/db.out.ogr/db.out.ogr.py
@@ -72,10 +72,7 @@ def main():
if format.lower() == "dbf":
format = "ESRI_Shapefile"
- if format.lower() == "csv":
- olayer = basename(output, "csv")
- else:
- olayer = None
+ olayer = basename(output, "csv") if format.lower() == "csv" else None
# is there a simpler way of testing for --overwrite?
dbffile = input + ".dbf"
diff --git a/scripts/db.univar/db.univar.py b/scripts/db.univar/db.univar.py
index 97dfbdb7dbe..4654e3011a0 100755
--- a/scripts/db.univar/db.univar.py
+++ b/scripts/db.univar/db.univar.py
@@ -118,10 +118,7 @@ def main():
perc = [float(p) for p in perc.split(",")]
if not output_format:
- if shellstyle:
- output_format = "shell"
- else:
- output_format = "plain"
+ output_format = "shell" if shellstyle else "plain"
elif shellstyle:
# This can be a message or warning in future versions.
# In version 9, -g may be removed.
diff --git a/scripts/g.extension/g.extension.py b/scripts/g.extension/g.extension.py
index 194f498d49c..f14a742ca06 100644
--- a/scripts/g.extension/g.extension.py
+++ b/scripts/g.extension/g.extension.py
@@ -1608,10 +1608,7 @@ def install_extension_win(name):
source, url = resolve_source_code(url="{0}/{1}.zip".format(base_url, name))
# to hide non-error messages from subprocesses
- if gs.verbosity() <= 2:
- outdev = open(os.devnull, "w")
- else:
- outdev = sys.stdout
+ outdev = open(os.devnull, "w") if gs.verbosity() <= 2 else sys.stdout
# download Addons ZIP file
os.chdir(TMPDIR) # this is just to not leave something behind
@@ -1961,10 +1958,7 @@ def install_extension_std_platforms(name, source, url, branch):
path_to_src_code_message = _("Path to the source code:")
# to hide non-error messages from subprocesses
- if gs.verbosity() <= 2:
- outdev = open(os.devnull, "w")
- else:
- outdev = sys.stdout
+ outdev = open(os.devnull, "w") if gs.verbosity() <= 2 else sys.stdout
os.chdir(TMPDIR) # this is just to not leave something behind
srcdir = os.path.join(TMPDIR, name)
@@ -2578,10 +2572,7 @@ def resolve_known_host_service(url, name, branch):
)
return None, None
if match:
- if not actual_start:
- actual_start = match["url_start"]
- else:
- actual_start = ""
+ actual_start = match["url_start"] if not actual_start else ""
if "branch" in match["url_end"]:
suffix = match["url_end"].format(
name=name,
diff --git a/scripts/g.manual/g.manual.py b/scripts/g.manual/g.manual.py
index f4ecf961076..345a6d1714a 100755
--- a/scripts/g.manual/g.manual.py
+++ b/scripts/g.manual/g.manual.py
@@ -132,10 +132,7 @@ def main():
elif flags["t"]:
special = "topics"
- if flags["m"]:
- start = start_man
- else:
- start = start_browser
+ start = start_man if flags["m"] else start_browser
entry = options["entry"]
gisbase = os.environ["GISBASE"]
diff --git a/scripts/i.in.spotvgt/i.in.spotvgt.py b/scripts/i.in.spotvgt/i.in.spotvgt.py
index cd744d4c252..666f3721761 100755
--- a/scripts/i.in.spotvgt/i.in.spotvgt.py
+++ b/scripts/i.in.spotvgt/i.in.spotvgt.py
@@ -136,11 +136,7 @@ def main():
spotdir = os.path.dirname(infile)
spotname = gs.basename(infile, "hdf")
-
- if rast:
- name = rast
- else:
- name = spotname
+ name = rast or spotname
if not gs.overwrite() and gs.find_file(name)["file"]:
gs.fatal(_("<%s> already exists. Aborting.") % name)
diff --git a/scripts/i.oif/i.oif.py b/scripts/i.oif/i.oif.py
index 0dabbe7cb38..cb156675927 100755
--- a/scripts/i.oif/i.oif.py
+++ b/scripts/i.oif/i.oif.py
@@ -90,10 +90,7 @@ def main():
stddev[band] = float(kv["stddev"])
else:
# run all bands in parallel
- if "WORKERS" in os.environ:
- workers = int(os.environ["WORKERS"])
- else:
- workers = len(bands)
+ workers = int(os.environ["WORKERS"]) if "WORKERS" in os.environ else len(bands)
proc = {}
pout = {}
@@ -142,10 +139,7 @@ def main():
_("The Optimum Index Factor analysis result (best combination shown first):")
)
- if shell:
- fmt = "%s,%s,%s:%.4f\n"
- else:
- fmt = "%s, %s, %s: %.4f\n"
+ fmt = "%s,%s,%s:%.4f\n" if shell else "%s, %s, %s: %.4f\n"
if not output or output == "-":
for v, p in oif:
diff --git a/scripts/i.spectral/i.spectral.py b/scripts/i.spectral/i.spectral.py
index 171eac7359c..07efd8af31f 100755
--- a/scripts/i.spectral/i.spectral.py
+++ b/scripts/i.spectral/i.spectral.py
@@ -136,10 +136,7 @@ def draw_gnuplot(what, xlabels, output, img_format, coord_legend):
cmd = []
for i, row in enumerate(what):
- if not coord_legend:
- title = "Pick " + str(i + 1)
- else:
- title = str(tuple(row[0:2]))
+ title = "Pick " + str(i + 1) if not coord_legend else str(tuple(row[0:2]))
x_datafile = os.path.join(tmp_dir, "data_%d" % i)
cmd.append(" '%s' title '%s'" % (x_datafile, title))
diff --git a/scripts/m.proj/m.proj.py b/scripts/m.proj/m.proj.py
index 4540b3dcd0a..a018606fff9 100755
--- a/scripts/m.proj/m.proj.py
+++ b/scripts/m.proj/m.proj.py
@@ -236,14 +236,8 @@ def main():
gcore.debug("output file=[%s]" % outfile)
# set up output style
- if not decimal:
- outfmt = ["-w5"]
- else:
- outfmt = ["-f", "%.8f"]
- if not copy_input:
- copyinp = []
- else:
- copyinp = ["-E"]
+ outfmt = ["-w5"] if not decimal else ["-f", "%.8f"]
+ copyinp = [] if not copy_input else ["-E"]
# do the conversion
# Convert cs2cs DMS format to GRASS DMS format:
diff --git a/scripts/r.buffer.lowmem/r.buffer.lowmem.py b/scripts/r.buffer.lowmem/r.buffer.lowmem.py
index 2916ad95e7d..8866c21faeb 100755
--- a/scripts/r.buffer.lowmem/r.buffer.lowmem.py
+++ b/scripts/r.buffer.lowmem/r.buffer.lowmem.py
@@ -92,10 +92,7 @@ def main():
s = gs.read_command("g.proj", flags="j")
kv = gs.parse_key_val(s)
- if kv["+proj"] == "longlat":
- metric = "geodesic"
- else:
- metric = "squared"
+ metric = "geodesic" if kv["+proj"] == "longlat" else "squared"
gs.run_command(
"r.grow.distance", input=input, metric=metric, distance=temp_dist, flags="m"
diff --git a/scripts/r.in.aster/r.in.aster.py b/scripts/r.in.aster/r.in.aster.py
index 24722293dde..626d27e7976 100755
--- a/scripts/r.in.aster/r.in.aster.py
+++ b/scripts/r.in.aster/r.in.aster.py
@@ -152,10 +152,7 @@ def main():
# Band 3b is not included ASTER L1T
if proctype == "L1T":
allbands.remove("3b")
- if band == "all":
- bandlist = allbands
- else:
- bandlist = band.split(",")
+ bandlist = allbands if band == "all" else band.split(",")
# initialize datasets for L1A, L1B, L1T
if proctype in {"L1A", "L1B", "L1T"}:
diff --git a/scripts/r.in.srtm/r.in.srtm.py b/scripts/r.in.srtm/r.in.srtm.py
index 1e4c585ac02..b9f51415ca0 100755
--- a/scripts/r.in.srtm/r.in.srtm.py
+++ b/scripts/r.in.srtm/r.in.srtm.py
@@ -177,10 +177,7 @@ def main():
infile = infile[:-4]
(fdir, tile) = os.path.split(infile)
- if not output:
- tileout = tile
- else:
- tileout = output
+ tileout = output or tile
if ".hgt" in input:
suff = ".hgt"
diff --git a/scripts/r.in.wms/wms_cap_parsers.py b/scripts/r.in.wms/wms_cap_parsers.py
index 56b1d0ce48c..723a63f0b23 100644
--- a/scripts/r.in.wms/wms_cap_parsers.py
+++ b/scripts/r.in.wms/wms_cap_parsers.py
@@ -501,10 +501,7 @@ def _find(self, etreeElement, tag, ns=None):
"""!Find child element.
If the element is not found it raises xml.etree.ElementTree.ParseError.
"""
- if not ns:
- res = etreeElement.find(tag)
- else:
- res = etreeElement.find(ns(tag))
+ res = etreeElement.find(tag) if not ns else etreeElement.find(ns(tag))
if res is None:
raise ParseError(
@@ -521,10 +518,7 @@ def _findall(self, etreeElement, tag, ns=None):
"""!Find all children element.
If no element is found it raises xml.etree.ElementTree.ParseError.
"""
- if not ns:
- res = etreeElement.findall(tag)
- else:
- res = etreeElement.findall(ns(tag))
+ res = etreeElement.findall(tag) if not ns else etreeElement.findall(ns(tag))
if not res:
raise ParseError(
diff --git a/scripts/r.in.wms/wms_drv.py b/scripts/r.in.wms/wms_drv.py
index 531112a1a6c..e1131918c4a 100644
--- a/scripts/r.in.wms/wms_drv.py
+++ b/scripts/r.in.wms/wms_drv.py
@@ -995,10 +995,7 @@ def _parseTilePattern(self, group_t_patts, bbox, region):
res["y"] = (bbox["maxy"] - bbox["miny"]) / region["rows"]
res["x"] = (bbox["maxx"] - bbox["minx"]) / region["cols"]
- if res["x"] < res["y"]:
- comp_res = "x"
- else:
- comp_res = "y"
+ comp_res = "x" if res["x"] < res["y"] else "y"
t_res = {}
best_patt = None
diff --git a/scripts/r.out.xyz/r.out.xyz.py b/scripts/r.out.xyz/r.out.xyz.py
index ae8e04de4d6..6df97f3c202 100755
--- a/scripts/r.out.xyz/r.out.xyz.py
+++ b/scripts/r.out.xyz/r.out.xyz.py
@@ -48,10 +48,7 @@ def main():
output = options["output"]
donodata = flags["i"]
- if donodata:
- statsflags = "1g"
- else:
- statsflags = "1gn"
+ statsflags = "1g" if donodata else "1gn"
parameters = {
"flags": statsflags,
"input": options["input"],
diff --git a/scripts/r.reclass.area/r.reclass.area.py b/scripts/r.reclass.area/r.reclass.area.py
index 5d6fc1292bc..01e474659bc 100755
--- a/scripts/r.reclass.area/r.reclass.area.py
+++ b/scripts/r.reclass.area/r.reclass.area.py
@@ -152,10 +152,7 @@ def reclass(inf, outf, lim, clump, diag, les):
if len(f) < 5:
continue
hectares = float(f[4]) * 0.0001
- if lesser:
- test = hectares <= limit
- else:
- test = hectares >= limit
+ test = hectares <= limit if lesser else hectares >= limit
if test:
rules += "%s = %s %s\n" % (f[0], f[2], f[3])
if rules:
diff --git a/scripts/r.unpack/r.unpack.py b/scripts/r.unpack/r.unpack.py
index 575d465ebb5..dd595b4722b 100644
--- a/scripts/r.unpack/r.unpack.py
+++ b/scripts/r.unpack/r.unpack.py
@@ -92,10 +92,7 @@ def main():
return 0
- if options["output"]:
- map_name = options["output"]
- else:
- map_name = data_names[0].split("@")[0]
+ map_name = options["output"] or data_names[0].split("@")[0]
gfile = grass.find_file(name=map_name, element="cell", mapset=".")
if gfile["file"]:
diff --git a/scripts/r3.in.xyz/r3.in.xyz.py b/scripts/r3.in.xyz/r3.in.xyz.py
index b17d59506b7..5b2c8be4a65 100755
--- a/scripts/r3.in.xyz/r3.in.xyz.py
+++ b/scripts/r3.in.xyz/r3.in.xyz.py
@@ -226,10 +226,7 @@ def main():
addl_opts["flags"] = "i"
if scan_only or shell_style:
- if shell_style:
- doShell = "g"
- else:
- doShell = ""
+ doShell = "g" if shell_style else ""
grass.run_command(
"r.in.xyz",
flags="s" + doShell,
@@ -243,10 +240,7 @@ def main():
)
sys.exit()
- if dtype == "float":
- data_type = "FCELL"
- else:
- data_type = "DCELL"
+ data_type = "FCELL" if dtype == "float" else "DCELL"
region = grass.region(region3d=True)
diff --git a/scripts/v.build.all/v.build.all.py b/scripts/v.build.all/v.build.all.py
index 69b0837209f..8691ecddc32 100755
--- a/scripts/v.build.all/v.build.all.py
+++ b/scripts/v.build.all/v.build.all.py
@@ -31,10 +31,7 @@ def main():
vectors = grass.list_grouped("vect")[mapset]
num_vectors = len(vectors)
- if grass.verbosity() < 2:
- quiet = True
- else:
- quiet = False
+ quiet = grass.verbosity() < 2
i = 1
for vect in vectors:
diff --git a/scripts/v.db.reconnect.all/v.db.reconnect.all.py b/scripts/v.db.reconnect.all/v.db.reconnect.all.py
index b42b8006673..9a9d46356a9 100755
--- a/scripts/v.db.reconnect.all/v.db.reconnect.all.py
+++ b/scripts/v.db.reconnect.all/v.db.reconnect.all.py
@@ -255,10 +255,7 @@ def main():
schema = ""
table = schema_table
- if new_schema:
- new_schema_table = "%s.%s" % (new_schema, table)
- else:
- new_schema_table = table
+ new_schema_table = "%s.%s" % (new_schema, table) if new_schema else table
gs.debug(
"DATABASE = '%s' SCHEMA = '%s' TABLE = '%s' ->\n"
diff --git a/scripts/v.dissolve/tests/conftest.py b/scripts/v.dissolve/tests/conftest.py
index 9b069330488..e5e9a38818d 100644
--- a/scripts/v.dissolve/tests/conftest.py
+++ b/scripts/v.dissolve/tests/conftest.py
@@ -13,10 +13,7 @@
def updates_as_transaction(table, cat_column, column, column_quote, cats, values):
"""Create SQL statement for categories and values for a given column"""
sql = ["BEGIN TRANSACTION"]
- if column_quote:
- quote = "'"
- else:
- quote = ""
+ quote = "'" if column_quote else ""
for cat, value in zip(cats, values):
sql.append(
f"UPDATE {table} SET {column} = {quote}{value}{quote} "
diff --git a/scripts/v.dissolve/tests/v_dissolve_aggregate_test.py b/scripts/v.dissolve/tests/v_dissolve_aggregate_test.py
index 68ca178b864..90dc3de075e 100644
--- a/scripts/v.dissolve/tests/v_dissolve_aggregate_test.py
+++ b/scripts/v.dissolve/tests/v_dissolve_aggregate_test.py
@@ -101,10 +101,7 @@ def test_aggregate_column_result(dataset, backend):
for stats_column in stats_columns:
assert stats_column in columns
column_info = columns[stats_column]
- if stats_column.endswith("_n"):
- correct_type = "integer"
- else:
- correct_type = "double precision"
+ correct_type = "integer" if stats_column.endswith("_n") else "double precision"
assert (
columns[stats_column]["type"].lower() == correct_type
), f"{stats_column} has a wrong type"
@@ -221,10 +218,7 @@ def test_sqlite_agg_accepted(dataset):
for method, stats_column in zip(stats, expected_stats_columns):
assert stats_column in columns
column_info = columns[stats_column]
- if method == "count":
- correct_type = "integer"
- else:
- correct_type = "double precision"
+ correct_type = "integer" if method == "count" else "double precision"
assert (
columns[stats_column]["type"].lower() == correct_type
), f"{stats_column} has a wrong type"
diff --git a/scripts/v.dissolve/tests/v_dissolve_layers_test.py b/scripts/v.dissolve/tests/v_dissolve_layers_test.py
index 702aa8f8496..f6986d35917 100644
--- a/scripts/v.dissolve/tests/v_dissolve_layers_test.py
+++ b/scripts/v.dissolve/tests/v_dissolve_layers_test.py
@@ -50,10 +50,7 @@ def test_layer_2(dataset_layer_2):
for method, stats_column in zip(stats, expected_stats_columns):
assert stats_column in columns
column_info = columns[stats_column]
- if method == "count":
- correct_type = "integer"
- else:
- correct_type = "double precision"
+ correct_type = "integer" if method == "count" else "double precision"
assert (
columns[stats_column]["type"].lower() == correct_type
), f"{stats_column} has a wrong type"
diff --git a/scripts/v.in.e00/v.in.e00.py b/scripts/v.in.e00/v.in.e00.py
index 4d63636199f..4258fa3181a 100755
--- a/scripts/v.in.e00/v.in.e00.py
+++ b/scripts/v.in.e00/v.in.e00.py
@@ -86,10 +86,7 @@ def main():
)
merging = True
- if vect:
- name = vect
- else:
- name = e00name
+ name = vect or e00name
# do import
diff --git a/scripts/v.in.lines/v.in.lines.py b/scripts/v.in.lines/v.in.lines.py
index 44112b297a3..35991988f6b 100755
--- a/scripts/v.in.lines/v.in.lines.py
+++ b/scripts/v.in.lines/v.in.lines.py
@@ -50,12 +50,7 @@ def main():
fs = separator(options["separator"])
threeD = flags["z"]
-
- if threeD:
- do3D = "z"
- else:
- do3D = ""
-
+ do3D = "z" if threeD else ""
tmp = grass.tempfile()
# set up input file
diff --git a/scripts/v.in.mapgen/v.in.mapgen.py b/scripts/v.in.mapgen/v.in.mapgen.py
index 404fb7ec6b2..efe7af1075d 100755
--- a/scripts/v.in.mapgen/v.in.mapgen.py
+++ b/scripts/v.in.mapgen/v.in.mapgen.py
@@ -73,18 +73,12 @@ def main():
if not os.path.isfile(infile):
grass.fatal(_("Input file <%s> not found") % infile)
- if output:
- name = output
- else:
- name = ""
+ name = output or ""
if threeD:
matlab = True
- if threeD:
- do3D = "z"
- else:
- do3D = ""
+ do3D = "z" if threeD else ""
tmp = grass.tempfile()
diff --git a/scripts/v.pack/v.pack.py b/scripts/v.pack/v.pack.py
index 4468c888bcb..e39d52dbafe 100755
--- a/scripts/v.pack/v.pack.py
+++ b/scripts/v.pack/v.pack.py
@@ -73,10 +73,7 @@ def main():
infile = infile.split("@")[0]
# output name
- if options["output"]:
- outfile = options["output"]
- else:
- outfile = infile + ".pack"
+ outfile = options["output"] or infile + ".pack"
# check if exists the output file
if os.path.exists(outfile):
diff --git a/scripts/v.rast.stats/v.rast.stats.py b/scripts/v.rast.stats/v.rast.stats.py
index 803fc8691ad..4096aa49caf 100644
--- a/scripts/v.rast.stats/v.rast.stats.py
+++ b/scripts/v.rast.stats/v.rast.stats.py
@@ -116,10 +116,7 @@ def main():
# Get mapset of the vector
vs = vector.split("@")
- if len(vs) > 1:
- vect_mapset = vs[1]
- else:
- vect_mapset = mapset
+ vect_mapset = vs[1] if len(vs) > 1 else mapset
# does map exist in CURRENT mapset?
if vect_mapset != mapset or not gs.find_file(vector, "vector", mapset)["file"]:
@@ -373,10 +370,7 @@ def set_up_columns(vector, layer, percentile, colprefix, basecols, dbfdriver, c)
perc = b
if perc:
# namespace is limited in DBF but the % value is important
- if dbfdriver:
- perccol = "per" + percentile
- else:
- perccol = "percentile_" + percentile
+ perccol = "per" + percentile if dbfdriver else "percentile_" + percentile
percindex = basecols.index(perc)
basecols[percindex] = perccol
@@ -424,10 +418,7 @@ def set_up_columns(vector, layer, percentile, colprefix, basecols, dbfdriver, c)
+ _("Use -c flag to update values in this column.")
)
else:
- if i == "n":
- coltype = "INTEGER"
- else:
- coltype = "DOUBLE PRECISION"
+ coltype = "INTEGER" if i == "n" else "DOUBLE PRECISION"
addcols.append(currcolumn + " " + coltype)
if addcols:
diff --git a/scripts/v.report/v.report.py b/scripts/v.report/v.report.py
index cec84582155..29d9d3c914e 100755
--- a/scripts/v.report/v.report.py
+++ b/scripts/v.report/v.report.py
@@ -91,10 +91,7 @@ def main():
isConnection = False
colnames = ["cat"]
- if option == "coor":
- extracolnames = ["x", "y", "z"]
- else:
- extracolnames = [option]
+ extracolnames = ["x", "y", "z"] if option == "coor" else [option]
if units == "percent":
unitsp = "meters"
diff --git a/scripts/v.unpack/v.unpack.py b/scripts/v.unpack/v.unpack.py
index ea75d443b57..c3a7a55deb7 100644
--- a/scripts/v.unpack/v.unpack.py
+++ b/scripts/v.unpack/v.unpack.py
@@ -93,10 +93,7 @@ def main():
return 0
# set the output name
- if options["output"]:
- map_name = options["output"]
- else:
- map_name = data_name
+ map_name = options["output"] or data_name
# grass env
gisenv = grass.gisenv()
@@ -233,19 +230,13 @@ def main():
# for each old connection
for t in dbnlist:
# it split the line of each connection, to found layer number and key
- if len(t.split("|")) != 1:
- values = t.split("|")
- else:
- values = t.split(" ")
+ values = t.split("|") if len(t.split("|")) != 1 else t.split(" ")
from_table = values[1]
layer = values[0].split("/")[0]
# we need to take care about the table name in case of several layer
if options["output"]:
- if len(dbnlist) > 1:
- to_table = "%s_%s" % (map_name, layer)
- else:
- to_table = map_name
+ to_table = "%s_%s" % (map_name, layer) if len(dbnlist) > 1 else map_name
else:
to_table = from_table
From f63d3daf527e3aad1565a1b757d78e214b9d047b Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Edouard=20Choini=C3=A8re?=
<27212526+echoix@users.noreply.github.com>
Date: Sun, 20 Oct 2024 20:51:18 +0000
Subject: [PATCH 02/12] style: Fix if-else-block-instead-of-if-exp (SIM108) in
python/
Ruff rule: https://docs.astral.sh/ruff/rules/if-else-block-instead-of-if-exp
---
python/grass/app/runtime.py | 10 +----
python/grass/benchmark/app.py | 6 +--
python/grass/benchmark/plots.py | 10 +----
python/grass/gunittest/case.py | 5 +--
python/grass/gunittest/invoker.py | 5 +--
python/grass/gunittest/multireport.py | 5 +--
python/grass/gunittest/reporters.py | 15 ++------
python/grass/jupyter/map3d.py | 5 +--
python/grass/pydispatch/signal.py | 7 +---
.../pygrass/modules/interface/parameter.py | 5 +--
python/grass/pygrass/vector/__init__.py | 5 +--
python/grass/pygrass/vector/geometry.py | 5 +--
python/grass/pygrass/vector/table.py | 5 +--
python/grass/script/core.py | 15 ++------
python/grass/script/raster.py | 5 +--
python/grass/script/task.py | 10 +----
.../data/script_using_temporary_region.py | 10 +----
python/grass/script/utils.py | 20 ++--------
python/grass/script/vector.py | 10 +----
python/grass/temporal/abstract_map_dataset.py | 5 +--
.../temporal/abstract_space_time_dataset.py | 10 +----
.../grass/temporal/c_libraries_interface.py | 11 +-----
python/grass/temporal/datetime_math.py | 15 ++------
python/grass/temporal/gui_support.py | 5 +--
python/grass/temporal/list_stds.py | 5 +--
python/grass/temporal/register.py | 10 +----
python/grass/temporal/sampling.py | 17 ++-------
python/grass/temporal/temporal_algebra.py | 37 ++++---------------
.../temporal/temporal_raster_base_algebra.py | 5 +--
python/grass/temporal/univar_statistics.py | 5 +--
30 files changed, 57 insertions(+), 226 deletions(-)
diff --git a/python/grass/app/runtime.py b/python/grass/app/runtime.py
index 3f3805c9dfd..27f35760b8f 100644
--- a/python/grass/app/runtime.py
+++ b/python/grass/app/runtime.py
@@ -79,10 +79,7 @@ def append_left_addon_paths(paths, config_dir, env):
# addons (base)
addon_base = env.get("GRASS_ADDON_BASE")
if not addon_base:
- if MACOS:
- name = "Addons"
- else:
- name = "addons"
+ name = "addons" if not MACOS else "Addons"
addon_base = os.path.join(config_dir, name)
env["GRASS_ADDON_BASE"] = addon_base
@@ -174,10 +171,7 @@ def set_python_path_variable(install_path, env):
"""Set PYTHONPATH to find GRASS Python package in subprocesses"""
path = env.get("PYTHONPATH")
etcpy = os.path.join(install_path, "etc", "python")
- if path:
- path = etcpy + os.pathsep + path
- else:
- path = etcpy
+ path = etcpy + os.pathsep + path if path else etcpy
env["PYTHONPATH"] = path
diff --git a/python/grass/benchmark/app.py b/python/grass/benchmark/app.py
index 09cdf3f9481..835fc0d544b 100644
--- a/python/grass/benchmark/app.py
+++ b/python/grass/benchmark/app.py
@@ -47,11 +47,7 @@ def join_results_cli(args):
def select_only(result):
return result.label == args.only
- if args.only:
- select_function = select_only
- else:
- select_function = None
-
+ select_function = select_only if args.only else None
results = join_results_from_files(
source_filenames=args.results,
prefixes=args.prefixes,
diff --git a/python/grass/benchmark/plots.py b/python/grass/benchmark/plots.py
index 9483fda9116..24afcbcfbae 100644
--- a/python/grass/benchmark/plots.py
+++ b/python/grass/benchmark/plots.py
@@ -25,10 +25,7 @@ def get_pyplot(to_file):
"""
import matplotlib as mpl # pylint: disable=import-outside-toplevel
- if to_file:
- backend = "agg"
- else:
- backend = None
+ backend = "agg" if to_file else None
if backend:
mpl.use(backend)
@@ -124,10 +121,7 @@ def num_cells_plot(results, filename=None, title=None, show_resolution=False):
x_ticks = set()
for result in results:
- if show_resolution:
- x = result.resolutions
- else:
- x = result.cells
+ x = result.resolutions if show_resolution else result.cells
x_ticks.update(x)
plt.plot(x, result.times, label=result.label)
if hasattr(result, "all_times"):
diff --git a/python/grass/gunittest/case.py b/python/grass/gunittest/case.py
index 1277ee542b5..bb9825eae47 100644
--- a/python/grass/gunittest/case.py
+++ b/python/grass/gunittest/case.py
@@ -691,10 +691,7 @@ def assertFileMd5(self, filename, md5, text=False, msg=None):
at the end of file (as for example, Git or PEP8 requires).
"""
self.assertFileExists(filename, msg=msg)
- if text:
- actual = text_file_md5(filename)
- else:
- actual = file_md5(filename)
+ actual = text_file_md5(filename) if text else file_md5(filename)
if actual != md5:
standardMsg = (
"File <{name}> does not have the right MD5 sum.\n"
diff --git a/python/grass/gunittest/invoker.py b/python/grass/gunittest/invoker.py
index 2fe9c898b8b..29b62830e25 100644
--- a/python/grass/gunittest/invoker.py
+++ b/python/grass/gunittest/invoker.py
@@ -54,10 +54,7 @@ def update_keyval_file(filename, module, returncode):
keyval["name"] = module.name
keyval["tested_dir"] = module.tested_dir
if "status" not in keyval.keys():
- if returncode is None or returncode:
- status = "failed"
- else:
- status = "passed"
+ status = "failed" if returncode is None or returncode else "passed"
keyval["status"] = status
keyval["returncode"] = returncode
keyval["test_file_authors"] = test_file_authors
diff --git a/python/grass/gunittest/multireport.py b/python/grass/gunittest/multireport.py
index c5f36a6e0db..5a0350f1786 100644
--- a/python/grass/gunittest/multireport.py
+++ b/python/grass/gunittest/multireport.py
@@ -119,10 +119,7 @@ def median(values):
smedian = median(successes)
smax = max(successes)
- if successes[-1] < smedian:
- color = "r"
- else:
- color = "g"
+ color = "r" if successes[-1] < smedian else "g"
# another possibility is to color according to the gradient, ideally
# on the whole curve but that's much more complicated
diff --git a/python/grass/gunittest/reporters.py b/python/grass/gunittest/reporters.py
index 09f371dfffc..8c6823d9af5 100644
--- a/python/grass/gunittest/reporters.py
+++ b/python/grass/gunittest/reporters.py
@@ -487,10 +487,7 @@ def tail(filename, n):
def returncode_to_html_text(returncode, timed_out=None):
if returncode:
- if timed_out is not None:
- extra = f" (timeout >{timed_out}s)"
- else:
- extra = ""
+ extra = f" (timeout >{timed_out}s)" if timed_out is not None else ""
return f'FAILED{extra}'
# alternatives: SUCCEEDED, passed, OK
return 'succeeded'
@@ -857,10 +854,7 @@ def finish(self):
# this shoul be moved to some additional meta passed in constructor
svn_info = get_svn_info()
- if not svn_info:
- svn_revision = ""
- else:
- svn_revision = svn_info["revision"]
+ svn_revision = "" if not svn_info else svn_info["revision"]
summary = {}
summary["files_total"] = self.test_files
@@ -1025,10 +1019,7 @@ def end_file_test(
num_failed = test_summary.get("failures", 0)
num_failed += test_summary.get("errors", 0)
if num_failed:
- if num_failed > 1:
- text = " ({f} tests failed)"
- else:
- text = " ({f} test failed)"
+ text = " ({f} tests failed)" if num_failed > 1 else " ({f} test failed)"
self._stream.write(text.format(f=num_failed))
self._stream.write("\n")
# TODO: here we lost the possibility to include also file name
diff --git a/python/grass/jupyter/map3d.py b/python/grass/jupyter/map3d.py
index dd373f315a7..99253251406 100644
--- a/python/grass/jupyter/map3d.py
+++ b/python/grass/jupyter/map3d.py
@@ -210,10 +210,7 @@ def render(self, **kwargs):
with Display(
size=(self._width, self._height), **additional_kwargs
) as display:
- if has_env_copy:
- env = display.env()
- else:
- env = os.environ.copy()
+ env = display.env() if has_env_copy else os.environ.copy()
self._region_manager.set_region_from_command(env=env, **kwargs)
self.overlay.region_manager.set_region_from_env(env)
gs.run_command(module, env=env, **kwargs)
diff --git a/python/grass/pydispatch/signal.py b/python/grass/pydispatch/signal.py
index 1e968e99dca..51808e01ee3 100644
--- a/python/grass/pydispatch/signal.py
+++ b/python/grass/pydispatch/signal.py
@@ -7,7 +7,7 @@
from grass.pydispatch import dispatcher
-def _islambda(function):
+def _islambda(function) -> bool:
"""
Tests if object is a lambda function.
@@ -146,10 +146,7 @@ class connects to the signal::
will print
"""
if weak is None:
- if _islambda(handler):
- weak = False
- else:
- weak = True
+ weak = not _islambda(handler)
dispatcher.connect(receiver=handler, signal=self, weak=weak)
def disconnect(self, handler, weak=True):
diff --git a/python/grass/pygrass/modules/interface/parameter.py b/python/grass/pygrass/modules/interface/parameter.py
index 3b58ea2b372..1ec5466bc74 100644
--- a/python/grass/pygrass/modules/interface/parameter.py
+++ b/python/grass/pygrass/modules/interface/parameter.py
@@ -337,10 +337,7 @@ def __doc__(self):
..
"""
if hasattr(self, "values"):
- if self.isrange:
- vals = self.isrange
- else:
- vals = ", ".join([repr(val) for val in self.values])
+ vals = self.isrange or ", ".join([repr(val) for val in self.values])
else:
vals = False
if self.keydescvalues:
diff --git a/python/grass/pygrass/vector/__init__.py b/python/grass/pygrass/vector/__init__.py
index 461050807b0..6723b2e44b3 100644
--- a/python/grass/pygrass/vector/__init__.py
+++ b/python/grass/pygrass/vector/__init__.py
@@ -859,10 +859,7 @@ def features_to_wkb_list(self, bbox=None, feature_type="point", field=1):
ok = libvect.Vect_cat_get(
ctypes.byref(line_c), field, ctypes.byref(cat)
)
- if ok < 1:
- pcat = None
- else:
- pcat = cat.value
+ pcat = None if ok < 1 else cat.value
wkb_list.append((f_id, pcat, ctypes.string_at(barray, size.value)))
libgis.G_free(barray)
diff --git a/python/grass/pygrass/vector/geometry.py b/python/grass/pygrass/vector/geometry.py
index 10ecb1d2d13..b734161d1ea 100644
--- a/python/grass/pygrass/vector/geometry.py
+++ b/python/grass/pygrass/vector/geometry.py
@@ -810,10 +810,7 @@ def extend(self, line, forward=True):
"""
# set direction
- if forward:
- direction = libvect.GV_FORWARD
- else:
- direction = libvect.GV_BACKWARD
+ direction = libvect.GV_FORWARD if forward else libvect.GV_BACKWARD
# check if is a Line object
if isinstance(line, Line):
c_points = line.c_points
diff --git a/python/grass/pygrass/vector/table.py b/python/grass/pygrass/vector/table.py
index 9c8d0c3f9a2..5442d2f1e51 100644
--- a/python/grass/pygrass/vector/table.py
+++ b/python/grass/pygrass/vector/table.py
@@ -1261,10 +1261,7 @@ def create(self, cols, name=None, overwrite=False, cursor=None):
"""
cur = cursor or self.conn.cursor()
coldef = ",\n".join(["%s %s" % col for col in cols])
- if name:
- newname = name
- else:
- newname = self.name
+ newname = name or self.name
try:
cur.execute(sql.CREATE_TAB.format(tname=newname, coldef=coldef))
self.conn.commit()
diff --git a/python/grass/script/core.py b/python/grass/script/core.py
index 4f70f525133..0b51e7fdbe9 100644
--- a/python/grass/script/core.py
+++ b/python/grass/script/core.py
@@ -334,10 +334,7 @@ def get_module_and_code(args, kwargs):
args = make_command(*args, **kwargs)
# Since we are in error handler, let's be extra cautious
# about an empty command.
- if args:
- module = args[0]
- else:
- module = None
+ module = args[0] if args else None
code = " ".join(args)
return module, code
@@ -1699,10 +1696,7 @@ def mapsets(search_path=False, env=None):
:return: list of mapsets
"""
- if search_path:
- flags = "p"
- else:
- flags = "l"
+ flags = "p" if search_path else "l"
mapsets = read_command("g.mapsets", flags=flags, sep="newline", quiet=True, env=env)
if not mapsets:
fatal(_("Unable to list mapsets"))
@@ -2033,10 +2027,7 @@ def create_environment(gisdbase, location, mapset, env=None):
f.write("GISDBASE: {g}\n".format(g=gisdbase))
f.write("LOCATION_NAME: {l}\n".format(l=location))
f.write("GUI: text\n")
- if env:
- env = env.copy()
- else:
- env = os.environ.copy()
+ env = env.copy() if env else os.environ.copy()
env["GISRC"] = f.name
# remove mapset-specific env vars
env = sanitize_mapset_environment(env)
diff --git a/python/grass/script/raster.py b/python/grass/script/raster.py
index 54c1219dbaf..d82780d7c5c 100644
--- a/python/grass/script/raster.py
+++ b/python/grass/script/raster.py
@@ -218,10 +218,7 @@ def raster_what(map, coord, env=None, localized=False):
query
:param env:
"""
- if isinstance(map, (bytes, str)):
- map_list = [map]
- else:
- map_list = map
+ map_list = [map] if isinstance(map, (bytes, str)) else map
coord_list = []
if isinstance(coord, tuple):
diff --git a/python/grass/script/task.py b/python/grass/script/task.py
index cf398c59214..9867b3d8c49 100644
--- a/python/grass/script/task.py
+++ b/python/grass/script/task.py
@@ -345,14 +345,8 @@ def _process_params(self):
for ki in node_key_desc.findall("item"):
key_desc.append(ki.text)
- if p.get("multiple", "no") == "yes":
- multiple = True
- else:
- multiple = False
- if p.get("required", "no") == "yes":
- required = True
- else:
- required = False
+ multiple = p.get("multiple", "no") == "yes"
+ required = p.get("required", "no") == "yes"
if (
self.task.blackList["enabled"]
diff --git a/python/grass/script/testsuite/data/script_using_temporary_region.py b/python/grass/script/testsuite/data/script_using_temporary_region.py
index 5bb5a4cda26..839bf3d0a72 100755
--- a/python/grass/script/testsuite/data/script_using_temporary_region.py
+++ b/python/grass/script/testsuite/data/script_using_temporary_region.py
@@ -65,15 +65,9 @@ def main():
argument = sys.argv[1]
sizes = argument.split(",", 1)
size = sizes[0]
- if len(sizes) > 1:
- remaining = sizes[1]
- else:
- remaining = None
+ remaining = sizes[1] if len(sizes) > 1 else None
nesting = int(sys.argv[2])
- if len(sys.argv) == 4:
- map_name = sys.argv[3]
- else:
- map_name = None
+ map_name = sys.argv[3] if len(sys.argv) == 4 else None
call_use_temp_region(
script=this_file,
size=size,
diff --git a/python/grass/script/utils.py b/python/grass/script/utils.py
index 448289b57aa..25eb70190c5 100644
--- a/python/grass/script/utils.py
+++ b/python/grass/script/utils.py
@@ -190,10 +190,7 @@ def decode(bytes_, encoding=None):
if isinstance(bytes_, str):
return bytes_
if isinstance(bytes_, bytes):
- if encoding is None:
- enc = _get_encoding()
- else:
- enc = encoding
+ enc = _get_encoding() if encoding is None else encoding
return bytes_.decode(enc)
# only text should be used
raise TypeError("can only accept types str and bytes")
@@ -221,10 +218,7 @@ def encode(string, encoding=None):
if isinstance(string, bytes):
return string
if isinstance(string, str):
- if encoding is None:
- enc = _get_encoding()
- else:
- enc = encoding
+ enc = _get_encoding() if encoding is None else encoding
return string.encode(enc)
# if something else than text
raise TypeError("can only accept types str and bytes")
@@ -276,10 +270,7 @@ def parse_key_val(s, sep="=", dflt=None, val_type=None, vsep=None):
for line in lines:
kv = line.split(sep, 1)
k = decode(kv[0].strip())
- if len(kv) > 1:
- v = decode(kv[1].strip())
- else:
- v = dflt
+ v = decode(kv[1].strip()) if len(kv) > 1 else dflt
if val_type:
result[k] = val_type(v)
@@ -353,10 +344,7 @@ def convert(text):
return int(text) if text.isdigit() else text.lower()
def alphanum_key(actual_key):
- if key:
- sort_key = key(actual_key)
- else:
- sort_key = actual_key
+ sort_key = key(actual_key) if key else actual_key
return [convert(c) for c in re.split("([0-9]+)", sort_key)]
items.sort(key=alphanum_key)
diff --git a/python/grass/script/vector.py b/python/grass/script/vector.py
index ca3caf18471..2d484f7d590 100644
--- a/python/grass/script/vector.py
+++ b/python/grass/script/vector.py
@@ -129,10 +129,7 @@ def vector_columns(map, layer=None, getDict=True, env=None, **kwargs):
s = read_command(
"v.info", flags="c", map=map, layer=layer, quiet=True, env=env, **kwargs
)
- if getDict:
- result = {}
- else:
- result = []
+ result = {} if getDict else []
i = 0
for line in s.splitlines():
ctype, cname = line.split("|")
@@ -377,10 +374,7 @@ def vector_what(
if "LC_ALL" in env:
env["LC_ALL"] = "C"
- if isinstance(map, (bytes, str)):
- map_list = [map]
- else:
- map_list = map
+ map_list = [map] if isinstance(map, (bytes, str)) else map
if layer:
if isinstance(layer, (tuple, list)):
diff --git a/python/grass/temporal/abstract_map_dataset.py b/python/grass/temporal/abstract_map_dataset.py
index ecbf761d139..f6bec2bfef3 100644
--- a/python/grass/temporal/abstract_map_dataset.py
+++ b/python/grass/temporal/abstract_map_dataset.py
@@ -820,10 +820,7 @@ def temporal_buffer(self, increment, update=False, dbif=None):
else:
start, end, unit = self.get_relative_time()
new_start = start - increment
- if end is None:
- new_end = start + increment
- else:
- new_end = end + increment
+ new_end = start + increment if end is None else end + increment
if update:
self.update_relative_time(new_start, new_end, unit, dbif=dbif)
diff --git a/python/grass/temporal/abstract_space_time_dataset.py b/python/grass/temporal/abstract_space_time_dataset.py
index d17baaab6ae..8140a2da261 100644
--- a/python/grass/temporal/abstract_space_time_dataset.py
+++ b/python/grass/temporal/abstract_space_time_dataset.py
@@ -779,10 +779,7 @@ def sample_by_dataset(self, stds, method=None, spatial=False, dbif=None):
# print(relations)
tb = SpatioTemporalTopologyBuilder()
- if spatial:
- spatial = "2D"
- else:
- spatial = None
+ spatial = "2D" if spatial else None
mapsA = self.get_registered_maps_as_objects(dbif=dbif)
mapsB = stds.get_registered_maps_as_objects_with_gaps(dbif=dbif)
@@ -1429,10 +1426,7 @@ def get_registered_maps_as_objects_with_gaps(
start1, end1 = maps[i].get_temporal_extent_as_tuple()
start2, end2 = maps[i + 1].get_temporal_extent_as_tuple()
end = start2
- if end1 is not None:
- start = end1
- else:
- start = start1
+ start = end1 if end1 is not None else start1
map = self.get_new_map_instance(None)
diff --git a/python/grass/temporal/c_libraries_interface.py b/python/grass/temporal/c_libraries_interface.py
index 85a19a3ec6e..0d24fc0f732 100644
--- a/python/grass/temporal/c_libraries_interface.py
+++ b/python/grass/temporal/c_libraries_interface.py
@@ -256,11 +256,7 @@ def _get_driver_name(lock, conn, data):
:returns: Name of the driver or None if no temporal database present
"""
mapset = data[1]
- if not mapset:
- mapset = libgis.G_mapset()
- else:
- mapset = encode(mapset)
-
+ mapset = libgis.G_mapset() if not mapset else encode(mapset)
drstring = libtgis.tgis_get_mapset_driver_name(mapset)
conn.send(decode(drstring.data))
@@ -280,10 +276,7 @@ def _get_database_name(lock, conn, data):
dbstring = None
try:
mapset = data[1]
- if not mapset:
- mapset = libgis.G_mapset()
- else:
- mapset = encode(mapset)
+ mapset = libgis.G_mapset() if not mapset else encode(mapset)
dbstring = libtgis.tgis_get_mapset_database_name(mapset)
dbstring = dbstring.data
diff --git a/python/grass/temporal/datetime_math.py b/python/grass/temporal/datetime_math.py
index 1031582fe23..b986637162a 100644
--- a/python/grass/temporal/datetime_math.py
+++ b/python/grass/temporal/datetime_math.py
@@ -694,10 +694,7 @@ def compute_datetime_delta(start, end):
else:
d += 24 * 60 * day_diff
elif d == 0:
- if comp["hour"]:
- d = 60 * comp["hour"]
- else:
- d = 24 * 60 * day_diff
+ d = 60 * comp["hour"] if comp["hour"] else 24 * 60 * day_diff
comp["minute"] = d
@@ -914,10 +911,7 @@ def datetime_to_grass_datetime_string(dt):
# Check for time zone info in the datetime object
if dt.tzinfo is not None:
tz = dt.tzinfo.utcoffset(0)
- if tz.seconds > 86400 / 2:
- tz = (tz.seconds - 86400) / 60
- else:
- tz = tz.seconds / 60
+ tz = (tz.seconds - 86400) / 60 if tz.seconds > 86400 / 2 else tz.seconds / 60
string = "%.2i %s %.2i %.2i:%.2i:%.2i %+.4i" % (
dt.day,
@@ -999,10 +993,7 @@ def create_numeric_suffix(base, count, zeros):
if len(spli) == 2:
suff = spli[1]
if suff.isdigit():
- if int(suff[0]) == 0:
- zero = suff
- else:
- zero = "0{nu}".format(nu=suff)
+ zero = suff if int(suff[0]) == 0 else "0{nu}".format(nu=suff)
else:
zero = "05"
else:
diff --git a/python/grass/temporal/gui_support.py b/python/grass/temporal/gui_support.py
index 41f22edc6b7..84adf260ea6 100644
--- a/python/grass/temporal/gui_support.py
+++ b/python/grass/temporal/gui_support.py
@@ -40,10 +40,7 @@ def tlist_grouped(type, group_type=False, dbif=None):
dbif, connection_state_changed = init_dbif(dbif)
mapset = None
- if type == "stds":
- types = ["strds", "str3ds", "stvds"]
- else:
- types = [type]
+ types = ["strds", "str3ds", "stvds"] if type == "stds" else [type]
for type in types:
try:
tlist_result = tlist(type=type, dbif=dbif)
diff --git a/python/grass/temporal/list_stds.py b/python/grass/temporal/list_stds.py
index 9f6b6867766..22a2708123d 100644
--- a/python/grass/temporal/list_stds.py
+++ b/python/grass/temporal/list_stds.py
@@ -325,10 +325,7 @@ def _get_get_registered_maps_as_objects_delta_gran(
msgr.fatal(_("Empty entry in map list, this should not happen"))
start, end = map_object.get_temporal_extent_as_tuple()
- if end:
- delta = end - start
- else:
- delta = None
+ delta = end - start if end else None
delta_first = start - first_time
if map_object.is_time_absolute():
diff --git a/python/grass/temporal/register.py b/python/grass/temporal/register.py
index 92be36a3547..d8705765d02 100644
--- a/python/grass/temporal/register.py
+++ b/python/grass/temporal/register.py
@@ -158,10 +158,7 @@ def register_maps_in_space_time_dataset(
# Read the map list from file
if file:
- if hasattr(file, "readline"):
- fd = file
- else:
- fd = open(file)
+ fd = file if hasattr(file, "readline") else open(file)
line = True
while True:
@@ -639,10 +636,7 @@ def register_map_object_list(
string = f"{id}|{start}|{end}\n"
register_file.write(string)
- if output_stds:
- output_stds_id = output_stds.get_id()
- else:
- output_stds_id = None
+ output_stds_id = output_stds.get_id() if output_stds else None
register_maps_in_space_time_dataset(
type, output_stds_id, unit=unit, file=filename, dbif=dbif
diff --git a/python/grass/temporal/sampling.py b/python/grass/temporal/sampling.py
index 425ca484da5..5209ce6a80c 100644
--- a/python/grass/temporal/sampling.py
+++ b/python/grass/temporal/sampling.py
@@ -82,19 +82,11 @@ def sample_stds_by_stds_topology(
sts = []
for input in inputs:
- if input.find("@") >= 0:
- id = input
- else:
- id = input + "@" + mapset
-
+ id = input if input.find("@") >= 0 else input + "@" + mapset
st = dataset_factory(intype, id)
sts.append(st)
- if sampler.find("@") >= 0:
- sid = sampler
- else:
- sid = sampler + "@" + mapset
-
+ sid = sampler if sampler.find("@") >= 0 else sampler + "@" + mapset
sst = dataset_factory(sampletype, sid)
dbif = SQLDatabaseInterfaceConnection()
@@ -156,10 +148,7 @@ def sample_stds_by_stds_topology(
map = entry["granule"]
start, end = map.get_temporal_extent_as_tuple()
- if end:
- delta = end - start
- else:
- delta = None
+ delta = end - start if end else None
delta_first = start - first_time
if map.is_time_absolute():
diff --git a/python/grass/temporal/temporal_algebra.py b/python/grass/temporal/temporal_algebra.py
index e4717eb3326..2429b61e35e 100644
--- a/python/grass/temporal/temporal_algebra.py
+++ b/python/grass/temporal/temporal_algebra.py
@@ -992,10 +992,7 @@ def generate_map_name(self):
same object for map name generation in multiple threads.
"""
self.count += 1
- if self.pid is not None:
- pid = self.pid
- else:
- pid = os.getpid()
+ pid = self.pid if self.pid is not None else os.getpid()
name = "tmp_map_name_%i_%i" % (pid, self.count)
self.names[name] = name
return name
@@ -1234,10 +1231,7 @@ def check_stds(self, input, clear=False, stds_type=None, check_type=True):
"""
if isinstance(input, str):
# Check for mapset in given stds input.
- if input.find("@") >= 0:
- id_input = input
- else:
- id_input = input + "@" + self.mapset
+ id_input = input if input.find("@") >= 0 else input + "@" + self.mapset
# Create empty spacetime dataset.
if stds_type:
stds = dataset_factory(stds_type, id_input)
@@ -1634,7 +1628,7 @@ def build_spatio_temporal_topology_list(
def assign_bool_value(
self, map_i, temporal_topo_list=["EQUAL"], spatial_topo_list=[]
- ):
+ ) -> bool:
"""Function to assign boolean map value based on the map_values from the
compared map list by topological relationships.
@@ -1668,10 +1662,7 @@ def assign_bool_value(
str(relationmap.get_temporal_extent_as_tuple())
+ str(boolean),
)
- if all(condition_value_list):
- resultbool = True
- else:
- resultbool = False
+ resultbool = bool(all(condition_value_list))
map_i.condition_value = [resultbool]
return resultbool
@@ -2296,20 +2287,14 @@ def recurse_compare(conditionlist):
ele_index = conditionlist.index(ele)
right = conditionlist.pop(ele_index)
left = conditionlist.pop(ele_index - 2)
- if any([left, right]):
- result = True
- else:
- result = False
+ result = bool(any([left, right]))
conditionlist[ele_index - 2] = result
recurse_compare(conditionlist)
if ele == "&&":
ele_index = conditionlist.index(ele)
right = conditionlist.pop(ele_index)
left = conditionlist.pop(ele_index - 2)
- if all([left, right]):
- result = True
- else:
- result = False
+ result = bool(all([left, right]))
conditionlist[ele_index - 2] = result
recurse_compare(conditionlist)
@@ -2643,10 +2628,7 @@ def p_expr_tmap_function(self, t):
input = t[3]
if not isinstance(input, list):
# Check for mapset in given stds input.
- if input.find("@") >= 0:
- id_input = input
- else:
- id_input = input + "@" + self.mapset
+ id_input = input if input.find("@") >= 0 else input + "@" + self.mapset
# Create empty map dataset.
map_i = dataset_factory(self.maptype, id_input)
# Check for occurrence of space time dataset.
@@ -3079,10 +3061,7 @@ def p_expr_t_select_operator(self, t):
# Evaluate temporal operator.
operators = self.eval_toperator(t[2], optype="select")
# Check for negative selection.
- if operators[2] == "!:":
- negation = True
- else:
- negation = False
+ negation = operators[2] == "!:"
# Perform selection.
selectlist = self.perform_temporal_selection(
maplistA, maplistB, topolist=operators[0], inverse=negation
diff --git a/python/grass/temporal/temporal_raster_base_algebra.py b/python/grass/temporal/temporal_raster_base_algebra.py
index 8ff156cbed5..cb2122f4a37 100644
--- a/python/grass/temporal/temporal_raster_base_algebra.py
+++ b/python/grass/temporal/temporal_raster_base_algebra.py
@@ -960,10 +960,7 @@ def p_expr_spmap_function(self, t):
input = t[3]
if not isinstance(input, list):
# Check for mapset in given stds input.
- if input.find("@") >= 0:
- id_input = input
- else:
- id_input = input + "@" + self.mapset
+ id_input = input if input.find("@") >= 0 else input + "@" + self.mapset
# Create empty map dataset.
map_i = dataset_factory(self.maptype, id_input)
# Check for occurrence of space time dataset.
diff --git a/python/grass/temporal/univar_statistics.py b/python/grass/temporal/univar_statistics.py
index dd334e7e9f1..b6a9c1ac508 100755
--- a/python/grass/temporal/univar_statistics.py
+++ b/python/grass/temporal/univar_statistics.py
@@ -304,10 +304,7 @@ def print_vector_dataset_univar_statistics(
mapset = get_current_mapset()
- if input.find("@") >= 0:
- id = input
- else:
- id = input + "@" + mapset
+ id = input if input.find("@") >= 0 else input + "@" + mapset
sp = dataset_factory("stvds", id)
From 0b81de1a8d5ad8d7f830ac70e5000a0d0bfdb65c Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Edouard=20Choini=C3=A8re?=
<27212526+echoix@users.noreply.github.com>
Date: Sun, 20 Oct 2024 21:02:02 +0000
Subject: [PATCH 03/12] checks: Rename inner variable shadowing type to _type
in python/grass/temporal/gui_support.py
---
python/grass/temporal/gui_support.py | 20 +++++++++++---------
1 file changed, 11 insertions(+), 9 deletions(-)
diff --git a/python/grass/temporal/gui_support.py b/python/grass/temporal/gui_support.py
index 84adf260ea6..d2cbca13d68 100644
--- a/python/grass/temporal/gui_support.py
+++ b/python/grass/temporal/gui_support.py
@@ -37,13 +37,14 @@ def tlist_grouped(type, group_type=False, dbif=None):
:return: directory of mapsets/elements
"""
result = {}
+ _type = type
dbif, connection_state_changed = init_dbif(dbif)
mapset = None
- types = ["strds", "str3ds", "stvds"] if type == "stds" else [type]
- for type in types:
+ types = ["strds", "str3ds", "stvds"] if _type == "stds" else [_type]
+ for _type in types:
try:
- tlist_result = tlist(type=type, dbif=dbif)
+ tlist_result = tlist(type=_type, dbif=dbif)
except gs.ScriptError as e:
gs.warning(e)
continue
@@ -62,10 +63,10 @@ def tlist_grouped(type, group_type=False, dbif=None):
result[mapset] = []
if group_type:
- if type in result[mapset]:
- result[mapset][type].append(name)
+ if _type in result[mapset]:
+ result[mapset][_type].append(name)
else:
- result[mapset][type] = [
+ result[mapset][_type] = [
name,
]
else:
@@ -87,19 +88,20 @@ def tlist(type, dbif=None):
:return: a list of space time dataset ids
"""
+ _type = type
id = None
- sp = dataset_factory(type, id)
+ sp = dataset_factory(_type, id)
dbif, connection_state_changed = init_dbif(dbif)
mapsets = get_available_temporal_mapsets()
output = []
temporal_type = ["absolute", "relative"]
- for type in temporal_type:
+ for _type in temporal_type:
# For each available mapset
for mapset in mapsets.keys():
# Table name
- if type == "absolute":
+ if _type == "absolute":
table = sp.get_type() + "_view_abs_time"
else:
table = sp.get_type() + "_view_rel_time"
From 897db7f8d7fe858028b3215a7d69c4d505bb20b9 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Edouard=20Choini=C3=A8re?=
<27212526+echoix@users.noreply.github.com>
Date: Sun, 20 Oct 2024 21:16:28 +0000
Subject: [PATCH 04/12] style: Manual fixes for if-else-block-instead-of-if-exp
(SIM108) in python/
Ruff rule: https://docs.astral.sh/ruff/rules/if-else-block-instead-of-if-exp
---
python/grass/exceptions/__init__.py | 10 +++-------
python/grass/gunittest/case.py | 9 +++------
python/grass/gunittest/reporters.py | 7 ++-----
python/grass/temporal/temporal_granularity.py | 9 +++------
4 files changed, 11 insertions(+), 24 deletions(-)
diff --git a/python/grass/exceptions/__init__.py b/python/grass/exceptions/__init__.py
index b22d0a45c1d..deec48ffd96 100644
--- a/python/grass/exceptions/__init__.py
+++ b/python/grass/exceptions/__init__.py
@@ -71,13 +71,9 @@ def __init__(self, module, code, returncode, errors=None):
"""
# CalledProcessError has undocumented constructor
super().__init__(returncode, module)
- if not module or module in code:
- # No need to include module name if it is directly in code
- # of if it is not set.
- executed = code
- else:
- # Make sure module name is there if provided and not in code.
- executed = f"{module} {code}"
+ # No need to include module name if it is directly in code of if it is not set.
+ # Otherwise, make sure module name is there if provided and not in code.
+ executed = code if not module or module in code else f"{module} {code}"
if errors:
# We assume actual errors, e.g., captured stderr.
err = _("See the following errors:\n{errors}").format(errors=errors)
diff --git a/python/grass/gunittest/case.py b/python/grass/gunittest/case.py
index bb9825eae47..4e0ee3ab24d 100644
--- a/python/grass/gunittest/case.py
+++ b/python/grass/gunittest/case.py
@@ -1336,12 +1336,9 @@ def runModule(cls, module, expecting_stdout=False, **kwargs):
errors = " The errors are:\n" + module.outputs.stderr
else:
errors = " There were no error messages."
- if module.outputs.stdout:
- # this is not appropriate for translation but we don't want
- # and don't need testing to be translated
- got = "only whitespace."
- else:
- got = "nothing."
+ # This is not appropriate for translation but we don't want
+ # and don't need testing to be translated
+ got = "only whitespace." if module.outputs.stdout else "nothing."
raise RuntimeError(
"Module call "
+ module.get_python()
diff --git a/python/grass/gunittest/reporters.py b/python/grass/gunittest/reporters.py
index 8c6823d9af5..57b0a8fc643 100644
--- a/python/grass/gunittest/reporters.py
+++ b/python/grass/gunittest/reporters.py
@@ -234,11 +234,8 @@ def get_svn_path_authors(path, from_date=None):
:returns: a set of authors
"""
- if from_date is None:
- # this is the SVN default for local copies
- revision_range = "BASE:1"
- else:
- revision_range = "BASE:{%s}" % from_date
+ # "BASE:1" is the SVN default for local copies
+ revision_range = "BASE:1" if from_date is None else "BASE:{%s}" % from_date
try:
# TODO: allow also usage of --limit
p = subprocess.Popen(
diff --git a/python/grass/temporal/temporal_granularity.py b/python/grass/temporal/temporal_granularity.py
index b4043054520..173e4e715ea 100644
--- a/python/grass/temporal/temporal_granularity.py
+++ b/python/grass/temporal/temporal_granularity.py
@@ -494,7 +494,7 @@ def compute_absolute_time_granularity(maps):
# Keep the temporal extent to compare to the following/next map
previous_start, previous_end = start, end
- # Create a list with a single time unit only
+ # Create a set with a single time unit only
dlist = set()
assigned_time_unit = None
time_unit_multipliers = {
@@ -529,11 +529,8 @@ def compute_absolute_time_granularity(maps):
if not dlist:
return None
- if len(dlist) > 1:
- # Find greatest common divisor
- granularity = gcd_list(dlist)
- else:
- granularity = dlist.pop()
+ # Find greatest common divisor to get a single time unit
+ granularity = gcd_list(dlist) if len(dlist) > 1 else dlist.pop()
if granularity is None:
return None
From 7282ffe80f4be6d9351a67d1e64488369cc24861 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Edouard=20Choini=C3=A8re?=
<27212526+echoix@users.noreply.github.com>
Date: Sun, 20 Oct 2024 22:16:23 +0000
Subject: [PATCH 05/12] style: Fix if-else-block-instead-of-if-exp (SIM108) in
gui/
Ruff rule: https://docs.astral.sh/ruff/rules/if-else-block-instead-of-if-exp
---
gui/wxpython/animation/dialogs.py | 5 +-
gui/wxpython/animation/frame.py | 17 ++----
gui/wxpython/animation/temporal_manager.py | 6 +--
gui/wxpython/core/gcmd.py | 5 +-
gui/wxpython/core/gconsole.py | 10 +---
gui/wxpython/core/menutree.py | 32 +++--------
gui/wxpython/core/render.py | 37 +++----------
gui/wxpython/core/settings.py | 5 +-
gui/wxpython/core/treemodel.py | 7 +--
gui/wxpython/core/utils.py | 5 +-
gui/wxpython/core/workspace.py | 15 ++----
gui/wxpython/datacatalog/tree.py | 5 +-
gui/wxpython/dbmgr/base.py | 37 +++----------
gui/wxpython/dbmgr/dialogs.py | 5 +-
gui/wxpython/dbmgr/sqlbuilder.py | 10 +---
gui/wxpython/gcp/manager.py | 21 ++------
gui/wxpython/gmodeler/dialogs.py | 16 ++----
gui/wxpython/gmodeler/model.py | 62 +++++-----------------
gui/wxpython/gmodeler/panels.py | 5 +-
gui/wxpython/gui_core/dialogs.py | 15 ++----
gui/wxpython/gui_core/forms.py | 41 +++-----------
gui/wxpython/gui_core/gselect.py | 27 ++--------
gui/wxpython/gui_core/menu.py | 5 +-
gui/wxpython/gui_core/preferences.py | 5 +-
gui/wxpython/gui_core/prompt.py | 5 +-
gui/wxpython/gui_core/treeview.py | 5 +-
gui/wxpython/iclass/dialogs.py | 6 +--
gui/wxpython/iclass/digit.py | 12 ++---
gui/wxpython/image2target/ii2t_gis_set.py | 5 +-
gui/wxpython/image2target/ii2t_manager.py | 22 ++------
gui/wxpython/iscatt/controllers.py | 10 +---
gui/wxpython/iscatt/frame.py | 6 +--
gui/wxpython/iscatt/iscatt_core.py | 6 +--
gui/wxpython/lmgr/frame.py | 10 +---
gui/wxpython/lmgr/layertree.py | 16 ++----
gui/wxpython/lmgr/menudata.py | 10 +---
gui/wxpython/location_wizard/wizard.py | 5 +-
gui/wxpython/main_window/frame.py | 10 +---
gui/wxpython/mapdisp/frame.py | 5 +-
gui/wxpython/mapdisp/toolbars.py | 5 +-
gui/wxpython/mapwin/buffered.py | 25 ++-------
gui/wxpython/mapwin/decorations.py | 10 +---
gui/wxpython/modules/colorrules.py | 25 ++-------
gui/wxpython/modules/extensions.py | 6 +--
gui/wxpython/modules/import_export.py | 10 +---
gui/wxpython/modules/mcalc_builder.py | 5 +-
gui/wxpython/nviz/mapwindow.py | 5 +-
gui/wxpython/nviz/tools.py | 30 +++--------
gui/wxpython/nviz/workspace.py | 5 +-
gui/wxpython/nviz/wxnviz.py | 17 ++----
gui/wxpython/photo2image/ip2i_manager.py | 15 ++----
gui/wxpython/psmap/dialogs.py | 57 ++++----------------
gui/wxpython/psmap/frame.py | 35 +++---------
gui/wxpython/psmap/utils.py | 10 +---
gui/wxpython/rdigit/controller.py | 5 +-
gui/wxpython/tools/update_menudata.py | 5 +-
gui/wxpython/tplot/frame.py | 5 +-
gui/wxpython/vdigit/dialogs.py | 5 +-
gui/wxpython/vdigit/mapwindow.py | 10 +---
gui/wxpython/vdigit/preferences.py | 22 ++------
gui/wxpython/vdigit/toolbars.py | 5 +-
gui/wxpython/vdigit/wxdigit.py | 5 +-
gui/wxpython/vdigit/wxdisplay.py | 12 ++---
gui/wxpython/vnet/dialogs.py | 5 +-
gui/wxpython/vnet/vnet_data.py | 26 ++-------
gui/wxpython/vnet/vnet_utils.py | 5 +-
gui/wxpython/web_services/widgets.py | 10 +---
gui/wxpython/wxgui.py | 5 +-
gui/wxpython/wxplot/scatter.py | 6 +--
69 files changed, 186 insertions(+), 736 deletions(-)
diff --git a/gui/wxpython/animation/dialogs.py b/gui/wxpython/animation/dialogs.py
index bc7e7fe2482..5f085615b24 100644
--- a/gui/wxpython/animation/dialogs.py
+++ b/gui/wxpython/animation/dialogs.py
@@ -1619,10 +1619,7 @@ def SetStdsProperties(self, layer):
dlg.CenterOnParent()
if dlg.ShowModal() == wx.ID_OK:
layer = dlg.GetLayer()
- if hidden:
- signal = self.layerAdded
- else:
- signal = self.cmdChanged
+ signal = self.layerAdded if hidden else self.cmdChanged
signal.emit(index=self._layerList.GetLayerIndex(layer), layer=layer)
elif hidden:
self._layerList.RemoveLayer(layer)
diff --git a/gui/wxpython/animation/frame.py b/gui/wxpython/animation/frame.py
index 6496920a5cd..42953803778 100644
--- a/gui/wxpython/animation/frame.py
+++ b/gui/wxpython/animation/frame.py
@@ -274,17 +274,11 @@ def OnStop(self, event):
self.controller.EndAnimation()
def OnOneDirectionReplay(self, event):
- if event.IsChecked():
- mode = ReplayMode.REPEAT
- else:
- mode = ReplayMode.ONESHOT
+ mode = ReplayMode.REPEAT if event.IsChecked() else ReplayMode.ONESHOT
self.controller.SetReplayMode(mode)
def OnBothDirectionReplay(self, event):
- if event.IsChecked():
- mode = ReplayMode.REVERSE
- else:
- mode = ReplayMode.ONESHOT
+ mode = ReplayMode.REVERSE if event.IsChecked() else ReplayMode.ONESHOT
self.controller.SetReplayMode(mode)
def OnAdjustSpeed(self, event):
@@ -642,11 +636,8 @@ def _updateFrameIndex(self, index):
}
else:
label = _("to %(to)s") % {"to": self.timeLabels[index][1]}
- else: # noqa: PLR5501
- if self.temporalType == TemporalType.ABSOLUTE:
- label = start
- else:
- label = ""
+ else:
+ label = start if self.temporalType == TemporalType.ABSOLUTE else ""
self.label2.SetLabel(label)
if self.temporalType == TemporalType.RELATIVE:
self.indexField.SetValue(start)
diff --git a/gui/wxpython/animation/temporal_manager.py b/gui/wxpython/animation/temporal_manager.py
index ef782543089..1b5037639cf 100644
--- a/gui/wxpython/animation/temporal_manager.py
+++ b/gui/wxpython/animation/temporal_manager.py
@@ -259,10 +259,8 @@ def _getLabelsAndMaps(self, timeseries):
elif self.temporalType == TemporalType.RELATIVE:
unit = self.timeseriesInfo[timeseries]["unit"]
- if self.granularityMode == GranularityMode.ONE_UNIT:
- gran = 1
- else:
- gran = granNum
+ gran = 1 if self.granularityMode == GranularityMode.ONE_UNIT else granNum
+
# start sampling - now it can be used for both interval and point data
# after instance, there can be a gap or an interval
# if it is a gap we remove it and put there the previous instance instead
diff --git a/gui/wxpython/core/gcmd.py b/gui/wxpython/core/gcmd.py
index a173e28c7f8..134ed756d23 100644
--- a/gui/wxpython/core/gcmd.py
+++ b/gui/wxpython/core/gcmd.py
@@ -709,10 +709,7 @@ def RunCommand(
kwargs["stdin"] = subprocess.PIPE
# Do not change the environment, only a local copy.
- if env:
- env = env.copy()
- else:
- env = os.environ.copy()
+ env = env.copy() if env else os.environ.copy()
if parent:
env["GRASS_MESSAGE_FORMAT"] = "standard"
diff --git a/gui/wxpython/core/gconsole.py b/gui/wxpython/core/gconsole.py
index a4b58435cf4..5b58c08cc55 100644
--- a/gui/wxpython/core/gconsole.py
+++ b/gui/wxpython/core/gconsole.py
@@ -310,10 +310,7 @@ def write(self, s):
if "GRASS_INFO_PERCENT" in line:
value = int(line.rsplit(":", 1)[1].strip())
- if value >= 0 and value < 100:
- progressValue = value
- else:
- progressValue = 0
+ progressValue = value if value >= 0 and value < 100 else 0
elif "GRASS_INFO_MESSAGE" in line:
self.type = "message"
self.message += line.split(":", 1)[1].strip() + "\n"
@@ -632,10 +629,7 @@ def load_source(modname, filename):
return
- if env:
- env = env.copy()
- else:
- env = os.environ.copy()
+ env = env.copy() if env else os.environ.copy()
# activate computational region (set with g.region)
# for all non-display commands.
if compReg and "GRASS_REGION" in env:
diff --git a/gui/wxpython/core/menutree.py b/gui/wxpython/core/menutree.py
index fba33daf705..b8f60e9610a 100644
--- a/gui/wxpython/core/menutree.py
+++ b/gui/wxpython/core/menutree.py
@@ -108,30 +108,14 @@ def _createItem(self, item, node):
shortcut = item.find("shortcut") # optional
wxId = item.find("id") # optional
icon = item.find("icon") # optional
- if gcmd is not None:
- gcmd = gcmd.text
- else:
- gcmd = ""
- if desc.text:
- desc = _(desc.text)
- else:
- desc = ""
- if keywords is None or keywords.text is None:
- keywords = ""
- else:
- keywords = keywords.text
- if shortcut is not None:
- shortcut = shortcut.text
- else:
- shortcut = ""
- if wxId is not None:
- wxId = eval("wx." + wxId.text)
- else:
- wxId = wx.ID_ANY
- if icon is not None:
- icon = icon.text
- else:
- icon = ""
+ gcmd = gcmd.text if gcmd is not None else ""
+ desc = _(desc.text) if desc.text else ""
+ keywords = (
+ "" if keywords is None or keywords.text is None else keywords.text
+ )
+ shortcut = shortcut.text if shortcut is not None else ""
+ wxId = eval("wx." + wxId.text) if wxId is not None else wx.ID_ANY
+ icon = icon.text if icon is not None else ""
label = origLabel
if gcmd:
if self.menustyle == 1:
diff --git a/gui/wxpython/core/render.py b/gui/wxpython/core/render.py
index 2db3287bf78..0f70806d8c3 100644
--- a/gui/wxpython/core/render.py
+++ b/gui/wxpython/core/render.py
@@ -100,10 +100,7 @@ def __init__(
if mapfile:
self.mapfile = mapfile
else:
- if ltype == "overlay":
- tempfile_sfx = ".png"
- else:
- tempfile_sfx = ".ppm"
+ tempfile_sfx = ".png" if ltype == "overlay" else ".ppm"
self.mapfile = get_tempfile_name(suffix=tempfile_sfx)
@@ -790,10 +787,7 @@ def ReportProgress(self, env, layer=None):
stText += "..."
if self.progressInfo["range"] != len(self.progressInfo["rendered"]):
- if stText:
- stText = _("Rendering & ") + stText
- else:
- stText = _("Rendering...")
+ stText = _("Rendering & ") + stText if stText else _("Rendering...")
self.updateProgress.emit(
range=self.progressInfo["range"],
@@ -1260,16 +1254,8 @@ def GetListOfLayers(
:return: list of selected layers
"""
selected = []
-
- if isinstance(ltype, str):
- one_type = True
- else:
- one_type = False
-
- if one_type and ltype == "overlay":
- llist = self.overlays
- else:
- llist = self.layers
+ one_type = bool(isinstance(ltype, str))
+ llist = self.overlays if one_type and ltype == "overlay" else self.layers
# ["raster", "vector", "wms", ... ]
for layer in llist:
@@ -1332,10 +1318,7 @@ def Render(self, force=False, windres=False):
self.renderMgr.Render(force, windres)
def _addLayer(self, layer, pos=-1):
- if layer.type == "overlay":
- llist = self.overlays
- else:
- llist = self.layers
+ llist = self.overlays if layer.type == "overlay" else self.layers
# add maplayer to the list of layers
if pos > -1:
@@ -1426,10 +1409,7 @@ def DeleteLayer(self, layer, overlay=False):
"""
Debug.msg(3, "Map.DeleteLayer(): name=%s" % layer.name)
- if overlay:
- list = self.overlays
- else:
- list = self.layers
+ list = self.overlays if overlay else self.layers
if layer in list:
if layer.mapfile:
@@ -1583,10 +1563,7 @@ def GetLayerIndex(self, layer, overlay=False):
:return: layer index
:return: -1 if layer not found
"""
- if overlay:
- list = self.overlays
- else:
- list = self.layers
+ list = self.overlays if overlay else self.layers
if layer in list:
return list.index(layer)
diff --git a/gui/wxpython/core/settings.py b/gui/wxpython/core/settings.py
index 5cc2fddaf44..c2486600874 100644
--- a/gui/wxpython/core/settings.py
+++ b/gui/wxpython/core/settings.py
@@ -960,10 +960,7 @@ def _readLegacyFile(self, settings=None):
del kv[0]
idx = 0
while idx < len(kv):
- if subkeyMaster:
- subkey = [subkeyMaster, kv[idx]]
- else:
- subkey = kv[idx]
+ subkey = [subkeyMaster, kv[idx]] if subkeyMaster else kv[idx]
value = kv[idx + 1]
value = self._parseValue(value, read=True)
self.Append(settings, group, key, subkey, value)
diff --git a/gui/wxpython/core/treemodel.py b/gui/wxpython/core/treemodel.py
index fb18384ba36..0ce69133e1b 100644
--- a/gui/wxpython/core/treemodel.py
+++ b/gui/wxpython/core/treemodel.py
@@ -294,15 +294,12 @@ def __init__(self, label=None, data=None):
def label(self):
return self._label
- def match(self, key, value, case_sensitive=False):
+ def match(self, key, value, case_sensitive=False) -> bool:
"""Method used for searching according to command,
keywords or description."""
if not self.data:
return False
- if isinstance(key, str):
- keys = [key]
- else:
- keys = key
+ keys = [key] if isinstance(key, str) else key
for key in keys:
if key not in {"command", "keywords", "description"}:
diff --git a/gui/wxpython/core/utils.py b/gui/wxpython/core/utils.py
index 2b1f3f4997a..6a39a158555 100644
--- a/gui/wxpython/core/utils.py
+++ b/gui/wxpython/core/utils.py
@@ -864,10 +864,7 @@ def StoreEnvVariable(key, value=None, envFile=None):
)
)
return
- if windows:
- expCmd = "set"
- else:
- expCmd = "export"
+ expCmd = "set" if windows else "export"
for key, value in environ.items():
fd.write("%s %s=%s\n" % (expCmd, key, value))
diff --git a/gui/wxpython/core/workspace.py b/gui/wxpython/core/workspace.py
index 22aa56bfe62..8534e9c195c 100644
--- a/gui/wxpython/core/workspace.py
+++ b/gui/wxpython/core/workspace.py
@@ -312,10 +312,7 @@ def __processLayer(self, layer):
)
)
- if layer.find("selected") is not None:
- selected = True
- else:
- selected = False
+ selected = layer.find("selected") is not None
#
# Vector digitizer settings
@@ -330,10 +327,7 @@ def __processLayer(self, layer):
# Nviz (3D settings)
#
node_nviz = layer.find("nviz")
- if node_nviz is not None:
- nviz = self.__processLayerNviz(node_nviz)
- else:
- nviz = None
+ nviz = self.__processLayerNviz(node_nviz) if node_nviz is not None else None
return (cmd, selected, vdigit, nviz)
@@ -729,10 +723,7 @@ def __processLayerNvizNode(self, node, tag, cast, dc=None):
try:
value = cast(node_tag.text)
except ValueError:
- if cast == str:
- value = ""
- else:
- value = None
+ value = "" if cast == str else None
if dc:
dc[tag] = {}
dc[tag]["value"] = value
diff --git a/gui/wxpython/datacatalog/tree.py b/gui/wxpython/datacatalog/tree.py
index 176f5231712..bf06fd11ab8 100644
--- a/gui/wxpython/datacatalog/tree.py
+++ b/gui/wxpython/datacatalog/tree.py
@@ -2016,10 +2016,7 @@ def _getNewMapName(self, message, title, value, element, mapset, env):
mapset=mapset,
)
dlg.SetValue(value)
- if dlg.ShowModal() == wx.ID_OK:
- name = dlg.GetValue()
- else:
- name = None
+ name = dlg.GetValue() if dlg.ShowModal() == wx.ID_OK else None
dlg.Destroy()
return name
diff --git a/gui/wxpython/dbmgr/base.py b/gui/wxpython/dbmgr/base.py
index 1af8d6fccb1..775f72a6dc5 100644
--- a/gui/wxpython/dbmgr/base.py
+++ b/gui/wxpython/dbmgr/base.py
@@ -1542,10 +1542,7 @@ def OnDataItemEdit(self, event):
column = tlist.columns[columnName[i]]
if len(values[i]) > 0:
try:
- if missingKey is True:
- idx = i - 1
- else:
- idx = i
+ idx = i - 1 if missingKey is True else i
if column["ctype"] != str:
tlist.itemDataMap[item][idx] = column["ctype"](
@@ -1707,10 +1704,7 @@ def OnDataItemAdd(self, event):
del values[0]
# add new item to the tlist
- if len(tlist.itemIndexMap) > 0:
- index = max(tlist.itemIndexMap) + 1
- else:
- index = 0
+ index = max(tlist.itemIndexMap) + 1 if len(tlist.itemIndexMap) > 0 else 0
tlist.itemIndexMap.append(index)
tlist.itemDataMap[index] = values
@@ -1828,11 +1822,7 @@ def _drawSelected(self, zoom, selectedOnly=True):
return
tlist = self.FindWindowById(self.layerPage[self.selLayer]["data"])
- if selectedOnly:
- fn = tlist.GetSelectedItems
- else:
- fn = tlist.GetItems
-
+ fn = tlist.GetSelectedItems if selectedOnly else tlist.GetItems
cats = list(map(int, fn()))
digitToolbar = None
@@ -1929,11 +1919,7 @@ def AddQueryMapLayer(self, selectedOnly=True):
:return: True if map has been redrawn, False if no map is given
"""
tlist = self.FindWindowById(self.layerPage[self.selLayer]["data"])
- if selectedOnly:
- fn = tlist.GetSelectedItems
- else:
- fn = tlist.GetItems
-
+ fn = tlist.GetSelectedItems if selectedOnly else tlist.GetItems
cats = {self.selLayer: fn()}
if self.mapdisplay.Map.GetLayerIndex(self.qlayer) < 0:
@@ -2237,10 +2223,7 @@ def ValidateSelectStatement(self, statement):
break
cols += c
index += 1
- if cols == "*":
- cols = None
- else:
- cols = cols.split(",")
+ cols = None if cols == "*" else cols.split(",")
tablelen = len(self.dbMgrData["mapDBInfo"].layers[self.selLayer]["table"])
@@ -2251,10 +2234,7 @@ def ValidateSelectStatement(self, statement):
if len(statement[index + 7 + tablelen :]) > 0:
index = statement.lower().find("where ")
- if index > -1:
- where = statement[index + 6 :]
- else:
- where = None
+ where = statement[index + 6 :] if index > -1 else None
else:
where = None
@@ -3324,10 +3304,7 @@ def _createAddPage(self):
row = 0
for key in ("layer", "driver", "database", "table", "key", "addCat"):
label, value = self.addLayerWidgets[key]
- if not value:
- span = (1, 2)
- else:
- span = (1, 1)
+ span = (1, 2) if not value else (1, 1)
dataSizer.Add(label, flag=wx.ALIGN_CENTER_VERTICAL, pos=(row, 0), span=span)
if not value:
diff --git a/gui/wxpython/dbmgr/dialogs.py b/gui/wxpython/dbmgr/dialogs.py
index 0d7c6e9e523..0bd632a33ba 100644
--- a/gui/wxpython/dbmgr/dialogs.py
+++ b/gui/wxpython/dbmgr/dialogs.py
@@ -393,10 +393,7 @@ def UpdateDialog(self, map=None, query=None, cats=None, fid=-1, action=None):
"""
if action:
self.action = action
- if action == "display":
- enabled = False
- else:
- enabled = True
+ enabled = action != "display"
self.closeDialog.Enable(enabled)
self.FindWindowById(wx.ID_OK).Enable(enabled)
diff --git a/gui/wxpython/dbmgr/sqlbuilder.py b/gui/wxpython/dbmgr/sqlbuilder.py
index 5e6fe0e7706..51010e49677 100644
--- a/gui/wxpython/dbmgr/sqlbuilder.py
+++ b/gui/wxpython/dbmgr/sqlbuilder.py
@@ -574,10 +574,7 @@ def _add(self, element, value):
idx1 = len("select")
idx2 = sqlstr.lower().find("from")
colstr = sqlstr[idx1:idx2].strip()
- if colstr == "*":
- cols = []
- else:
- cols = colstr.split(",")
+ cols = [] if colstr == "*" else colstr.split(",")
if value in cols:
cols.remove(value)
else:
@@ -922,10 +919,7 @@ def _add(self, element, value):
print(__doc__, file=sys.stderr)
sys.exit()
- if len(sys.argv) == 3:
- layer = 1
- else:
- layer = int(sys.argv[3])
+ layer = 1 if len(sys.argv) == 3 else int(sys.argv[3])
if sys.argv[1] == "select":
sqlBuilder = SQLBuilderSelect
diff --git a/gui/wxpython/gcp/manager.py b/gui/wxpython/gcp/manager.py
index 3b6dd398b51..74ede7189e9 100644
--- a/gui/wxpython/gcp/manager.py
+++ b/gui/wxpython/gcp/manager.py
@@ -469,11 +469,7 @@ def __init__(self, wizard, parent):
def OnMaptype(self, event):
"""Change map type"""
global maptype
-
- if event.GetInt() == 0:
- maptype = "raster"
- else:
- maptype = "vector"
+ maptype = "raster" if event.GetInt() == 0 else "vector"
def OnLocation(self, event):
"""Sets source location for map(s) to georectify"""
@@ -1433,10 +1429,7 @@ def SetGCPSatus(self, item, itemIndex):
else:
item.SetPropertyVal("hide", False)
if self.highest_only:
- if itemIndex == self.highest_key:
- wxPen = "highest"
- else:
- wxPen = "default"
+ wxPen = "highest" if itemIndex == self.highest_key else "default"
elif self.mapcoordlist[key][5] > self.rmsthresh:
wxPen = "highest"
else:
@@ -1676,10 +1669,7 @@ def OnFocus(self, event):
pass
def _onMouseLeftUpPointer(self, mapWindow, x, y):
- if mapWindow == self.SrcMapWindow:
- coordtype = "source"
- else:
- coordtype = "target"
+ coordtype = "source" if mapWindow == self.SrcMapWindow else "target"
coord = (x, y)
self.SetGCPData(coordtype, coord, self, confirm=True)
@@ -1806,10 +1796,7 @@ def OnGeorect(self, event):
self.grwiz.SwitchEnv("source")
- if self.clip_to_region:
- flags = "ac"
- else:
- flags = "a"
+ flags = "ac" if self.clip_to_region else "a"
with wx.BusyInfo(_("Rectifying images, please wait..."), parent=self):
wx.GetApp().Yield()
diff --git a/gui/wxpython/gmodeler/dialogs.py b/gui/wxpython/gmodeler/dialogs.py
index 7cd7cbd1147..c8dd7509e74 100644
--- a/gui/wxpython/gmodeler/dialogs.py
+++ b/gui/wxpython/gmodeler/dialogs.py
@@ -291,11 +291,7 @@ def GetPanel(self):
def _getCmd(self):
line = self.cmd_prompt.GetCurLine()[0].strip()
- if len(line) == 0:
- cmd = []
- else:
- cmd = utils.split(str(line))
- return cmd
+ return [] if len(line) == 0 else utils.split(str(line))
def GetCmd(self):
"""Get command"""
@@ -980,10 +976,7 @@ def Populate(self, data):
checked.append(None)
else:
bId = action.GetBlockId()
- if not bId:
- bId = _("No")
- else:
- bId = _("Yes")
+ bId = _("No") if not bId else _("Yes")
options = action.GetParameterizedParams()
params = []
for f in options["flags"]:
@@ -1110,10 +1103,7 @@ def MoveItems(self, items, up):
idxList = {}
itemsToSelect = []
for i in items:
- if up:
- idx = i - 1
- else:
- idx = i + 1
+ idx = i - 1 if up else i + 1
itemsToSelect.append(idx)
idxList[model.GetItemIndex(modelActions[i])] = model.GetItemIndex(
modelActions[idx]
diff --git a/gui/wxpython/gmodeler/model.py b/gui/wxpython/gmodeler/model.py
index fdf6ac63b36..15c4eaa8cd4 100644
--- a/gui/wxpython/gmodeler/model.py
+++ b/gui/wxpython/gmodeler/model.py
@@ -833,10 +833,7 @@ def Parameterize(self):
if gtype in {"raster", "vector", "mapset", "file", "region", "dir"}:
gisprompt = True
prompt = gtype
- if gtype == "raster":
- element = "cell"
- else:
- element = gtype
+ element = "cell" if gtype == "raster" else gtype
ptype = "string"
else:
gisprompt = False
@@ -1102,10 +1099,7 @@ def _setPen(self):
group="modeler", key="action", subkey=("width", "default")
)
)
- if self.isEnabled:
- style = wx.SOLID
- else:
- style = wx.DOT
+ style = wx.SOLID if self.isEnabled else wx.DOT
pen = wx.Pen(wx.BLACK, width, style)
self.SetPen(pen)
@@ -1453,10 +1447,7 @@ def SetValue(self, value):
self.SetLabel()
for direction in ("from", "to"):
for rel in self.GetRelations(direction):
- if direction == "from":
- action = rel.GetTo()
- else:
- action = rel.GetFrom()
+ action = rel.GetTo() if direction == "from" else rel.GetFrom()
task = GUI(show=None).ParseCommand(cmd=action.GetLog(string=False))
task.set_param(rel.GetLabel(), self.value)
@@ -1525,10 +1516,7 @@ def _getPen(self):
group="modeler", key="action", subkey=("width", "default")
)
)
- if self.intermediate:
- style = wx.DOT
- else:
- style = wx.SOLID
+ style = wx.DOT if self.intermediate else wx.SOLID
return wx.Pen(wx.BLACK, width, style)
@@ -1718,10 +1706,7 @@ def __init__(
def _setPen(self):
"""Set pen"""
- if self.isEnabled:
- style = wx.SOLID
- else:
- style = wx.DOT
+ style = wx.SOLID if self.isEnabled else wx.DOT
pen = wx.Pen(wx.BLACK, 1, style)
self.SetPen(pen)
@@ -1986,10 +1971,7 @@ def __init__(self, tree):
self.root = self.tree.getroot()
# check if input is a valid GXM file
if self.root is None or self.root.tag != "gxm":
- if self.root is not None:
- tagName = self.root.tag
- else:
- tagName = _("empty")
+ tagName = self.root.tag if self.root is not None else _("empty")
raise GException(_("Details: unsupported tag name '{0}'.").format(tagName))
# list of actions, data
@@ -2099,10 +2081,7 @@ def _processActions(self):
aId = int(action.get("id", -1))
label = action.get("name")
comment = action.find("comment")
- if comment is not None:
- commentString = comment.text
- else:
- commentString = ""
+ commentString = comment.text if comment is not None else ""
self.actions.append(
{
@@ -2515,10 +2494,7 @@ def _data(self, dataList):
# relations
for ft in ("from", "to"):
for rel in data.GetRelations(ft):
- if ft == "from":
- aid = rel.GetTo().GetId()
- else:
- aid = rel.GetFrom().GetId()
+ aid = rel.GetTo().GetId() if ft == "from" else rel.GetFrom().GetId()
self.fd.write(
'%s\n'
% (" " * self.indent, ft, aid, rel.GetLabel())
@@ -2987,10 +2963,7 @@ def _write_input_outputs(self, item, intermediates):
parameterized_params = item.GetParameterizedParams()
for flag in parameterized_params["flags"]:
- if flag["label"]:
- desc = flag["label"]
- else:
- desc = flag["description"]
+ desc = flag["label"] or flag["description"]
if flag["value"]:
value = '\n{}default="{}"'.format(
@@ -3256,12 +3229,7 @@ def _getPythonActionCmd(self, item, task, cmdIndent, variables={}):
return ret
def _getParamDesc(self, param):
- if param["label"]:
- desc = param["label"]
- else:
- desc = param["description"]
-
- return desc
+ return param["label"] or param["description"]
def _getParamValue(self, param):
if param["value"] and "output" not in param["name"]:
@@ -3374,10 +3342,7 @@ def _writePython(self):
for item in modelItems:
parametrizedParams = item.GetParameterizedParams()
for flag in parametrizedParams["flags"]:
- if flag["label"]:
- desc = flag["label"]
- else:
- desc = flag["description"]
+ desc = flag["label"] or flag["description"]
self.fd.write(
r"""# %option
# % key: {flag_name}
@@ -3398,10 +3363,7 @@ def _writePython(self):
self.fd.write("# %end\n")
for param in parametrizedParams["params"]:
- if param["label"]:
- desc = param["label"]
- else:
- desc = param["description"]
+ desc = param["label"] or param["description"]
self.fd.write(
r"""# %option
# % key: {param_name}
diff --git a/gui/wxpython/gmodeler/panels.py b/gui/wxpython/gmodeler/panels.py
index 416a9b85592..f0443e67939 100644
--- a/gui/wxpython/gmodeler/panels.py
+++ b/gui/wxpython/gmodeler/panels.py
@@ -622,10 +622,7 @@ def LoadModelFile(self, filename):
item.Show(True)
# relations/data
for rel in item.GetRelations():
- if rel.GetFrom() == item:
- dataItem = rel.GetTo()
- else:
- dataItem = rel.GetFrom()
+ dataItem = rel.GetTo() if rel.GetFrom() == item else rel.GetFrom()
self._addEvent(dataItem)
self.canvas.diagram.AddShape(dataItem)
self.AddLine(rel)
diff --git a/gui/wxpython/gui_core/dialogs.py b/gui/wxpython/gui_core/dialogs.py
index a38836ac23e..27ce4523a76 100644
--- a/gui/wxpython/gui_core/dialogs.py
+++ b/gui/wxpython/gui_core/dialogs.py
@@ -466,10 +466,7 @@ def CreateNewVector(
"""
vExternalOut = grass.parse_command("v.external.out", flags="g")
isNative = vExternalOut["format"] == "native"
- if cmd[0] == "v.edit" and not isNative:
- showType = True
- else:
- showType = False
+ showType = bool(cmd[0] == "v.edit" and not isNative)
dlg = NewVectorDialog(
parent,
title=title,
@@ -1340,10 +1337,7 @@ def ShowResult(self, group, returnCode, create):
def GetSelectedGroup(self):
"""Return currently selected group (without mapset)"""
g = self.groupSelect.GetValue().split("@")[0]
- if self.edit_subg:
- s = self.subGroupSelect.GetValue()
- else:
- s = None
+ s = self.subGroupSelect.GetValue() if self.edit_subg else None
return g, s
def GetGroupLayers(self, group, subgroup=None):
@@ -1374,10 +1368,7 @@ def ApplyChanges(self):
GMessage(parent=self, message=_("No subgroup selected."))
return 0
- if self.edit_subg:
- subgroup = self.currentSubgroup
- else:
- subgroup = None
+ subgroup = self.currentSubgroup if self.edit_subg else None
groups = self.GetExistGroups()
if group in groups:
diff --git a/gui/wxpython/gui_core/forms.py b/gui/wxpython/gui_core/forms.py
index 2636b213df3..7172835f001 100644
--- a/gui/wxpython/gui_core/forms.py
+++ b/gui/wxpython/gui_core/forms.py
@@ -193,10 +193,7 @@ def run(self):
if not pMap:
pMap = self.task.get_param("input", raiseError=False)
- if pMap:
- map = pMap.get("value", "")
- else:
- map = None
+ map = pMap.get("value", "") if pMap else None
# avoid running db.describe several times
cparams = {}
@@ -278,10 +275,7 @@ def run(self):
elif p.get("element", "") in {"layer", "layer_all"}: # -> layer
# get layer
layer = p.get("value", "")
- if layer != "":
- layer = p.get("value", "")
- else:
- layer = p.get("default", "")
+ layer = p.get("value", "") if layer != "" else p.get("default", "")
# get map name
pMapL = self.task.get_param(
@@ -722,10 +716,7 @@ def __init__(
sizeFrame = self.GetBestSize()
self.SetMinSize(sizeFrame)
- if hasattr(self, "closebox"):
- scale = 0.33
- else:
- scale = 0.50
+ scale = 0.33 if hasattr(self, "closebox") else 0.5
self.SetSize(
wx.Size(
round(sizeFrame[0]),
@@ -813,10 +804,7 @@ def OnMapCreated(self, name, ltype, add: bool | None = None):
:param ltype: layer type (prompt value)
:param add: whether to display layer or not
"""
- if hasattr(self, "addbox") and self.addbox.IsChecked():
- add = True
- else:
- add = False
+ add = bool(hasattr(self, "addbox") and self.addbox.IsChecked())
if self._giface:
self._giface.mapCreated.emit(name=name, ltype=ltype, add=add)
@@ -1156,10 +1144,7 @@ def __init__(self, parent, giface, task, id=wx.ID_ANY, frame=None, *args, **kwar
else:
title_sizer = wx.BoxSizer(wx.HORIZONTAL)
title_txt = StaticText(parent=which_panel)
- if p["key_desc"]:
- ltype = ",".join(p["key_desc"])
- else:
- ltype = p["type"]
+ ltype = ",".join(p["key_desc"]) if p["key_desc"] else p["type"]
# red star for required options
if p.get("required", False):
required_txt = StaticText(parent=which_panel, label="*")
@@ -1900,10 +1885,7 @@ def __init__(self, parent, giface, task, id=wx.ID_ANY, frame=None, *args, **kwar
win.Bind(wx.EVT_COMBOBOX, self.OnSetValue)
elif prompt == "mapset":
- if p.get("age", "old") == "old":
- new = False
- else:
- new = True
+ new = p.get("age", "old") != "old"
win = gselect.MapsetSelect(
parent=which_panel,
@@ -2008,10 +1990,7 @@ def __init__(self, parent, giface, task, id=wx.ID_ANY, frame=None, *args, **kwar
# file selector
elif p.get("prompt", "") != "color" and p.get("prompt", "") == "file":
- if p.get("age", "new") == "new":
- fmode = wx.FD_SAVE
- else:
- fmode = wx.FD_OPEN
+ fmode = wx.FD_SAVE if p.get("age", "new") == "new" else wx.FD_OPEN
# check wildcard
try:
fExt = os.path.splitext(p.get("key_desc", ["*.*"])[0])[1]
@@ -2770,11 +2749,7 @@ def OnVerbosity(self, event):
event.Skip()
def OnPageChange(self, event):
- if not event:
- sel = self.notebook.GetSelection()
- else:
- sel = event.GetSelection()
-
+ sel = self.notebook.GetSelection() if not event else event.GetSelection()
idx = self.notebook.GetPageIndexByName("manual")
if idx > -1 and sel == idx:
# calling LoadPage() is strangely time-consuming (only first call)
diff --git a/gui/wxpython/gui_core/gselect.py b/gui/wxpython/gui_core/gselect.py
index ff256803a97..67b8a1280e2 100644
--- a/gui/wxpython/gui_core/gselect.py
+++ b/gui/wxpython/gui_core/gselect.py
@@ -1394,10 +1394,7 @@ def __init__(
super().__init__(parent, id=wx.ID_ANY, size=size, **kwargs)
self.SetName("FormatSelect")
- if ogr:
- ftype = "ogr"
- else:
- ftype = "gdal"
+ ftype = "ogr" if ogr else "gdal"
formats = []
for f in GetFormats()[ftype][srcType].items():
@@ -1504,10 +1501,7 @@ def __init__(
self.protocolWidgets = {}
self.pgWidgets = {}
- if ogr:
- fType = "ogr"
- else:
- fType = "gdal"
+ fType = "ogr" if ogr else "gdal"
# file
fileMask = "%(all)s (*)|*|" % {"all": _("All files")}
@@ -2290,12 +2284,7 @@ def hasRastSameProjAsLocation(dsn, table=None):
return projectionMatch
def getProjMatchCaption(projectionMatch):
- if projectionMatch == "0":
- projectionMatchCaption = _("No")
- else:
- projectionMatchCaption = _("Yes")
-
- return projectionMatchCaption
+ return _("No") if projectionMatch == "0" else _("Yes")
dsn = self.GetDsn()
if not dsn:
@@ -2440,15 +2429,9 @@ def OnHelp(self, event):
"""Show related manual page"""
cmd = ""
if self.dest:
- if self.ogr:
- cmd = "v.external.out"
- else:
- cmd = "r.external.out"
+ cmd = "v.external.out" if self.ogr else "r.external.out"
elif self.link:
- if self.ogr:
- cmd = "v.external"
- else:
- cmd = "r.external"
+ cmd = "v.external" if self.ogr else "r.external"
elif self.ogr:
cmd = "v.in.ogr"
else:
diff --git a/gui/wxpython/gui_core/menu.py b/gui/wxpython/gui_core/menu.py
index b284461af0a..34d6eeffd31 100644
--- a/gui/wxpython/gui_core/menu.py
+++ b/gui/wxpython/gui_core/menu.py
@@ -91,10 +91,7 @@ def _createMenuItem(
menu.AppendSeparator()
return
- if command:
- helpString = command + " -- " + description
- else:
- helpString = description
+ helpString = command + " -- " + description if command else description
if shortcut:
label += "\t" + shortcut
diff --git a/gui/wxpython/gui_core/preferences.py b/gui/wxpython/gui_core/preferences.py
index 724e4a5aec0..85e5313da0e 100644
--- a/gui/wxpython/gui_core/preferences.py
+++ b/gui/wxpython/gui_core/preferences.py
@@ -2268,10 +2268,7 @@ def OnEnableWheelZoom(self, event):
"""Enable/disable wheel zoom mode control"""
choiceId = self.winId["display:mouseWheelZoom:selection"]
choice = self.FindWindowById(choiceId)
- if choice.GetSelection() == 2:
- enable = False
- else:
- enable = True
+ enable = choice.GetSelection() != 2
scrollId = self.winId["display:scrollDirection:selection"]
self.FindWindowById(scrollId).Enable(enable)
diff --git a/gui/wxpython/gui_core/prompt.py b/gui/wxpython/gui_core/prompt.py
index 6734de169a9..3857f04fb32 100644
--- a/gui/wxpython/gui_core/prompt.py
+++ b/gui/wxpython/gui_core/prompt.py
@@ -428,10 +428,7 @@ def GetWordLeft(self, withDelimiter=False, ignoredDelimiter=None):
ignoredDelimiter = ""
for char in set(" .,-=") - set(ignoredDelimiter):
- if not withDelimiter:
- delimiter = ""
- else:
- delimiter = char
+ delimiter = "" if not withDelimiter else char
parts.append(delimiter + textLeft.rpartition(char)[2])
return min(parts, key=lambda x: len(x))
diff --git a/gui/wxpython/gui_core/treeview.py b/gui/wxpython/gui_core/treeview.py
index a7660308843..2fde45feec8 100644
--- a/gui/wxpython/gui_core/treeview.py
+++ b/gui/wxpython/gui_core/treeview.py
@@ -209,10 +209,7 @@ class CTreeView(AbstractTreeViewMixin, CustomTreeCtrl):
"""Tree view class inheriting from wx.TreeCtrl"""
def __init__(self, model, parent, **kw):
- if hasAgw:
- style = "agwStyle"
- else:
- style = "style"
+ style = "agwStyle" if hasAgw else "style"
if style not in kw:
kw[style] = (
diff --git a/gui/wxpython/iclass/dialogs.py b/gui/wxpython/iclass/dialogs.py
index 322bfcf5721..b97b14a3eff 100644
--- a/gui/wxpython/iclass/dialogs.py
+++ b/gui/wxpython/iclass/dialogs.py
@@ -588,11 +588,7 @@ def ContrastColor(color):
# gacek,
# http://stackoverflow.com/questions/1855884/determine-font-color-based-on-background-color
a = 1 - (0.299 * color[0] + 0.587 * color[1] + 0.114 * color[2]) / 255
-
- if a < 0.5:
- d = 0
- else:
- d = 255
+ d = 0 if a < 0.5 else 255
# maybe return just bool if text should be dark or bright
return (d, d, d)
diff --git a/gui/wxpython/iclass/digit.py b/gui/wxpython/iclass/digit.py
index 85334993db1..7442c24ab5d 100644
--- a/gui/wxpython/iclass/digit.py
+++ b/gui/wxpython/iclass/digit.py
@@ -156,15 +156,9 @@ def CopyMap(self, name, tmp=False, update=False):
poMapInfoNew = pointer(Map_info())
if not tmp:
- if update:
- open_fn = Vect_open_update
- else:
- open_fn = Vect_open_new
- else: # noqa: PLR5501
- if update:
- open_fn = Vect_open_tmp_update
- else:
- open_fn = Vect_open_tmp_new
+ open_fn = Vect_open_update if update else Vect_open_new
+ else:
+ open_fn = Vect_open_tmp_update if update else Vect_open_tmp_new
if update:
if open_fn(poMapInfoNew, name, "") == -1:
diff --git a/gui/wxpython/image2target/ii2t_gis_set.py b/gui/wxpython/image2target/ii2t_gis_set.py
index 6ed97bc46c1..0329516e04a 100644
--- a/gui/wxpython/image2target/ii2t_gis_set.py
+++ b/gui/wxpython/image2target/ii2t_gis_set.py
@@ -1014,10 +1014,7 @@ def OnSetDatabase(self, event):
def OnBrowse(self, event):
"""'Browse' button clicked"""
- if not event:
- defaultPath = os.getenv("HOME")
- else:
- defaultPath = ""
+ defaultPath = os.getenv("HOME") if not event else ""
dlg = wx.DirDialog(
parent=self,
diff --git a/gui/wxpython/image2target/ii2t_manager.py b/gui/wxpython/image2target/ii2t_manager.py
index 3adcf5ef9bd..939c2fb0fe8 100644
--- a/gui/wxpython/image2target/ii2t_manager.py
+++ b/gui/wxpython/image2target/ii2t_manager.py
@@ -488,11 +488,7 @@ def __init__(self, wizard, parent):
def OnMaptype(self, event):
"""Change map type"""
global maptype
-
- if event.GetInt() == 0:
- maptype = "raster"
- else:
- maptype = "vector"
+ maptype = "raster" if event.GetInt() == 0 else "vector"
def OnLocation(self, event):
"""Sets source location for map(s) to georectify"""
@@ -1416,10 +1412,7 @@ def SetGCPSatus(self, item, itemIndex):
else:
item.SetPropertyVal("hide", False)
if self.highest_only:
- if itemIndex == self.highest_key:
- wxPen = "highest"
- else:
- wxPen = "default"
+ wxPen = "highest" if itemIndex == self.highest_key else "default"
elif self.mapcoordlist[key][7] > self.rmsthresh:
wxPen = "highest"
else:
@@ -1702,10 +1695,7 @@ def OnFocus(self, event):
pass
def _onMouseLeftUpPointer(self, mapWindow, x, y):
- if mapWindow == self.SrcMapWindow:
- coordtype = "source"
- else:
- coordtype = "target"
+ coordtype = "source" if mapWindow == self.SrcMapWindow else "target"
coord = (x, y)
self.SetGCPData(coordtype, coord, self, confirm=True)
@@ -1761,11 +1751,7 @@ def OnGeorect(self, event):
if maptype == "raster":
self.grwiz.SwitchEnv("source")
-
- if self.clip_to_region:
- flags = "ac"
- else:
- flags = "a"
+ flags = "ac" if self.clip_to_region else "a"
with wx.BusyInfo(_("Rectifying images, please wait..."), parent=self):
wx.GetApp().Yield()
diff --git a/gui/wxpython/iscatt/controllers.py b/gui/wxpython/iscatt/controllers.py
index fef4e95505e..06ca5d0b243 100644
--- a/gui/wxpython/iscatt/controllers.py
+++ b/gui/wxpython/iscatt/controllers.py
@@ -149,10 +149,7 @@ def SetBands(self, bands):
callable=self.core.CleanUp, ondone=lambda event: self.CleanUpDone()
)
- if self.show_add_scatt_plot:
- show_add = True
- else:
- show_add = False
+ show_add = bool(self.show_add_scatt_plot)
self.all_bands_to_bands = dict(zip(bands, [-1] * len(bands)))
self.all_bands = bands
@@ -697,10 +694,7 @@ def SetData(self):
def AddCategory(self, cat_id=None, name=None, color=None, nstd=None):
if cat_id is None:
- if self.cats_ids:
- cat_id = max(self.cats_ids) + 1
- else:
- cat_id = 1
+ cat_id = max(self.cats_ids) + 1 if self.cats_ids else 1
if self.scatt_mgr.data_set:
self.scatt_mgr.thread.Run(callable=self.core.AddCategory, cat_id=cat_id)
diff --git a/gui/wxpython/iscatt/frame.py b/gui/wxpython/iscatt/frame.py
index 122aa053b9b..5350ecbd8a0 100644
--- a/gui/wxpython/iscatt/frame.py
+++ b/gui/wxpython/iscatt/frame.py
@@ -568,11 +568,7 @@ def OnCategoryRightUp(self, event):
item = menu.Append(wx.ID_ANY, _("Change opacity level"))
self.Bind(wx.EVT_MENU, self.OnPopupOpacityLevel, item)
- if showed:
- text = _("Hide")
- else:
- text = _("Show")
-
+ text = _("Hide") if showed else _("Show")
item = menu.Append(wx.ID_ANY, text)
self.Bind(
wx.EVT_MENU,
diff --git a/gui/wxpython/iscatt/iscatt_core.py b/gui/wxpython/iscatt/iscatt_core.py
index 86321ed2ff1..3d4b3d588b0 100644
--- a/gui/wxpython/iscatt/iscatt_core.py
+++ b/gui/wxpython/iscatt/iscatt_core.py
@@ -805,11 +805,7 @@ def _parseRegion(region_str):
for param in region_str:
k, v = param.split("=")
- if k in {"rows", "cols", "cells"}:
- v = int(v)
- else:
- v = float(v)
- region[k] = v
+ region[k] = int(v) if k in {"rows", "cols", "cells"} else float(v)
return region
diff --git a/gui/wxpython/lmgr/frame.py b/gui/wxpython/lmgr/frame.py
index 963a36e3a58..9879ce1d937 100644
--- a/gui/wxpython/lmgr/frame.py
+++ b/gui/wxpython/lmgr/frame.py
@@ -747,10 +747,7 @@ def OnLocationWizard(self, event):
self._giface.grassdbChanged.emit(
grassdb=grassdb, location=location, action="new", element="location"
)
- if grassdb == gisenv["GISDBASE"]:
- switch_grassdb = None
- else:
- switch_grassdb = grassdb
+ switch_grassdb = grassdb if grassdb != gisenv["GISDBASE"] else None
if can_switch_mapset_interactive(self, grassdb, location, mapset):
switch_mapset_interactively(
self,
@@ -1116,10 +1113,7 @@ def GetMenuCmd(self, event):
:return: command as a list"""
layer = None
- if event:
- cmd = self.menucmd[event.GetId()]
- else:
- cmd = ""
+ cmd = self.menucmd[event.GetId()] if event else ""
try:
cmdlist = cmd.split(" ")
diff --git a/gui/wxpython/lmgr/layertree.py b/gui/wxpython/lmgr/layertree.py
index 855896e35ab..fa301805270 100644
--- a/gui/wxpython/lmgr/layertree.py
+++ b/gui/wxpython/lmgr/layertree.py
@@ -688,10 +688,7 @@ def OnLayerContextMenu(self, event):
)
digitToolbar = self.mapdisplay.GetToolbar("vdigit")
- if digitToolbar:
- vdigitLayer = digitToolbar.GetLayer()
- else:
- vdigitLayer = None
+ vdigitLayer = digitToolbar.GetLayer() if digitToolbar else None
layer = self.GetLayerInfo(self.layer_selected, key="maplayer")
if vdigitLayer is not layer:
item = wx.MenuItem(
@@ -1569,10 +1566,7 @@ def AddLayer(
name = None
- if ctrl:
- ctrlId = ctrl.GetId()
- else:
- ctrlId = None
+ ctrlId = ctrl.GetId() if ctrl else None
# add a data object to hold the layer's command (does not
# apply to generic command layers)
@@ -1606,11 +1600,7 @@ def AddLayer(
prevMapLayer = self.GetLayerInfo(prevItem, key="maplayer")
prevItem = self.GetNextItem(prevItem)
-
- if prevMapLayer:
- pos = self.Map.GetLayerIndex(prevMapLayer)
- else:
- pos = -1
+ pos = self.Map.GetLayerIndex(prevMapLayer) if prevMapLayer else -1
maplayer = self.Map.AddLayer(
pos=pos,
diff --git a/gui/wxpython/lmgr/menudata.py b/gui/wxpython/lmgr/menudata.py
index 59eb72ecb67..88f769af403 100644
--- a/gui/wxpython/lmgr/menudata.py
+++ b/gui/wxpython/lmgr/menudata.py
@@ -25,10 +25,7 @@
class LayerManagerMenuData(MenuTreeModelBuilder):
def __init__(self, filename=None, message_handler=GError):
- if filename:
- expandAddons = False
- else:
- expandAddons = True
+ expandAddons = not filename
fallback = os.path.join(WXGUIDIR, "xml", "menudata.xml")
if not filename:
@@ -57,10 +54,7 @@ def __init__(self, filename=None, message_handler=GError):
class LayerManagerModuleTree(MenuTreeModelBuilder):
def __init__(self, filename=None, message_handler=GError):
- if filename:
- expandAddons = False
- else:
- expandAddons = True
+ expandAddons = not filename
fallback = os.path.join(WXGUIDIR, "xml", "module_tree_menudata.xml")
if not filename:
diff --git a/gui/wxpython/location_wizard/wizard.py b/gui/wxpython/location_wizard/wizard.py
index 1f8de66dda6..d553b4e11d9 100644
--- a/gui/wxpython/location_wizard/wizard.py
+++ b/gui/wxpython/location_wizard/wizard.py
@@ -2760,10 +2760,7 @@ def CreateProj4String(self):
# set ellipsoid parameters
for item in ellipseparams:
- if item[:4] == "f=1/":
- item = " +rf=" + item[4:]
- else:
- item = " +" + item
+ item = " +rf=" + item[4:] if item[:4] == "f=1/" else " +" + item
proj4string = "%s %s" % (proj4string, item)
# set datum transform parameters if relevant
diff --git a/gui/wxpython/main_window/frame.py b/gui/wxpython/main_window/frame.py
index cef4aee7121..3574e7c8951 100644
--- a/gui/wxpython/main_window/frame.py
+++ b/gui/wxpython/main_window/frame.py
@@ -861,10 +861,7 @@ def OnLocationWizard(self, event):
self._giface.grassdbChanged.emit(
grassdb=grassdb, location=location, action="new", element="location"
)
- if grassdb == gisenv["GISDBASE"]:
- switch_grassdb = None
- else:
- switch_grassdb = grassdb
+ switch_grassdb = grassdb if grassdb != gisenv["GISDBASE"] else None
if can_switch_mapset_interactive(self, grassdb, location, mapset):
switch_mapset_interactively(
self,
@@ -1268,10 +1265,7 @@ def GetMenuCmd(self, event):
:return: command as a list"""
layer = None
- if event:
- cmd = self.menucmd[event.GetId()]
- else:
- cmd = ""
+ cmd = self.menucmd[event.GetId()] if event else ""
try:
cmdlist = cmd.split(" ")
diff --git a/gui/wxpython/mapdisp/frame.py b/gui/wxpython/mapdisp/frame.py
index 0a1660ff06a..86ef27f1bc5 100644
--- a/gui/wxpython/mapdisp/frame.py
+++ b/gui/wxpython/mapdisp/frame.py
@@ -783,10 +783,7 @@ def DOutFile(self, command, callback=None):
# --overwrite
continue
if p == "format": # must be there
- if self.IsPaneShown("3d"):
- extType = "ppm"
- else:
- extType = val
+ extType = "ppm" if self.IsPaneShown("3d") else val
if p == "output": # must be there
name = val
elif p == "size":
diff --git a/gui/wxpython/mapdisp/toolbars.py b/gui/wxpython/mapdisp/toolbars.py
index 4eb49846d4f..18459b26e17 100644
--- a/gui/wxpython/mapdisp/toolbars.py
+++ b/gui/wxpython/mapdisp/toolbars.py
@@ -285,10 +285,7 @@ def RemoveTool(self, tool):
def ChangeToolsDesc(self, mode2d):
"""Change description of zoom tools for 2D/3D view"""
- if mode2d:
- icons = BaseIcons
- else:
- icons = NvizIcons
+ icons = BaseIcons if mode2d else NvizIcons
for i, data in enumerate(self.controller.data):
for tool in ("zoomIn", "zoomOut"):
if data[0] == tool:
diff --git a/gui/wxpython/mapwin/buffered.py b/gui/wxpython/mapwin/buffered.py
index c4b07a94fd2..16b6b329ef6 100644
--- a/gui/wxpython/mapwin/buffered.py
+++ b/gui/wxpython/mapwin/buffered.py
@@ -344,10 +344,7 @@ def Draw(
# TODO: find better solution
if not pen:
- if pdctype == "polyline":
- pen = self.polypen
- else:
- pen = self.pen
+ pen = self.polypen if pdctype == "polyline" else self.pen
if img and pdctype == "image":
# self.imagedict[img]['coords'] = coords
@@ -501,10 +498,7 @@ def Draw(
elif pdctype == "text": # draw text on top of map
if not img["active"]:
return # only draw active text
- if "rotation" in img:
- rotation = float(img["rotation"])
- else:
- rotation = 0.0
+ rotation = float(img["rotation"]) if "rotation" in img else 0.0
w, h = self.GetFullTextExtent(img["text"])[0:2]
pdc.SetFont(img["font"])
pdc.SetTextForeground(img["color"])
@@ -536,10 +530,7 @@ def TextBounds(self, textinfo, relcoords=False):
:return: bbox of rotated text bbox (wx.Rect)
:return: relCoords are text coord inside bbox
"""
- if "rotation" in textinfo:
- rotation = float(textinfo["rotation"])
- else:
- rotation = 0.0
+ rotation = float(textinfo["rotation"]) if "rotation" in textinfo else 0.0
coords = textinfo["coords"]
bbox = Rect(coords[0], coords[1], 0, 0)
@@ -1469,10 +1460,7 @@ def OnMouseWheel(self, event):
wheel = event.GetWheelRotation()
Debug.msg(5, "BufferedWindow.MouseAction(): wheel=%d" % wheel)
- if wheel > 0:
- zoomtype = 1
- else:
- zoomtype = -1
+ zoomtype = 1 if wheel > 0 else -1
if UserSettings.Get(group="display", key="scrollDirection", subkey="selection"):
zoomtype *= -1
# zoom 1/2 of the screen (TODO: settings)
@@ -1504,10 +1492,7 @@ def OnDragging(self, event):
previous = self.mouse["begin"]
move = (current[0] - previous[0], current[1] - previous[1])
- if self.digit:
- digitToolbar = self.toolbar
- else:
- digitToolbar = None
+ digitToolbar = self.toolbar if self.digit else None
# dragging or drawing box with left button
if self.mouse["use"] == "pan" or event.MiddleIsDown():
diff --git a/gui/wxpython/mapwin/decorations.py b/gui/wxpython/mapwin/decorations.py
index 24db63d8492..9c643d17752 100644
--- a/gui/wxpython/mapwin/decorations.py
+++ b/gui/wxpython/mapwin/decorations.py
@@ -323,14 +323,8 @@ def ResizeLegend(self, begin, end, screenSize):
"""Resize legend according to given bbox coordinates."""
w = abs(begin[0] - end[0])
h = abs(begin[1] - end[1])
- if begin[0] < end[0]:
- x = begin[0]
- else:
- x = end[0]
- if begin[1] < end[1]:
- y = begin[1]
- else:
- y = end[1]
+ x = min(end[0], begin[0])
+ y = min(end[1], begin[1])
at = [
(screenSize[1] - (y + h)) / float(screenSize[1]) * 100,
diff --git a/gui/wxpython/modules/colorrules.py b/gui/wxpython/modules/colorrules.py
index 3dfdde8c42b..f2b7666d2b8 100644
--- a/gui/wxpython/modules/colorrules.py
+++ b/gui/wxpython/modules/colorrules.py
@@ -977,10 +977,7 @@ def OnSelectionInput(self, event):
self.cr_label.SetLabel(_("Enter raster category values or percents"))
return
- if info["datatype"] == "CELL":
- mapRange = _("range")
- else:
- mapRange = _("fp range")
+ mapRange = _("range") if info["datatype"] == "CELL" else _("fp range")
self.cr_label.SetLabel(
_("Enter raster category values or percents (%(range)s = %(min)d-%(max)d)")
% {
@@ -1409,10 +1406,7 @@ def AddTemporaryColumn(self, type):
idx += 1
self.properties["tmpColumn"] = name + "_" + str(idx)
- if self.version7:
- modul = "v.db.addcolumn"
- else:
- modul = "v.db.addcol"
+ modul = "v.db.addcolumn" if self.version7 else "v.db.addcol"
RunCommand(
modul,
parent=self,
@@ -1427,10 +1421,7 @@ def DeleteTemporaryColumn(self):
return
if self.inmap:
- if self.version7:
- modul = "v.db.dropcolumn"
- else:
- modul = "v.db.dropcol"
+ modul = "v.db.dropcolumn" if self.version7 else "v.db.dropcol"
RunCommand(
modul,
map=self.inmap,
@@ -1452,10 +1443,7 @@ def OnLayerSelection(self, event):
self.sourceColumn.SetValue("cat")
self.properties["sourceColumn"] = self.sourceColumn.GetValue()
- if self.attributeType == "color":
- type = ["character"]
- else:
- type = ["integer"]
+ type = ["character"] if self.attributeType == "color" else ["integer"]
self.fromColumn.InsertColumns(
vector=self.inmap,
layer=vlayer,
@@ -1502,10 +1490,7 @@ def OnAddColumn(self, event):
self.columnsProp[self.attributeType]["name"]
not in self.fromColumn.GetColumns()
):
- if self.version7:
- modul = "v.db.addcolumn"
- else:
- modul = "v.db.addcol"
+ modul = "v.db.addcolumn" if self.version7 else "v.db.addcol"
RunCommand(
modul,
map=self.inmap,
diff --git a/gui/wxpython/modules/extensions.py b/gui/wxpython/modules/extensions.py
index f7822e0cb0e..7837a92589d 100644
--- a/gui/wxpython/modules/extensions.py
+++ b/gui/wxpython/modules/extensions.py
@@ -356,11 +356,7 @@ def _expandPrefix(self, c):
def Load(self, url, full=True):
"""Load list of extensions"""
self._emptyTree()
-
- if full:
- flags = "g"
- else:
- flags = "l"
+ flags = "g" if full else "l"
retcode, ret, msg = RunCommand(
"g.extension", read=True, getErrorMsg=True, url=url, flags=flags, quiet=True
)
diff --git a/gui/wxpython/modules/import_export.py b/gui/wxpython/modules/import_export.py
index c3106d0467b..6b6769ef1b7 100644
--- a/gui/wxpython/modules/import_export.py
+++ b/gui/wxpython/modules/import_export.py
@@ -328,20 +328,14 @@ def AddLayers(self, returncode, cmd=None, userData=None):
self.commandId += 1
layer, output = self.list.GetLayers()[self.commandId][:2]
- if "@" not in output:
- name = output + "@" + grass.gisenv()["MAPSET"]
- else:
- name = output
+ name = output + "@" + grass.gisenv()["MAPSET"] if "@" not in output else output
# add imported layers into layer tree
# an alternative would be emit signal (mapCreated) and (optionally)
# connect to this signal
llist = self._giface.GetLayerList()
if self.importType == "gdal":
- if userData:
- nBands = int(userData.get("nbands", 1))
- else:
- nBands = 1
+ nBands = int(userData.get("nbands", 1)) if userData else 1
if UserSettings.Get(group="rasterLayer", key="opaque", subkey="enabled"):
nFlag = True
diff --git a/gui/wxpython/modules/mcalc_builder.py b/gui/wxpython/modules/mcalc_builder.py
index b0f2f280409..b02a217ae49 100644
--- a/gui/wxpython/modules/mcalc_builder.py
+++ b/gui/wxpython/modules/mcalc_builder.py
@@ -681,10 +681,7 @@ def OnMCalcRun(self, event):
self.log.RunCmd(cmd, onDone=self.OnDone)
self.parent.Raise()
else:
- if self.overwrite.IsChecked():
- overwrite = True
- else:
- overwrite = False
+ overwrite = bool(self.overwrite.IsChecked())
params = {"expression": "%s=%s" % (name, expr), "overwrite": overwrite}
if seed_flag:
params["flags"] = "s"
diff --git a/gui/wxpython/nviz/mapwindow.py b/gui/wxpython/nviz/mapwindow.py
index 1eea5b278a9..d3f93f94938 100644
--- a/gui/wxpython/nviz/mapwindow.py
+++ b/gui/wxpython/nviz/mapwindow.py
@@ -382,10 +382,7 @@ def OnEraseBackground(self, event):
def OnSize(self, event):
size = self.GetClientSize()
- if CheckWxVersion(version=[2, 9]):
- context = self.context
- else:
- context = self.GetContext()
+ context = self.context if CheckWxVersion(version=[2, 9]) else self.GetContext()
if self.size != size and context:
Debug.msg(
3, "GLCanvas.OnSize(): w = %d, h = %d" % (size.width, size.height)
diff --git a/gui/wxpython/nviz/tools.py b/gui/wxpython/nviz/tools.py
index 7ced7d157e1..53c19d075b6 100644
--- a/gui/wxpython/nviz/tools.py
+++ b/gui/wxpython/nviz/tools.py
@@ -3210,10 +3210,7 @@ def _createControl(
"style": style,
"size": sizeW,
}
- if floatSlider:
- slider = FloatSlider(**kwargs)
- else:
- slider = Slider(**kwargs)
+ slider = FloatSlider(**kwargs) if floatSlider else Slider(**kwargs)
slider.SetName("slider")
if bind[0]:
@@ -3432,12 +3429,9 @@ def OnViewChange(self, event):
else:
self.PostViewEvent(zExag=False)
- if winName in {"persp", "twist"}:
- convert = int
- else:
- convert = float
-
- view[winName]["value"] = convert(value)
+ view[winName]["value"] = (
+ int(value) if winName in {"persp", "twist"} else float(value)
+ )
for win in self.win["view"][winName].values():
self.FindWindowById(win).SetValue(value)
@@ -3881,11 +3875,7 @@ def _get3dRange(self, name):
def _getPercent(self, value, toPercent=True):
"""Convert values 0 - 255 to percents and vice versa"""
value = int(value)
- if toPercent:
- value = int(value / 255.0 * 100)
- else:
- value = int(value / 100.0 * 255)
- return value
+ return int(value / 255.0 * 100) if toPercent else int(value / 100.0 * 255)
def OnSurfaceWireColor(self, event):
"""Set wire color"""
@@ -4199,10 +4189,7 @@ def OnVectorHeightText(self, event):
def OnVectorSurface(self, event):
"""Reference surface for vector map (lines/points)"""
id = event.GetId()
- if id == self.win["vector"]["lines"]["surface"]:
- vtype = "lines"
- else:
- vtype = "points"
+ vtype = "lines" if id == self.win["vector"]["lines"]["surface"] else "points"
checkList = self.FindWindowById(self.win["vector"][vtype]["surface"])
checked = []
surfaces = []
@@ -4278,10 +4265,7 @@ def OnCheckThematic(self, event):
check = self.win["vector"][vtype]["thematic"]["check" + attrType]
button = self.win["vector"][vtype]["thematic"]["button" + attrType]
- if self.FindWindowById(check).GetValue():
- checked = True
- else:
- checked = False
+ checked = bool(self.FindWindowById(check).GetValue())
self.FindWindowById(button).Enable(checked)
data = self.GetLayerData("vector")
diff --git a/gui/wxpython/nviz/workspace.py b/gui/wxpython/nviz/workspace.py
index 1e38aee239a..ac9e0582b2d 100644
--- a/gui/wxpython/nviz/workspace.py
+++ b/gui/wxpython/nviz/workspace.py
@@ -136,10 +136,7 @@ def SetVolumeDefaultProp(self):
sel = UserSettings.Get(
group="nviz", key="volume", subkey=["draw", "mode"]
)
- if sel == 0:
- desc = "isosurface"
- else:
- desc = "slice"
+ desc = "isosurface" if sel == 0 else "slice"
data["draw"]["mode"] = {
"value": sel,
"desc": desc,
diff --git a/gui/wxpython/nviz/wxnviz.py b/gui/wxpython/nviz/wxnviz.py
index 47cf99c079d..b37f1c01a45 100644
--- a/gui/wxpython/nviz/wxnviz.py
+++ b/gui/wxpython/nviz/wxnviz.py
@@ -708,11 +708,7 @@ def SetSurfaceAttr(self, id, attr, map, value):
if map:
ret = Nviz_set_attr(id, MAP_OBJ_SURF, attr, MAP_ATT, value, -1.0, self.data)
else:
- if attr == ATT_COLOR:
- val = Nviz_color_from_str(value)
- else:
- val = float(value)
-
+ val = Nviz_color_from_str(value) if attr == ATT_COLOR else float(value)
ret = Nviz_set_attr(id, MAP_OBJ_SURF, attr, CONST_ATT, None, val, self.data)
Debug.msg(
@@ -1505,11 +1501,7 @@ def SetIsosurfaceAttr(self, id, isosurf_id, attr, map, value):
if map:
ret = GVL_isosurf_set_att_map(id, isosurf_id, attr, value)
else:
- if attr == ATT_COLOR:
- val = Nviz_color_from_str(value)
- else:
- val = float(value)
-
+ val = Nviz_color_from_str(value) if attr == ATT_COLOR else float(value)
ret = GVL_isosurf_set_att_const(id, isosurf_id, attr, val)
Debug.msg(
@@ -2175,10 +2167,7 @@ def Resize(self):
def Load(self):
"""Load image to texture"""
- if self.image.HasAlpha():
- bytesPerPixel = 4
- else:
- bytesPerPixel = 3
+ bytesPerPixel = 4 if self.image.HasAlpha() else 3
bytes = bytesPerPixel * self.width * self.height
rev_val = self.height - 1
im = (c_ubyte * bytes)()
diff --git a/gui/wxpython/photo2image/ip2i_manager.py b/gui/wxpython/photo2image/ip2i_manager.py
index 5a2a1f14f21..5e18fe7b626 100644
--- a/gui/wxpython/photo2image/ip2i_manager.py
+++ b/gui/wxpython/photo2image/ip2i_manager.py
@@ -797,10 +797,7 @@ def SetGCPSatus(self, item, itemIndex):
else:
item.SetPropertyVal("hide", False)
if self.highest_only:
- if itemIndex == self.highest_key:
- wxPen = "highest"
- else:
- wxPen = "default"
+ wxPen = "highest" if itemIndex == self.highest_key else "default"
else: # noqa: PLR5501
if self.mapcoordlist[key][5] > self.rmsthresh:
wxPen = "highest"
@@ -1042,10 +1039,7 @@ def OnFocus(self, event):
pass
def _onMouseLeftUpPointer(self, mapWindow, x, y):
- if mapWindow == self.SrcMapWindow:
- coordtype = "source"
- else:
- coordtype = "target"
+ coordtype = "source" if mapWindow == self.SrcMapWindow else "target"
coord = (x, y)
self.SetGCPData(coordtype, coord, self, confirm=True)
@@ -1102,10 +1096,7 @@ def OnGeorect(self, event):
if maptype == "raster":
self.grwiz.SwitchEnv("source")
- if self.clip_to_region:
- flags = "ac"
- else:
- flags = "a"
+ flags = "ac" if self.clip_to_region else "a"
busy = wx.BusyInfo(_("Rectifying images, please wait..."), parent=self)
wx.GetApp().Yield()
diff --git a/gui/wxpython/psmap/dialogs.py b/gui/wxpython/psmap/dialogs.py
index c4784525cc9..a9f562fb46a 100644
--- a/gui/wxpython/psmap/dialogs.py
+++ b/gui/wxpython/psmap/dialogs.py
@@ -1256,10 +1256,7 @@ def OnMap(self, event):
if self.scaleChoice.GetSelection() == 0:
self.selectedMap = self.selected
- if self.rasterTypeRadio.GetValue():
- mapType = "raster"
- else:
- mapType = "vector"
+ mapType = "raster" if self.rasterTypeRadio.GetValue() else "vector"
self.scale[0], self.center[0], foo = AutoAdjust(
self,
@@ -1308,10 +1305,7 @@ def OnScaleChoice(self, event):
self.vectorTypeRadio.Show()
self.drawMap.Show()
self.staticBox.SetLabel(" %s " % _("Map selection"))
- if self.rasterTypeRadio.GetValue():
- stype = "raster"
- else:
- stype = "vector"
+ stype = "raster" if self.rasterTypeRadio.GetValue() else "vector"
self.select.SetElementList(type=stype)
self.mapText.SetLabel(self.mapOrRegionText[0])
@@ -1368,10 +1362,7 @@ def OnScaleChoice(self, event):
def OnElementType(self, event):
"""Changes data in map selection tree ctrl popup"""
- if self.rasterTypeRadio.GetValue():
- mapType = "raster"
- else:
- mapType = "vector"
+ mapType = "raster" if self.rasterTypeRadio.GetValue() else "vector"
self.select.SetElementList(type=mapType)
if self.mapType != mapType and event is not None:
self.mapType = mapType
@@ -1488,10 +1479,7 @@ def update(self):
)
if self.mapType == "vector":
raster = self.instruction.FindInstructionByType("raster")
- if raster:
- rasterId = raster.id
- else:
- rasterId = None
+ rasterId = raster.id if raster else None
if rasterId:
self.env["GRASS_REGION"] = gs.region_env(
@@ -1562,10 +1550,7 @@ def update(self):
region = gs.region(env=None)
raster = self.instruction.FindInstructionByType("raster")
- if raster:
- rasterId = raster.id
- else:
- rasterId = None
+ rasterId = raster.id if raster else None
if rasterId: # because of resolution
self.env["GRASS_REGION"] = gs.region_env(
@@ -3748,10 +3733,7 @@ def _vectorLegend(self, notebook):
def sizePositionFont(self, legendType, parent, mainSizer):
"""Insert widgets for size, position and font control"""
- if legendType == "raster":
- legendDict = self.rLegendDict
- else:
- legendDict = self.vLegendDict
+ legendDict = self.rLegendDict if legendType == "raster" else self.vLegendDict
panel = parent
border = mainSizer
@@ -4125,10 +4107,7 @@ def OnUp(self, event):
self.vectorListCtrl.SetItemData(pos, idx1)
self.vectorListCtrl.SetItemData(pos - 1, idx2)
self.vectorListCtrl.SortItems(cmp)
- if pos > 0:
- selected = pos - 1
- else:
- selected = 0
+ selected = pos - 1 if pos > 0 else 0
self.vectorListCtrl.Select(selected)
@@ -4463,11 +4442,7 @@ def updateDialog(self):
else:
self.rasterId = None
- if raster:
- currRaster = raster["raster"]
- else:
- currRaster = None
-
+ currRaster = raster["raster"] if raster else None
rasterType = getRasterType(map=currRaster)
self.rasterCurrent.SetLabel(
_("%(rast)s: type %(type)s") % {"rast": currRaster, "type": str(rasterType)}
@@ -4995,10 +4970,7 @@ def _scalebarPanel(self):
globalvar.IMGDIR, "scalebar-simple.png"
)
for item, path in zip(["fancy", "simple"], imagePath):
- if not os.path.exists(path):
- bitmap = EmptyBitmap(0, 0)
- else:
- bitmap = wx.Bitmap(path)
+ bitmap = EmptyBitmap(0, 0) if not os.path.exists(path) else wx.Bitmap(path)
self.sbCombo.Append(item="", bitmap=bitmap, clientData=item[0])
# self.sbCombo.Append(
# item="simple",
@@ -5884,11 +5856,7 @@ def _imagePanel(self, notebook):
panel.image["scale"].SetFormat("%f")
panel.image["scale"].SetDigits(1)
- if self.imageDict["scale"]:
- value = float(self.imageDict["scale"])
- else:
- value = 0
-
+ value = float(self.imageDict["scale"]) if self.imageDict["scale"] else 0
panel.image["scale"].SetValue(value)
gridSizer.Add(scaleLabel, pos=(0, 0), flag=wx.ALIGN_CENTER_VERTICAL)
@@ -6601,10 +6569,7 @@ def __init__(self, parent, id, settings, env, type="rectangle", coordinates=None
:param coordinates: begin and end point coordinate (wx.Point, wx.Point)
"""
- if type == "rectangle":
- title = _("Rectangle settings")
- else:
- title = _("Line settings")
+ title = _("Rectangle settings") if type == "rectangle" else _("Line settings")
PsmapDialog.__init__(
self, parent=parent, id=id, title=title, settings=settings, env=env
)
diff --git a/gui/wxpython/psmap/frame.py b/gui/wxpython/psmap/frame.py
index 1d937483123..06c5eebbae5 100644
--- a/gui/wxpython/psmap/frame.py
+++ b/gui/wxpython/psmap/frame.py
@@ -370,10 +370,7 @@ def PSFile(self, filename=None, pdf=False):
temp = False
regOld = gs.region(env=self.env)
- if pdf:
- pdfname = filename
- else:
- pdfname = None
+ pdfname = filename if pdf else None
# preview or pdf
if not filename or (filename and pdf):
temp = True
@@ -571,10 +568,7 @@ def getFile(self, wildcard):
s = "." + s
suffix.append(s)
raster = self.instruction.FindInstructionByType("raster")
- if raster:
- rasterId = raster.id
- else:
- rasterId = None
+ rasterId = raster.id if raster else None
if rasterId and self.instruction[rasterId]["raster"]:
mapName = self.instruction[rasterId]["raster"].split("@")[0] + suffix[0]
@@ -1108,10 +1102,7 @@ def getInitMap(self):
scale = mapInitRect.Get()[2] / realWidth
initMap = self.instruction.FindInstructionByType("initMap")
- if initMap:
- id = initMap.id
- else:
- id = None
+ id = initMap.id if initMap else None
if not id:
id = NewId()
@@ -2102,10 +2093,7 @@ def OnDragging(self, event):
instr = self.instruction[self.dragId]
points = instr["where"]
# moving point
- if self.currentLinePoint == 0:
- pPaper = points[1]
- else:
- pPaper = points[0]
+ pPaper = points[1] if self.currentLinePoint == 0 else points[0]
pCanvas = self.CanvasPaperCoordinates(
rect=Rect2DPS(pPaper, (0, 0)), canvasToPaper=False
)[:2]
@@ -2534,10 +2522,7 @@ def DrawBitmap(self, pdc, filePath, rotation, bbox):
pdc.DrawBitmap(bitmap, bbox[0], bbox[1], useMask=True)
def DrawRotText(self, pdc, drawId, textDict, coords, bounds):
- if textDict["rotate"]:
- rot = float(textDict["rotate"])
- else:
- rot = 0
+ rot = float(textDict["rotate"]) if textDict["rotate"] else 0
if textDict["background"] != "none":
background = textDict["background"]
@@ -2693,16 +2678,10 @@ def UpdateMapLabel(self):
"""Updates map frame label"""
vector = self.instruction.FindInstructionByType("vector")
- if vector:
- vectorId = vector.id
- else:
- vectorId = None
+ vectorId = vector.id if vector else None
raster = self.instruction.FindInstructionByType("raster")
- if raster:
- rasterId = raster.id
- else:
- rasterId = None
+ rasterId = raster.id if raster else None
rasterName = "None"
if rasterId:
diff --git a/gui/wxpython/psmap/utils.py b/gui/wxpython/psmap/utils.py
index 6bb53acd9f0..4e754fafd39 100644
--- a/gui/wxpython/psmap/utils.py
+++ b/gui/wxpython/psmap/utils.py
@@ -93,10 +93,7 @@ class UnitConversion:
def __init__(self, parent=None):
self.parent = parent
- if self.parent:
- ppi = wx.ClientDC(self.parent).GetPPI()
- else:
- ppi = (72, 72)
+ ppi = wx.ClientDC(self.parent).GetPPI() if self.parent else (72, 72)
self._unitsPage = {
"inch": {"val": 1.0, "tr": _("inch")},
"point": {"val": 72.0, "tr": _("point")},
@@ -323,10 +320,7 @@ def ComputeSetRegion(self, mapDict, env):
centerN = mapDict["center"][1]
raster = self.instruction.FindInstructionByType("raster")
- if raster:
- rasterId = raster.id
- else:
- rasterId = None
+ rasterId = raster.id if raster else None
if rasterId:
env["GRASS_REGION"] = gs.region_env(
diff --git a/gui/wxpython/rdigit/controller.py b/gui/wxpython/rdigit/controller.py
index 8018ee04e5c..9b70a2cc468 100644
--- a/gui/wxpython/rdigit/controller.py
+++ b/gui/wxpython/rdigit/controller.py
@@ -447,10 +447,7 @@ def _createNewMap(self, mapName, backgroundMap, mapType):
name = mapName.split("@")[0]
background = backgroundMap.split("@")[0]
types = {"CELL": "int", "FCELL": "float", "DCELL": "double"}
- if background:
- back = background
- else:
- back = "null()"
+ back = background or "null()"
try:
grast.mapcalc(
exp="{name} = {mtype}({back})".format(
diff --git a/gui/wxpython/tools/update_menudata.py b/gui/wxpython/tools/update_menudata.py
index 2f548da3087..08897e6147d 100644
--- a/gui/wxpython/tools/update_menudata.py
+++ b/gui/wxpython/tools/update_menudata.py
@@ -136,10 +136,7 @@ def main(argv=None):
if argv is None:
argv = sys.argv
- if len(argv) > 1 and argv[1] == "-d":
- printDiff = True
- else:
- printDiff = False
+ printDiff = bool(len(argv) > 1 and argv[1] == "-d")
if len(argv) > 1 and argv[1] == "-h":
print(sys.stderr, __doc__, file=sys.stderr)
diff --git a/gui/wxpython/tplot/frame.py b/gui/wxpython/tplot/frame.py
index f52c5a4d190..d152a41a7ec 100755
--- a/gui/wxpython/tplot/frame.py
+++ b/gui/wxpython/tplot/frame.py
@@ -756,10 +756,7 @@ def _writeCSV(self, x, y):
"""Used to write CSV file of plotted data"""
import csv
- if isinstance(y[0], list):
- zipped = list(zip(x, *y))
- else:
- zipped = list(zip(x, y))
+ zipped = list(zip(x, *y)) if isinstance(y[0], list) else list(zip(x, y))
with open(self.csvpath, "w", newline="") as fi:
writer = csv.writer(fi)
if self.header:
diff --git a/gui/wxpython/vdigit/dialogs.py b/gui/wxpython/vdigit/dialogs.py
index 43b277b2ca7..2e7333cf122 100644
--- a/gui/wxpython/vdigit/dialogs.py
+++ b/gui/wxpython/vdigit/dialogs.py
@@ -431,10 +431,7 @@ def ApplyChanges(self, fid):
if layer not in catsCurr[1].keys() or cat not in catsCurr[1][layer]:
catList.append(cat)
if catList != []:
- if action == "catadd":
- add = True
- else:
- add = False
+ add = action == "catadd"
newfid = self.digit.SetLineCats(fid, layer, catList, add)
if len(self.cats.keys()) == 1:
diff --git a/gui/wxpython/vdigit/mapwindow.py b/gui/wxpython/vdigit/mapwindow.py
index ff7e62ebaa9..db9ebf57caf 100644
--- a/gui/wxpython/vdigit/mapwindow.py
+++ b/gui/wxpython/vdigit/mapwindow.py
@@ -834,10 +834,7 @@ def OnLeftUpVarious(self, event):
self.digit.GetDisplay().SelectAreaByPoint(pos1)["area"] != -1
)
else:
- if action == "moveLine":
- drawSeg = True
- else:
- drawSeg = False
+ drawSeg = action == "moveLine"
nselected = self.digit.GetDisplay().SelectLinesByBox(
bbox=(pos1, pos2), drawSeg=drawSeg
@@ -1103,10 +1100,7 @@ def _onRightUp(self, event):
GError(parent=self, message=_("No vector map selected for editing."))
if mapName:
- if self.toolbar.GetAction("type") == "line":
- line = True
- else:
- line = False
+ line = self.toolbar.GetAction("type") == "line"
if len(self.polycoords) < 2: # ignore 'one-point' lines
return
diff --git a/gui/wxpython/vdigit/preferences.py b/gui/wxpython/vdigit/preferences.py
index e565c60dfe9..b8fd9096510 100644
--- a/gui/wxpython/vdigit/preferences.py
+++ b/gui/wxpython/vdigit/preferences.py
@@ -622,10 +622,7 @@ def _createAttributesPage(self, notebook):
layer = UserSettings.Get(group="vdigit", key="layer", subkey="value")
mapLayer = self.parent.toolbars["vdigit"].GetLayer()
tree = self.parent.tree
- if tree:
- item = tree.FindItemByData("maplayer", mapLayer)
- else:
- item = None
+ item = tree.FindItemByData("maplayer", mapLayer) if tree else None
row = 0
for attrb in ["length", "area", "perimeter"]:
# checkbox
@@ -664,10 +661,7 @@ def _createAttributesPage(self, notebook):
column.SetStringSelection(
tree.GetLayerInfo(item, key="vdigit")["geomAttr"][attrb]["column"]
)
- if attrb == "area":
- type = "area"
- else:
- type = "length"
+ type = "area" if attrb == "area" else "length"
unitsIdx = Units.GetUnitsIndex(
type,
tree.GetLayerInfo(item, key="vdigit")["geomAttr"][attrb]["units"],
@@ -987,10 +981,7 @@ def UpdateSettings(self):
# geometry attributes (workspace)
mapLayer = self.parent.toolbars["vdigit"].GetLayer()
tree = self._giface.GetLayerTree()
- if tree:
- item = tree.FindItemByData("maplayer", mapLayer)
- else:
- item = None
+ item = tree.FindItemByData("maplayer", mapLayer) if tree else None
for key, val in self.geomAttrb.items():
checked = self.FindWindowById(val["check"]).IsChecked()
column = self.FindWindowById(val["column"]).GetValue()
@@ -999,11 +990,8 @@ def UpdateSettings(self):
tree.SetLayerInfo(item, key="vdigit", value={"geomAttr": {}})
if checked: # enable
- if key == "area":
- type = key
- else:
- type = "length"
- unitsKey = Units.GetUnitsKey(type, unitsIdx)
+ _type = key if key == "area" else "length"
+ unitsKey = Units.GetUnitsKey(_type, unitsIdx)
tree.GetLayerInfo(item, key="vdigit")["geomAttr"][key] = {
"column": column,
"units": unitsKey,
diff --git a/gui/wxpython/vdigit/toolbars.py b/gui/wxpython/vdigit/toolbars.py
index 6c5c8b21212..a9cafe3dfb4 100644
--- a/gui/wxpython/vdigit/toolbars.py
+++ b/gui/wxpython/vdigit/toolbars.py
@@ -1291,10 +1291,7 @@ def UpdateListOfLayers(self, updateTool=False):
layerNameList.append(layer.GetName())
if updateTool: # update toolbar
- if not self.mapLayer:
- value = _("Select vector map")
- else:
- value = layerNameSelected
+ value = _("Select vector map") if not self.mapLayer else layerNameSelected
if not self.comboid:
if not self.tools or "selector" in self.tools:
diff --git a/gui/wxpython/vdigit/wxdigit.py b/gui/wxpython/vdigit/wxdigit.py
index eda912284a0..10cac8710b5 100644
--- a/gui/wxpython/vdigit/wxdigit.py
+++ b/gui/wxpython/vdigit/wxdigit.py
@@ -1896,10 +1896,7 @@ def _addFeature(self, ftype, coords, layer, cat, snap, threshold):
modeSnap,
)
- if ftype == GV_AREA:
- ltype = GV_BOUNDARY
- else:
- ltype = ftype
+ ltype = GV_BOUNDARY if ftype == GV_AREA else ftype
newline = Vect_write_line(self.poMapInfo, ltype, self.poPoints, self.poCats)
if newline < 0:
self._error.WriteLine()
diff --git a/gui/wxpython/vdigit/wxdisplay.py b/gui/wxpython/vdigit/wxdisplay.py
index d8e4d0a14bf..39662afb19f 100644
--- a/gui/wxpython/vdigit/wxdisplay.py
+++ b/gui/wxpython/vdigit/wxdisplay.py
@@ -982,15 +982,9 @@ def OpenMap(self, name, mapset, update=True, tmp=False):
# open existing map
if update:
- if tmp:
- open_fn = Vect_open_tmp_update
- else:
- open_fn = Vect_open_update
- else: # noqa: PLR5501
- if tmp:
- open_fn = Vect_open_tmp_old
- else:
- open_fn = Vect_open_old
+ open_fn = Vect_open_tmp_update if tmp else Vect_open_update
+ else:
+ open_fn = Vect_open_tmp_old if tmp else Vect_open_old
ret = open_fn(self.poMapInfo, name, mapset)
diff --git a/gui/wxpython/vnet/dialogs.py b/gui/wxpython/vnet/dialogs.py
index ee553a0b741..7985fc2f589 100644
--- a/gui/wxpython/vnet/dialogs.py
+++ b/gui/wxpython/vnet/dialogs.py
@@ -843,10 +843,7 @@ def _setInputData(self):
def _parseMapStr(self, vectMapStr):
"""Create full map name (add current mapset if it is not present in name)"""
mapValSpl = vectMapStr.strip().split("@")
- if len(mapValSpl) > 1:
- mapSet = mapValSpl[1]
- else:
- mapSet = grass.gisenv()["MAPSET"]
+ mapSet = mapValSpl[1] if len(mapValSpl) > 1 else grass.gisenv()["MAPSET"]
mapName = mapValSpl[0]
return mapName, mapSet
diff --git a/gui/wxpython/vnet/vnet_data.py b/gui/wxpython/vnet/vnet_data.py
index f2f17b0bfb5..6f20183fec0 100644
--- a/gui/wxpython/vnet/vnet_data.py
+++ b/gui/wxpython/vnet/vnet_data.py
@@ -841,10 +841,7 @@ def GetRelevantParams(self, analysis):
cols = self.vnetProperties[analysis]["cmdParams"]["cols"]
for col, v in cols.items():
- if "inputField" in col:
- colInptF = v["inputField"]
- else:
- colInptF = col
+ colInptF = v["inputField"] if "inputField" in col else col
relevant_params.append(colInptF)
return relevant_params
@@ -900,10 +897,7 @@ def HasTmpVectMap(self, vectMapName):
"""
mapValSpl = vectMapName.strip().split("@")
- if len(mapValSpl) > 1:
- mapSet = mapValSpl[1]
- else:
- mapSet = grass.gisenv()["MAPSET"]
+ mapSet = mapValSpl[1] if len(mapValSpl) > 1 else grass.gisenv()["MAPSET"]
mapName = mapValSpl[0]
fullName = mapName + "@" + mapSet
@@ -1324,10 +1318,7 @@ def _parseLine(self, line, histStepData):
del kv[0]
idx = 0
while idx < len(kv):
- if subkeyMaster:
- subkey = [subkeyMaster, kv[idx]]
- else:
- subkey = kv[idx]
+ subkey = [subkeyMaster, kv[idx]] if subkeyMaster else kv[idx]
value = kv[idx + 1]
value = self._parseValue(value, read=True)
if key not in histStepData:
@@ -1444,21 +1435,14 @@ def DataValidator(self, row, col, value):
self.turn_data[i_row][1] = new_to_angle
for i_row in inside_new:
- if col == 1:
- angle = new_from_angle
- else:
- angle = new_to_angle
+ angle = new_from_angle if col == 1 else new_to_angle
self.turn_data[i_row][1] = angle
self.turn_data[i_row][2] = angle
def RemoveDataValidator(self, row):
"""Angle recalculation due to direction remove"""
- if row == 0:
- prev_row = self.GetLinesCount() - 1
- else:
- prev_row = row - 1
-
+ prev_row = self.GetLinesCount() - 1 if row == 0 else row - 1
remove_to_angle = self.turn_data[row][2]
self.turn_data[prev_row][2] = remove_to_angle
diff --git a/gui/wxpython/vnet/vnet_utils.py b/gui/wxpython/vnet/vnet_utils.py
index e3cc11aee17..7157ac8a20e 100644
--- a/gui/wxpython/vnet/vnet_utils.py
+++ b/gui/wxpython/vnet/vnet_utils.py
@@ -34,10 +34,7 @@
def ParseMapStr(mapStr):
"""Create full map name (add current mapset if it is not present in name)"""
mapValSpl = mapStr.strip().split("@")
- if len(mapValSpl) > 1:
- mapSet = mapValSpl[1]
- else:
- mapSet = grass.gisenv()["MAPSET"]
+ mapSet = mapValSpl[1] if len(mapValSpl) > 1 else grass.gisenv()["MAPSET"]
mapName = mapValSpl[0]
return mapName, mapSet
diff --git a/gui/wxpython/web_services/widgets.py b/gui/wxpython/web_services/widgets.py
index 473a8fb58a2..e54bee5603f 100644
--- a/gui/wxpython/web_services/widgets.py
+++ b/gui/wxpython/web_services/widgets.py
@@ -384,10 +384,7 @@ def _advancedSettsPage(self):
continue
if k in labels or k == "o":
- if k != "o":
- label = labels[k]
- else:
- label = param
+ label = labels[k] if k != "o" else param
gridSizer.Add(
label, flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL, pos=(row, 0)
@@ -454,10 +451,7 @@ def _updateLayerOrderList(self, selected=None):
"""Update order in list."""
def getlayercaption(layer):
- if layer["title"]:
- cap = layer["title"]
- else:
- cap = layer["name"]
+ cap = layer["title"] or layer["name"]
if layer["style"]:
if layer["style"]["title"]:
diff --git a/gui/wxpython/wxgui.py b/gui/wxpython/wxgui.py
index 8fac39c4d5a..fe1d6f21054 100644
--- a/gui/wxpython/wxgui.py
+++ b/gui/wxpython/wxgui.py
@@ -139,10 +139,7 @@ def process_opt(opts, args):
printHelp()
elif o in {"-w", "--workspace"}:
- if a != "":
- workspaceFile = str(a)
- else:
- workspaceFile = args.pop(0)
+ workspaceFile = str(a) if a != "" else args.pop(0)
return workspaceFile
diff --git a/gui/wxpython/wxplot/scatter.py b/gui/wxpython/wxplot/scatter.py
index c57a3e1fac9..d87a03208e4 100644
--- a/gui/wxpython/wxplot/scatter.py
+++ b/gui/wxpython/wxplot/scatter.py
@@ -176,11 +176,7 @@ def CreateDatalist(self, rpair):
frequency can be in cell counts, percents, or area
"""
datalist = []
-
- if self.scattertype == "bubble":
- freqflag = "cn"
- else:
- freqflag = "n"
+ freqflag = "cn" if self.scattertype == "bubble" else "n"
try:
ret = RunCommand(
From 9e755277a3b8c089764e61622829eb18947bfdac Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Edouard=20Choini=C3=A8re?=
<27212526+echoix@users.noreply.github.com>
Date: Sun, 20 Oct 2024 22:19:30 +0000
Subject: [PATCH 06/12] checks: Rename inner variable shadowing list to _list
in gui/wxpython/core/render.py
---
gui/wxpython/core/render.py | 12 ++++++------
1 file changed, 6 insertions(+), 6 deletions(-)
diff --git a/gui/wxpython/core/render.py b/gui/wxpython/core/render.py
index 0f70806d8c3..989287cd4a5 100644
--- a/gui/wxpython/core/render.py
+++ b/gui/wxpython/core/render.py
@@ -1409,9 +1409,9 @@ def DeleteLayer(self, layer, overlay=False):
"""
Debug.msg(3, "Map.DeleteLayer(): name=%s" % layer.name)
- list = self.overlays if overlay else self.layers
+ _list = self.overlays if overlay else self.layers
- if layer in list:
+ if layer in _list:
if layer.mapfile:
base, mapfile = os.path.split(layer.mapfile)
tempbase = mapfile.split(".")[0]
@@ -1428,7 +1428,7 @@ def DeleteLayer(self, layer, overlay=False):
if os.path.isfile(layer._legrow):
os.remove(layer._legrow)
- list.remove(layer)
+ _list.remove(layer)
self.layerRemoved.emit(layer=layer)
return layer
@@ -1563,10 +1563,10 @@ def GetLayerIndex(self, layer, overlay=False):
:return: layer index
:return: -1 if layer not found
"""
- list = self.overlays if overlay else self.layers
+ _list = self.overlays if overlay else self.layers
- if layer in list:
- return list.index(layer)
+ if layer in _list:
+ return _list.index(layer)
return -1
From 958cb15923aa2b0c2743a9c8b24a7d2b71ade1e9 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Edouard=20Choini=C3=A8re?=
<27212526+echoix@users.noreply.github.com>
Date: Sun, 20 Oct 2024 22:30:49 +0000
Subject: [PATCH 07/12] style: Manual fixes for if-else-block-instead-of-if-exp
(SIM108) in gui/
Ruff rule: https://docs.astral.sh/ruff/rules/if-else-block-instead-of-if-exp
---
gui/wxpython/core/workspace.py | 7 ++-----
gui/wxpython/dbmgr/dialogs.py | 5 +----
gui/wxpython/gmodeler/panels.py | 9 ++-------
gui/wxpython/gui_core/mapdisp.py | 5 +----
gui/wxpython/iscatt/core_c.py | 6 +-----
gui/wxpython/lmgr/layertree.py | 8 ++------
gui/wxpython/mapdisp/frame.py | 6 ++----
gui/wxpython/nviz/tools.py | 12 ++++--------
gui/wxpython/timeline/frame.py | 14 ++++++--------
gui/wxpython/vnet/dialogs.py | 2 +-
gui/wxpython/vnet/vnet_data.py | 6 ++----
11 files changed, 24 insertions(+), 56 deletions(-)
diff --git a/gui/wxpython/core/workspace.py b/gui/wxpython/core/workspace.py
index 8534e9c195c..dd460a68195 100644
--- a/gui/wxpython/core/workspace.py
+++ b/gui/wxpython/core/workspace.py
@@ -169,11 +169,8 @@ def __processFile(self):
size = None
extentAttr = display.get("extent", "")
- if extentAttr:
- # w, s, e, n
- extent = map(float, extentAttr.split(","))
- else:
- extent = None
+ # w, s, e, n
+ extent = map(float, extentAttr.split(",")) if extentAttr else None
# projection
node_projection = display.find("projection")
diff --git a/gui/wxpython/dbmgr/dialogs.py b/gui/wxpython/dbmgr/dialogs.py
index 0bd632a33ba..8ec2b12f36b 100644
--- a/gui/wxpython/dbmgr/dialogs.py
+++ b/gui/wxpython/dbmgr/dialogs.py
@@ -417,10 +417,7 @@ def UpdateDialog(self, map=None, query=None, cats=None, fid=-1, action=None):
idx = 0
for layer in data["Layer"]:
layer = int(layer)
- if data["Id"][idx] is not None:
- tfid = int(data["Id"][idx])
- else:
- tfid = 0 # Area / Volume
+ tfid = int(data["Id"][idx]) if data["Id"][idx] is not None else 0
if tfid not in self.cats:
self.cats[tfid] = {}
if layer not in self.cats[tfid]:
diff --git a/gui/wxpython/gmodeler/panels.py b/gui/wxpython/gmodeler/panels.py
index f0443e67939..fbdc2048620 100644
--- a/gui/wxpython/gmodeler/panels.py
+++ b/gui/wxpython/gmodeler/panels.py
@@ -1660,13 +1660,8 @@ def GetScriptExt(self):
"""Get extension for script exporting.
:return: script extension
"""
- if self.write_object == WriteActiniaFile:
- ext = "json"
- else:
- # Python, PyWPS
- ext = "py"
-
- return ext
+ # return "py" for Python, PyWPS
+ return "json" if self.write_object == WriteActiniaFile else "py"
def SetWriteObject(self, script_type):
"""Set correct self.write_object depending on the script type.
diff --git a/gui/wxpython/gui_core/mapdisp.py b/gui/wxpython/gui_core/mapdisp.py
index a2810c9892b..ea770defe8e 100644
--- a/gui/wxpython/gui_core/mapdisp.py
+++ b/gui/wxpython/gui_core/mapdisp.py
@@ -380,10 +380,7 @@ def StatusbarEnableLongHelp(self, enable=True):
toolbar.EnableLongHelp(enable)
def ShowAllToolbars(self, show=True):
- if not show: # hide
- action = self.RemoveToolbar
- else:
- action = self.AddToolbar
+ action = self.RemoveToolbar if not show else self.AddToolbar
for toolbar in self.GetToolbarNames():
action(toolbar)
diff --git a/gui/wxpython/iscatt/core_c.py b/gui/wxpython/iscatt/core_c.py
index 8be04964b90..a6e6ac5c8a0 100644
--- a/gui/wxpython/iscatt/core_c.py
+++ b/gui/wxpython/iscatt/core_c.py
@@ -214,11 +214,7 @@ def _regionToCellHead(region):
}
for k, v in region.items():
- if k in {"rows", "cols", "cells", "zone"}: # zone added in r65224
- v = int(v)
- else:
- v = float(v)
-
+ v = int(v) if k in {"rows", "cols", "cells", "zone"} else float(v)
if k in convert_dict:
k = convert_dict[k]
diff --git a/gui/wxpython/lmgr/layertree.py b/gui/wxpython/lmgr/layertree.py
index fa301805270..350320d97a7 100644
--- a/gui/wxpython/lmgr/layertree.py
+++ b/gui/wxpython/lmgr/layertree.py
@@ -2053,12 +2053,8 @@ def RecreateItem(self, dragItem, dropTarget, parent=None):
# decide where to put recreated item
if dropTarget is not None and dropTarget != self.GetRootItem():
- if parent:
- # new item is a group
- afteritem = parent
- else:
- # new item is a single layer
- afteritem = dropTarget
+ # new item is a group (parent is truthy) or else new item is a single layer
+ afteritem = parent or dropTarget
# dragItem dropped on group
if self.GetLayerInfo(afteritem, key="type") == "group":
diff --git a/gui/wxpython/mapdisp/frame.py b/gui/wxpython/mapdisp/frame.py
index 86ef27f1bc5..3133341a334 100644
--- a/gui/wxpython/mapdisp/frame.py
+++ b/gui/wxpython/mapdisp/frame.py
@@ -795,10 +795,8 @@ def DOutFile(self, command, callback=None):
elif ext[1:] != extType:
extType = ext[1:]
- if self.IsPaneShown("3d"):
- bitmapType = "ppm"
- else:
- bitmapType = wx.BITMAP_TYPE_PNG # default type
+ # default type is PNG
+ bitmapType = "ppm" if self.IsPaneShown("3d") else wx.BITMAP_TYPE_PNG
for each in ltype:
if each["ext"] == extType:
bitmapType = each["type"]
diff --git a/gui/wxpython/nviz/tools.py b/gui/wxpython/nviz/tools.py
index 53c19d075b6..150fe519635 100644
--- a/gui/wxpython/nviz/tools.py
+++ b/gui/wxpython/nviz/tools.py
@@ -3419,10 +3419,8 @@ def OnViewChange(self, event):
self.AdjustSliderRange(slider=slider, value=value)
- if winName == "height":
- view = self.mapWindow.iview # internal
- else:
- view = self.mapWindow.view
+ # iview is internal
+ view = self.mapWindow.iview if winName == "height" else self.mapWindow.view
if winName == "z-exag" and value >= 0:
self.PostViewEvent(zExag=True)
@@ -3644,10 +3642,8 @@ def EnablePage(self, name, enabled=True):
def SetMapObjUseMap(self, nvizType, attrb, map=None):
"""Update dialog widgets when attribute type changed"""
- if attrb in {"topo", "color", "shine"}:
- incSel = -1 # decrement selection (no 'unset')
- else:
- incSel = 0
+ # decrement selection (no 'unset')
+ incSel = -1 if attrb in {"topo", "color", "shine"} else 0
if nvizType == "volume" and attrb == "topo":
return
if map is True: # map
diff --git a/gui/wxpython/timeline/frame.py b/gui/wxpython/timeline/frame.py
index 7ca51cd8989..6bb57e33927 100644
--- a/gui/wxpython/timeline/frame.py
+++ b/gui/wxpython/timeline/frame.py
@@ -272,10 +272,9 @@ def _draw3dFigure(self):
self.axes3d.clear()
self.axes3d.grid(False)
# self.axes3d.grid(True)
- if self.temporalType == "absolute":
- convert = mdates.date2num
- else:
- convert = lambda x: x # noqa: E731
+ convert = (
+ mdates.date2num if self.temporalType == "absolute" else lambda x: x
+ ) # noqa: E731
colors = cycle(COLORS)
plots = []
@@ -321,10 +320,9 @@ def _draw2dFigure(self):
"""Draws 2D plot (temporal extents)"""
self.axes2d.clear()
self.axes2d.grid(True)
- if self.temporalType == "absolute":
- convert = mdates.date2num
- else:
- convert = lambda x: x # noqa: E731
+ convert = (
+ mdates.date2num if self.temporalType == "absolute" else lambda x: x
+ ) # noqa: E731
colors = cycle(COLORS)
diff --git a/gui/wxpython/vnet/dialogs.py b/gui/wxpython/vnet/dialogs.py
index 7985fc2f589..396f0821c10 100644
--- a/gui/wxpython/vnet/dialogs.py
+++ b/gui/wxpython/vnet/dialogs.py
@@ -458,7 +458,7 @@ def _createParametersPage(self):
# , 'turn_layer', 'turn_cat_layer']:
for sel in ["input", "arc_layer", "node_layer"]:
- if sel == "input":
+ if sel == "input": # noqa: SIM108
btn = self.addToTreeBtn
# elif sel == "turn_layer":
# btn = self.createTtbBtn
diff --git a/gui/wxpython/vnet/vnet_data.py b/gui/wxpython/vnet/vnet_data.py
index 6f20183fec0..9971c9a9699 100644
--- a/gui/wxpython/vnet/vnet_data.py
+++ b/gui/wxpython/vnet/vnet_data.py
@@ -355,10 +355,8 @@ def SetPointStatus(self, item, itemIndex):
item.hide = False
elif len(cats) > 1:
idx = self.data[itemIndex][1]
- if idx == 2: # End/To/Sink point
- wxPen = "used2cat"
- else:
- wxPen = "used1cat"
+ # End/To/Sink point
+ wxPen = "used2cat" if idx == 2 else "used1cat"
else:
wxPen = "used1cat"
From c4fca523f5ace0d1e90389a2ef77484153ccf29e Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Edouard=20Choini=C3=A8re?=
<27212526+echoix@users.noreply.github.com>
Date: Sun, 20 Oct 2024 20:54:35 +0000
Subject: [PATCH 08/12] python: Add type annotations for
grass.script.core.parser()
---
python/grass/script/core.py | 10 ++++++----
1 file changed, 6 insertions(+), 4 deletions(-)
diff --git a/python/grass/script/core.py b/python/grass/script/core.py
index 0b51e7fdbe9..f51814a5900 100644
--- a/python/grass/script/core.py
+++ b/python/grass/script/core.py
@@ -18,6 +18,8 @@
.. sectionauthor:: Michael Barton
"""
+from __future__ import annotations
+
import os
import sys
import atexit
@@ -855,9 +857,9 @@ def get_capture_stderr():
# interface to g.parser
-def _parse_opts(lines):
- options = {}
- flags = {}
+def _parse_opts(lines: list) -> tuple[dict[str, str], dict[str, bool]]:
+ options: dict[str, str] = {}
+ flags: dict[str, bool] = {}
for line in lines:
if not line:
break
@@ -887,7 +889,7 @@ def _parse_opts(lines):
return (options, flags)
-def parser():
+def parser() -> tuple[dict[str, str], dict[str, bool]]:
"""Interface to g.parser, intended to be run from the top-level, e.g.:
::
From afd4ea9f334c4a6e9ad7936a72c88e13b7442223 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Edouard=20Choini=C3=A8re?=
<27212526+echoix@users.noreply.github.com>
Date: Sun, 20 Oct 2024 20:59:53 +0000
Subject: [PATCH 09/12] python: Add type annotations for is_time_absolute() and
is_time_relative() in grass.temporal.AbstractDataset
---
python/grass/temporal/abstract_dataset.py | 6 ++++--
1 file changed, 4 insertions(+), 2 deletions(-)
diff --git a/python/grass/temporal/abstract_dataset.py b/python/grass/temporal/abstract_dataset.py
index bf30afa21dd..6df2fa1f81e 100644
--- a/python/grass/temporal/abstract_dataset.py
+++ b/python/grass/temporal/abstract_dataset.py
@@ -10,6 +10,8 @@
:authors: Soeren Gebbert
"""
+from __future__ import annotations
+
from abc import ABCMeta, abstractmethod
from .core import get_current_mapset, get_tgis_message_interface, init_dbif
@@ -504,7 +506,7 @@ def update_all(self, dbif=None, execute=True, ident=None):
dbif.close()
return statement
- def is_time_absolute(self):
+ def is_time_absolute(self) -> bool | None:
"""Return True in case the temporal type is absolute
:return: True if temporal type is absolute, False otherwise
@@ -513,7 +515,7 @@ def is_time_absolute(self):
return self.base.get_ttype() == "absolute"
return None
- def is_time_relative(self):
+ def is_time_relative(self) -> bool | None:
"""Return True in case the temporal type is relative
:return: True if temporal type is relative, False otherwise
From c87df2e4b90cc630106614f40f1a2a4f6305fecf Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Edouard=20Choini=C3=A8re?=
<27212526+echoix@users.noreply.github.com>
Date: Sun, 20 Oct 2024 22:33:35 +0000
Subject: [PATCH 10/12] style: Enable Checking for SIM108
---
pyproject.toml | 1 -
1 file changed, 1 deletion(-)
diff --git a/pyproject.toml b/pyproject.toml
index 4b7856bab3b..bd1e57160ec 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -242,7 +242,6 @@ ignore = [
"S608", # hardcoded-sql-expression
"SIM102", # collapsible-if
"SIM105", # suppressible-exception
- "SIM108", # if-else-block-instead-of-if-exp
"SIM113", # enumerate-for-loop
"SIM116", # if-else-block-instead-of-dict-lookup
"SIM118", # in-dict-keys
From 1da060ea7fa964aba0e7e71bc5232a434f687859 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Edouard=20Choini=C3=A8re?=
<27212526+echoix@users.noreply.github.com>
Date: Mon, 21 Oct 2024 17:12:59 -0400
Subject: [PATCH 11/12] Update pyproject.toml to remove fixed issues
---
pyproject.toml | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/pyproject.toml b/pyproject.toml
index bd1e57160ec..9a335eea60d 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -363,7 +363,7 @@ ignore = [
"temporal/t.rast.algebra/testsu*/*_algebra_arithmetic.py" = ["FLY002"]
"temporal/t.rast.colors/t.rast.colors.py" = ["SIM115"]
"temporal/t.rast.series/t.rast.series.py" = ["SIM115"]
-"temporal/t.rast.what/t.rast.what.py" = ["E265", "E266", "SIM115"]
+"temporal/t.rast.what/t.rast.what.py" = ["SIM115"]
"temporal/t.register/testsu*/*_raster_different_local.py" = ["FLY002"]
"temporal/t.register/testsu*/*_raster_mapmetadata.py" = ["FLY002"]
"temporal/t.register/testsuite/test_t_register_raster.py" = ["FLY002"]
From b3b50443bef52825b73e357c9ae56a7a7adfa7bc Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Edouard=20Choini=C3=A8re?=
<27212526+echoix@users.noreply.github.com>
Date: Fri, 25 Oct 2024 07:40:09 -0400
Subject: [PATCH 12/12] Update base.py
Co-authored-by: Anna Petrasova
---
gui/wxpython/dbmgr/base.py | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/gui/wxpython/dbmgr/base.py b/gui/wxpython/dbmgr/base.py
index 775f72a6dc5..c5eb8877b0a 100644
--- a/gui/wxpython/dbmgr/base.py
+++ b/gui/wxpython/dbmgr/base.py
@@ -1542,7 +1542,7 @@ def OnDataItemEdit(self, event):
column = tlist.columns[columnName[i]]
if len(values[i]) > 0:
try:
- idx = i - 1 if missingKey is True else i
+ idx = i - 1 if missingKey else i
if column["ctype"] != str:
tlist.itemDataMap[item][idx] = column["ctype"](