From 9e1e85d6079f36962f19b32793b31f43c23b5a4f 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 13:34:52 -0400 Subject: [PATCH] style: Fix if-else-block-instead-of-if-exp (SIM108) (part 3) (#4570) * 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 * 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 * checks: Rename inner variable shadowing type to _type in python/grass/temporal/gui_support.py * 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 * 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 * checks: Rename inner variable shadowing list to _list in gui/wxpython/core/render.py * 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 * python: Add type annotations for grass.script.core.parser() * python: Add type annotations for is_time_absolute() and is_time_relative() in grass.temporal.AbstractDataset * style: Enable Checking for SIM108 * Update pyproject.toml to remove fixed issues * Update base.py Co-authored-by: Anna Petrasova --------- Co-authored-by: Anna Petrasova --- 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 | 45 ++++------------ gui/wxpython/core/settings.py | 5 +- gui/wxpython/core/treemodel.py | 7 +-- gui/wxpython/core/utils.py | 5 +- gui/wxpython/core/workspace.py | 22 ++------ gui/wxpython/datacatalog/tree.py | 5 +- gui/wxpython/dbmgr/base.py | 37 +++---------- gui/wxpython/dbmgr/dialogs.py | 10 +--- 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 | 14 ++--- 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/mapdisp.py | 5 +- 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/core_c.py | 6 +-- gui/wxpython/iscatt/frame.py | 6 +-- gui/wxpython/iscatt/iscatt_core.py | 6 +-- gui/wxpython/lmgr/frame.py | 10 +--- gui/wxpython/lmgr/layertree.py | 24 ++------- 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 | 11 ++-- 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 | 42 ++++----------- 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/timeline/frame.py | 14 +++-- 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 | 7 +-- gui/wxpython/vnet/vnet_data.py | 32 +++-------- 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 +-- pyproject.toml | 3 +- python/grass/script/core.py | 10 ++-- python/grass/temporal/abstract_dataset.py | 6 ++- 75 files changed, 225 insertions(+), 804 deletions(-) diff --git a/gui/wxpython/animation/dialogs.py b/gui/wxpython/animation/dialogs.py index 644553ec328..5a634b3bb16 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..989287cd4a5 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,12 +1409,9 @@ 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 in _list: if layer.mapfile: base, mapfile = os.path.split(layer.mapfile) tempbase = mapfile.split(".")[0] @@ -1448,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 @@ -1583,13 +1563,10 @@ 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) + if layer in _list: + return _list.index(layer) return -1 diff --git a/gui/wxpython/core/settings.py b/gui/wxpython/core/settings.py index b155d9607af..05c6579e636 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..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") @@ -312,10 +309,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 +324,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 +720,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..c5eb8877b0a 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 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..8ec2b12f36b 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) @@ -420,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/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..fbdc2048620 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) @@ -1663,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/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/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/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 9aaa7e31604..615e614689f 100644 --- a/gui/wxpython/iclass/dialogs.py +++ b/gui/wxpython/iclass/dialogs.py @@ -588,11 +588,7 @@ def ContrastColor(color): # gacek, # https://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/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/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 09214d08e42..52cecbfb381 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..350320d97a7 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, @@ -2063,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/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..3133341a334 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": @@ -798,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/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 6f48006db44..dcb34619b57 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 6810484bfdd..db4e3b517a2 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 52630e55820..4294a9730de 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..150fe519635 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]: @@ -3422,22 +3419,17 @@ 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) 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) @@ -3650,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 @@ -3881,11 +3871,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 +4185,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 +4261,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 5a223747277..35995d30e6b 100644 --- a/gui/wxpython/nviz/wxnviz.py +++ b/gui/wxpython/nviz/wxnviz.py @@ -885,11 +885,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( @@ -1682,11 +1678,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( @@ -2352,10 +2344,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 d0726a3bae2..0e6168a8edd 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" with 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 f086d65dd36..428ae248c87 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", @@ -5882,11 +5854,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) @@ -6579,10 +6547,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 e86b277252c..8926b8d1e75 100644 --- a/gui/wxpython/psmap/frame.py +++ b/gui/wxpython/psmap/frame.py @@ -369,10 +369,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 @@ -569,10 +566,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] @@ -1106,10 +1100,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() @@ -2100,10 +2091,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] @@ -2532,10 +2520,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"] @@ -2691,16 +2676,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/timeline/frame.py b/gui/wxpython/timeline/frame.py index fa2b16ad49f..0829d8bc3a0 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/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 07825058e2d..584d97fbf24 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..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 @@ -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..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" @@ -841,10 +839,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 +895,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 +1316,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 +1433,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( diff --git a/pyproject.toml b/pyproject.toml index a428c79106f..3c5950f922b 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -241,7 +241,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 @@ -365,7 +364,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"] 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.: :: 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