diff --git a/gui/wxpython/animation/data.py b/gui/wxpython/animation/data.py index 3799cf43ef1..f35e85e1e5b 100644 --- a/gui/wxpython/animation/data.py +++ b/gui/wxpython/animation/data.py @@ -295,9 +295,8 @@ def __init__(self): def SetName(self, name): if not self.hidden: if self._mapType is None: - raise ValueError( - "To set layer name, the type of layer must be specified." - ) + msg = "To set layer name, the type of layer must be specified." + raise ValueError(msg) if self._mapType in {"strds", "stvds", "str3ds"}: try: name = validateTimeseriesName(name, self._mapType) diff --git a/gui/wxpython/core/globalvar.py b/gui/wxpython/core/globalvar.py index e0397a2b121..4cca60d8fe8 100644 --- a/gui/wxpython/core/globalvar.py +++ b/gui/wxpython/core/globalvar.py @@ -95,7 +95,8 @@ def CheckForWx(): version = parse_version_string(wx.__version__) if version < WXPY3_MIN_VERSION: - raise ValueError("Your wxPython version is {}".format(wx.__version__)) + msg = "Your wxPython version is {}".format(wx.__version__) + raise ValueError(msg) return except ImportError as e: print("ERROR: wxGUI requires wxPython. {}".format(e), file=sys.stderr) diff --git a/gui/wxpython/core/layerlist.py b/gui/wxpython/core/layerlist.py index 5b14a4039fd..b6609b9c2df 100644 --- a/gui/wxpython/core/layerlist.py +++ b/gui/wxpython/core/layerlist.py @@ -222,15 +222,15 @@ def SetName(self, name): len(fullName) == 1 and self._mapType != "rgb" ): # skip checking rgb maps for now if self._mapType is None: - raise ValueError( - "To set layer name, the type of layer must be specified." - ) + msg = "To set layer name, the type of layer must be specified." + raise ValueError(msg) res = gcore.find_file( name=fullName, element=self._internalTypes[self._mapType] ) if not res["mapset"]: - raise ValueError("Map <{name}> not found.".format(name=name)) + msg = "Map <{name}> not found.".format(name=name) + raise ValueError(msg) self._name = name + "@" + res["mapset"] else: self._name = name @@ -263,7 +263,8 @@ def SetMapType(self, mapType): :param mapType: can be 'raster', 'vector', 'raster_3d' """ if mapType not in self._mapTypes: - raise ValueError("Wrong map type used: {mtype}".format(mtype=mapType)) + msg = "Wrong map type used: {mtype}".format(mtype=mapType) + raise ValueError(msg) self._mapType = mapType @@ -282,9 +283,8 @@ def SetOpacity(self, opacity): :param float opacity: value between 0 and 1 """ if not (0 <= opacity <= 1): - raise ValueError( - "Opacity value must be between 0 and 1, not {op}.".format(op=opacity) - ) + msg = "Opacity value must be between 0 and 1, not {op}.".format(op=opacity) + raise ValueError(msg) self._opacity = opacity opacity = property(fget=GetOpacity, fset=SetOpacity) diff --git a/gui/wxpython/core/utils.py b/gui/wxpython/core/utils.py index e500c47d263..77f8b5a3c5b 100644 --- a/gui/wxpython/core/utils.py +++ b/gui/wxpython/core/utils.py @@ -311,7 +311,8 @@ def ListOfMapsets(get="ordered"): mapsets_ordered.append(mapset) return mapsets_ordered - raise ValueError("Invalid value for 'get' parameter of ListOfMapsets()") + msg = "Invalid value for 'get' parameter of ListOfMapsets()" + raise ValueError(msg) def ListSortLower(list): diff --git a/gui/wxpython/gmodeler/model.py b/gui/wxpython/gmodeler/model.py index 2a4673f511a..930944d6bb1 100644 --- a/gui/wxpython/gmodeler/model.py +++ b/gui/wxpython/gmodeler/model.py @@ -325,7 +325,8 @@ def LoadModel(self, filename): try: gxmXml = ProcessModelFile(ET.parse(filename)) except Exception as e: - raise GException("{}".format(e)) + msg = "{}".format(e) + raise GException(msg) if self.canvas: win = self.canvas.parent @@ -1550,7 +1551,8 @@ def GetDisplayCmd(self): elif self.prompt == "vector": cmd.append("d.vect") else: - raise GException("Unsupported display prompt: {}".format(self.prompt)) + msg = "Unsupported display prompt: {}".format(self.prompt) + raise GException(msg) cmd.append("map=" + self.value) diff --git a/gui/wxpython/gui_core/mapdisp.py b/gui/wxpython/gui_core/mapdisp.py index d72fabe4438..515900959c7 100644 --- a/gui/wxpython/gui_core/mapdisp.py +++ b/gui/wxpython/gui_core/mapdisp.py @@ -285,19 +285,23 @@ def GetProgressBar(self): def GetMap(self): """Returns current map (renderer) instance""" - raise NotImplementedError("GetMap") + msg = self.GetMap.__name__ + raise NotImplementedError(msg) def GetWindow(self): """Returns current map window""" - raise NotImplementedError("GetWindow") + msg = self.GetWindow.__name__ + raise NotImplementedError(msg) def GetWindows(self): """Returns list of map windows""" - raise NotImplementedError("GetWindows") + msg = self.GetWindows.__name__ + raise NotImplementedError(msg) def GetMapToolbar(self): """Returns toolbar with zooming tools""" - raise NotImplementedError("GetMapToolbar") + msg = self.GetMapToolbar.__name__ + raise NotImplementedError(msg) def GetToolbar(self, name): """Returns toolbar if exists and is active, else None.""" @@ -393,7 +397,8 @@ def GetToolbarNames(self): def AddToolbar(self): """Add defined toolbar to the window""" - raise NotImplementedError("AddToolbar") + msg = self.AddToolbar.__name__ + raise NotImplementedError(msg) def RemoveToolbar(self, name, destroy=False): """Removes defined toolbar from the window @@ -419,7 +424,8 @@ def IsPaneShown(self, name): def OnRender(self, event): """Re-render map composition (each map layer)""" - raise NotImplementedError("OnRender") + msg = self.OnRender.__name__ + raise NotImplementedError(msg) def OnEnableDisableRender(self, event): """Enable/disable auto-rendering map composition (each map layer)""" diff --git a/gui/wxpython/iscatt/plots.py b/gui/wxpython/iscatt/plots.py index 30498c35fbe..02115c96314 100644 --- a/gui/wxpython/iscatt/plots.py +++ b/gui/wxpython/iscatt/plots.py @@ -633,10 +633,11 @@ class PolygonDrawer: def __init__(self, ax, pol, empty_pol): if pol.figure is None: - raise RuntimeError( + msg = ( "You must first add the polygon to a figure or canvas before defining " "the interactor" ) + raise RuntimeError(msg) self.ax = ax self.canvas = pol.figure.canvas @@ -912,7 +913,8 @@ class ModestImage(mi.AxesImage): def __init__(self, minx=0.0, miny=0.0, *args, **kwargs): if "extent" in kwargs and kwargs["extent"] is not None: - raise NotImplementedError("ModestImage does not support extents") + msg = f"{ModestImage.__name__} does not support extents" + raise NotImplementedError(msg) self._full_res = None self._sx, self._sy = None, None @@ -932,12 +934,14 @@ def set_data(self, A): self._A = A if self._A.dtype != np.uint8 and not np.can_cast(self._A.dtype, float): - raise TypeError("Image data can not convert to float") + msg = "Image data can not convert to float" + raise TypeError(msg) if self._A.ndim not in (2, 3) or ( self._A.ndim == 3 and self._A.shape[-1] not in (3, 4) ): - raise TypeError("Invalid dimensions for image data") + msg = "Invalid dimensions for image data" + raise TypeError(msg) self._imcache = None self._rgbacache = None diff --git a/gui/wxpython/lmgr/frame.py b/gui/wxpython/lmgr/frame.py index 1b69a517717..4c79250cd34 100644 --- a/gui/wxpython/lmgr/frame.py +++ b/gui/wxpython/lmgr/frame.py @@ -1396,10 +1396,11 @@ def write_help(): # this is programmer's error # can be relaxed in future # but keep it strict unless needed otherwise - raise ValueError( - "OnChangeCWD cmd parameter must be list of" + msg = ( + f"{self.OnChangeCWD.__name__} cmd parameter must be list of" " length 1 or 2 and 'cd' as a first item" ) + raise ValueError(msg) if cmd and len(cmd) > 2: # this might be a user error write_beginning(command=cmd) diff --git a/gui/wxpython/main_window/frame.py b/gui/wxpython/main_window/frame.py index a4a4dfea8e2..438cdf1d31f 100644 --- a/gui/wxpython/main_window/frame.py +++ b/gui/wxpython/main_window/frame.py @@ -1548,10 +1548,11 @@ def write_help(): # this is programmer's error # can be relaxed in future # but keep it strict unless needed otherwise - raise ValueError( - "OnChangeCWD cmd parameter must be list of" + msg = ( + f"{self.OnChangeCWD.__name__} cmd parameter must be a list of" " length 1 or 2 and 'cd' as a first item" ) + raise ValueError(msg) if cmd and len(cmd) > 2: # this might be a user error write_beginning(command=cmd) diff --git a/lib/gis/testsuite/test_gis_lib_getl.py b/lib/gis/testsuite/test_gis_lib_getl.py index 72e8992ad39..1ac9907f3d9 100644 --- a/lib/gis/testsuite/test_gis_lib_getl.py +++ b/lib/gis/testsuite/test_gis_lib_getl.py @@ -36,7 +36,8 @@ def read_lines_and_assert(self, get_line_function, newline): file_ptr = self.libc.fopen(str(self.file_path).encode("utf-8"), b"r") if not file_ptr: - raise FileNotFoundError(f"Could not open file: {self.file_path}") + msg = f"Could not open file: {self.file_path}" + raise FileNotFoundError(msg) try: buffer_size = 50 diff --git a/lib/init/grass.py b/lib/init/grass.py index 6e9dcbf7a58..5a2102ed3ec 100755 --- a/lib/init/grass.py +++ b/lib/init/grass.py @@ -231,7 +231,8 @@ def f(fmt, *args): matches.append(m) if len(matches) != len(args): - raise Exception("The numbers of format specifiers and arguments do not match") + msg = "The numbers of format specifiers and arguments do not match" + raise Exception(msg) i = len(args) - 1 for m in reversed(matches): @@ -1610,9 +1611,8 @@ def sh_like_startup(location, location_name, grass_env_file, sh): shrc = ".zshrc" grass_shrc = ".grass.zshrc" else: - raise ValueError( - "Only bash-like and zsh shells are supported by sh_like_startup()" - ) + msg = "Only bash-like and zsh shells are supported by sh_like_startup()" + raise ValueError(msg) # save command history in mapset dir and remember more # bash history file handled in specific_addition @@ -2106,10 +2106,11 @@ def find_grass_python_package(): # now we can import stuff from grass package else: # Not translatable because we don't have translations loaded. - raise RuntimeError( + msg = ( "The grass Python package is missing. " "Is the installation of GRASS GIS complete?" ) + raise RuntimeError(msg) def main(): diff --git a/pyproject.toml b/pyproject.toml index bd1da6c3029..33570645399 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -35,6 +35,7 @@ select = [ "D", # pydocstyle (D) "DTZ", # flake8-datetimez (DTZ) "E", # pycodestyle (E, W) + "EM", # flake8-errmsg (EM) "F", # Pyflakes (F) "FA", # flake8-future-annotations (FA) "FBT", # flake8-boolean-trap (FBT) diff --git a/python/grass/app/runtime.py b/python/grass/app/runtime.py index 27f35760b8f..1640d11a853 100644 --- a/python/grass/app/runtime.py +++ b/python/grass/app/runtime.py @@ -36,16 +36,18 @@ def get_grass_config_dir(major_version, minor_version, env): config_dir = env.get(env_dirname) if config_dir is None: - raise RuntimeError( + msg = ( f"The {env_dirname} variable is not set, ask your operating" " system support" ) + raise RuntimeError(msg) if not os.path.isdir(config_dir): - raise NotADirectoryError( + msg = ( f"The {env_dirname} variable points to directory which does" " not exist, ask your operating system support" ) + raise NotADirectoryError(msg) if WINDOWS: config_dirname = f"GRASS{major_version}" diff --git a/python/grass/benchmark/app.py b/python/grass/benchmark/app.py index 835fc0d544b..fb8262df17c 100644 --- a/python/grass/benchmark/app.py +++ b/python/grass/benchmark/app.py @@ -39,10 +39,11 @@ class CliUsageError(ValueError): def join_results_cli(args): """Translate CLI parser result to API calls.""" if args.prefixes and len(args.results) != len(args.prefixes): - raise CliUsageError( + msg = ( f"Number of prefixes ({len(args.prefixes)}) needs to be the same" f" as the number of input result files ({len(args.results)})" ) + raise CliUsageError(msg) def select_only(result): return result.label == args.only diff --git a/python/grass/benchmark/plots.py b/python/grass/benchmark/plots.py index 24afcbcfbae..575463e662e 100644 --- a/python/grass/benchmark/plots.py +++ b/python/grass/benchmark/plots.py @@ -72,10 +72,9 @@ def nprocs_plot(results, filename=None, title=None, metric="time"): ylabel = metric.title() plt.plot(x, getattr(result, metric), label=result.label) else: - raise ValueError( - f"Invalid metric '{metric}' in result, it should be:\ + msg = f"Invalid metric '{metric}' in result, it should be:\ 'time', 'speedup' or 'efficiency'" - ) + raise ValueError(msg) plt.legend() # If there is not many x values, show ticks for each, but use default # ticks when there is a lot of x values. diff --git a/python/grass/experimental/create.py b/python/grass/experimental/create.py index afe8f9c7b69..8581691ac42 100644 --- a/python/grass/experimental/create.py +++ b/python/grass/experimental/create.py @@ -42,15 +42,17 @@ def require_create_ensure_mapset( if overwrite: delete_mapset(path.directory, path.location, path.mapset) else: - raise ValueError( + msg = ( f"Mapset '{path.mapset}' already exists, " "use a different name, overwrite, or ensure" ) + raise ValueError(msg) if create or (ensure and not exists): create_mapset(path.directory, path.location, path.mapset) elif not exists or not is_mapset_valid(path): reason = get_mapset_invalid_reason(path.directory, path.location, path.mapset) - raise ValueError(f"Mapset {path.mapset} is not valid: {reason}") + msg = f"Mapset {path.mapset} is not valid: {reason}" + raise ValueError(msg) def create_temporary_mapset(path, location=None) -> MapsetPath: diff --git a/python/grass/experimental/mapset.py b/python/grass/experimental/mapset.py index e6b818f0a2c..02417d95175 100644 --- a/python/grass/experimental/mapset.py +++ b/python/grass/experimental/mapset.py @@ -92,7 +92,8 @@ def finish(self): the environment obtained from this object. """ if not self.active: - raise ValueError("Attempt to finish an already finished session") + msg = "Attempt to finish an already finished session" + raise ValueError(msg) os.remove(self._session_file) self._active = False @@ -104,9 +105,8 @@ def __enter__(self): :returns: reference to the object (self) """ if not self.active: - raise ValueError( - "Attempt to use inactive (finished) session as a context manager" - ) + msg = "Attempt to use inactive (finished) session as a context manager" + raise ValueError(msg) return self def __exit__(self, type, value, traceback): # pylint: disable=redefined-builtin @@ -211,7 +211,8 @@ def finish(self): the environment obtained from this object. """ if not self.active: - raise ValueError("Attempt to finish an already finished session") + msg = "Attempt to finish an already finished session" + raise ValueError(msg) self._active = False os.remove(self._session_file) shutil.rmtree(self._path.path, ignore_errors=True) @@ -224,9 +225,8 @@ def __enter__(self): :returns: reference to the object (self) """ if not self.active: - raise ValueError( - "Attempt to use inactive (finished) session as a context manager" - ) + msg = "Attempt to use inactive (finished) session as a context manager" + raise ValueError(msg) return self def __exit__(self, type, value, traceback): # pylint: disable=redefined-builtin diff --git a/python/grass/grassdb/history.py b/python/grass/grassdb/history.py index d7c22eb36fc..d168c0aa184 100644 --- a/python/grass/grassdb/history.py +++ b/python/grass/grassdb/history.py @@ -313,7 +313,8 @@ def add_entry(history_path, entry): if get_history_file_extension(history_path) == ".json": _add_entry_to_JSON(history_path, entry) else: - raise ValueError("Adding entries is supported only for JSON format.") + msg = "Adding entries is supported only for JSON format." + raise ValueError(msg) def _update_entry_in_JSON(history_path, command_info, index=None): @@ -360,7 +361,8 @@ def update_entry(history_path, command_info, index=None): if get_history_file_extension(history_path) == ".json": _update_entry_in_JSON(history_path, command_info, index) else: - raise ValueError("Updating entries is supported only for JSON format.") + msg = "Updating entries is supported only for JSON format." + raise ValueError(msg) def copy(history_path, target_path): diff --git a/python/grass/gunittest/case.py b/python/grass/gunittest/case.py index 49a378d6133..791217d13c1 100644 --- a/python/grass/gunittest/case.py +++ b/python/grass/gunittest/case.py @@ -133,14 +133,17 @@ def del_temp_region(cls): name = os.environ.pop("WIND_OVERRIDE") if name != cls._temp_region: # be strict about usage of region - raise RuntimeError( + msg = ( "Inconsistent use of" " TestCase.use_temp_region, WIND_OVERRIDE" " or temporary region in general\n" "Region to which should be now deleted ({n})" " by TestCase class" "does not correspond to currently set" - " WIND_OVERRIDE ({c})", + " WIND_OVERRIDE ({c})" + ) + raise RuntimeError( + msg, n=cls._temp_region, c=name, ) @@ -263,12 +266,13 @@ def assertModuleKeyValue( else: # we can probably remove this once we have more tests # of keyvalue_equals and diff_keyvalue against each other - raise RuntimeError( + msg = ( "keyvalue_equals() showed difference but" " diff_keyvalue() did not. This can be" " a bug in one of them or in the caller" " (assertModuleKeyValue())" ) + raise RuntimeError(msg) self.fail(self._formatMessage(msg, stdMsg)) def assertRasterFitsUnivar(self, raster, reference, precision=None, msg=None): @@ -1441,9 +1445,11 @@ def assertModuleFail(self, module, msg=None, **kwargs): def _module_from_parameters(module, **kwargs): if kwargs: if not isinstance(module, str): - raise ValueError("module can be only string or PyGRASS Module") + msg = "module can be only string or PyGRASS Module" + raise ValueError(msg) if isinstance(module, Module): - raise ValueError("module can be only string if other parameters are given") + msg = "module can be only string if other parameters are given" + raise ValueError(msg) # allow passing all parameters in one dictionary called parameters if list(kwargs.keys()) == ["parameters"]: kwargs = kwargs["parameters"] @@ -1454,20 +1460,24 @@ def _module_from_parameters(module, **kwargs): def _check_module_run_parameters(module): # in this case module already run and we would start it again if module.run_: - raise ValueError("Do not run the module manually, set run_=False") + msg = "Do not run the module manually, set run_=False" + raise ValueError(msg) if not module.finish_: - raise ValueError( + msg = ( "This function will always finish module run," " set finish_=None or finish_=True." ) + raise ValueError(msg) # we expect most of the usages with stdout=PIPE # TODO: in any case capture PIPE always? if module.stdout_ is None: module.stdout_ = subprocess.PIPE elif module.stdout_ != subprocess.PIPE: - raise ValueError("stdout_ can be only PIPE or None") + msg = "stdout_ can be only PIPE or None" + raise ValueError(msg) if module.stderr_ is None: module.stderr_ = subprocess.PIPE elif module.stderr_ != subprocess.PIPE: - raise ValueError("stderr_ can be only PIPE or None") + msg = "stderr_ can be only PIPE or None" + raise ValueError(msg) # because we want to capture it diff --git a/python/grass/gunittest/checkers.py b/python/grass/gunittest/checkers.py index c63f6d08ff0..d822a8ef45a 100644 --- a/python/grass/gunittest/checkers.py +++ b/python/grass/gunittest/checkers.py @@ -226,11 +226,10 @@ def text_to_keyvalue( # line contains something but not separator if not skip_invalid: # TODO: here should go _ for translation - raise ValueError( - ("Line <{l}> does not contain separator <{s}>.").format( - l=line, s=sep - ) + msg = ("Line <{l}> does not contain separator <{s}>.").format( + l=line, s=sep ) + raise ValueError(msg) # if we get here we are silently ignoring the line # because it is invalid (does not contain key-value separator) or # because it is empty @@ -277,9 +276,8 @@ def values_equal(value_a, value_b, precision=0.000001): # in Python 3 None < 3 raises TypeError precision = float(precision) if precision < 0: - raise ValueError( - "precision needs to be greater than or equal to zero: {precision} < 0" - ) + msg = "precision needs to be greater than or equal to zero: {precision} < 0" + raise ValueError(msg) if abs(value_a - value_b) > precision: return False diff --git a/python/grass/gunittest/invoker.py b/python/grass/gunittest/invoker.py index 29b62830e25..b6e3e5bca99 100644 --- a/python/grass/gunittest/invoker.py +++ b/python/grass/gunittest/invoker.py @@ -286,10 +286,11 @@ def run_in_location(self, gisdbase, location, location_type, results_dir, exclud not to one file as these will simply contain the last executed file. """ if os.path.abspath(results_dir) == os.path.abspath(self.start_dir): - raise RuntimeError( + msg = ( "Results root directory should not be the same" " as discovery start directory" ) + raise RuntimeError(msg) self.reporter = GrassTestFilesMultiReporter( reporters=[ GrassTestFilesTextReporter(stream=sys.stderr), diff --git a/python/grass/gunittest/main.py b/python/grass/gunittest/main.py index 741db5e43d2..fe39e7ca23b 100644 --- a/python/grass/gunittest/main.py +++ b/python/grass/gunittest/main.py @@ -147,7 +147,8 @@ def get_config(start_directory, config_file): # Does not check presence of the file config_parser.read(config_file) else: - raise ValueError("Either start_directory or config_file must be set") + msg = "Either start_directory or config_file must be set" + raise ValueError(msg) if "gunittest" not in config_parser: # Create an empty section if file is not available or section is not present. config_parser.read_dict({"gunittest": {}}) diff --git a/python/grass/gunittest/testsuite/data/samplecode/submodule_errors/subsubmodule_errors/testsuite/test_error.py b/python/grass/gunittest/testsuite/data/samplecode/submodule_errors/subsubmodule_errors/testsuite/test_error.py index 0be341770a6..d0a6b609479 100644 --- a/python/grass/gunittest/testsuite/data/samplecode/submodule_errors/subsubmodule_errors/testsuite/test_error.py +++ b/python/grass/gunittest/testsuite/data/samplecode/submodule_errors/subsubmodule_errors/testsuite/test_error.py @@ -6,7 +6,8 @@ class TestError(TestCase): # pylint: disable=R0904 def test_something(self): - raise RuntimeError("Error in test function") + msg = "Error in test function" + raise RuntimeError(msg) self.assertTrue(True) @@ -14,7 +15,8 @@ class TestErrorSetUp(TestCase): # pylint: disable=R0904 def setUp(self): - raise RuntimeError("Error in setUp") + msg = "Error in setUp" + raise RuntimeError(msg) def test_something(self): self.assertTrue(True) @@ -24,7 +26,8 @@ class TestErrorTearDown(TestCase): # pylint: disable=R0904 def tearDown(self): - raise RuntimeError("Error in tearDown") + msg = "Error in tearDown" + raise RuntimeError(msg) def test_something(self): self.assertTrue(True) @@ -35,7 +38,8 @@ class TestErrorClassSetUp(TestCase): @classmethod def setUpClass(cls): - raise RuntimeError("Error in setUpClass") + msg = "Error in setUpClass" + raise RuntimeError(msg) def test_something(self): self.assertTrue(True) @@ -46,7 +50,8 @@ class TestErrorClassTearDown(TestCase): @classmethod def tearDownClass(cls): - raise RuntimeError("Error in tearDownClass") + msg = "Error in tearDownClass" + raise RuntimeError(msg) def test_something(self): self.assertTrue(True) diff --git a/python/grass/gunittest/testsuite/data/samplecode/testsuite/test_good_and_bad.py b/python/grass/gunittest/testsuite/data/samplecode/testsuite/test_good_and_bad.py index ef3f36b89bd..d9e207d6359 100644 --- a/python/grass/gunittest/testsuite/data/samplecode/testsuite/test_good_and_bad.py +++ b/python/grass/gunittest/testsuite/data/samplecode/testsuite/test_good_and_bad.py @@ -15,7 +15,8 @@ def test_something_failing(self): self.assertTrue(False, msg="This failed in test_good_and_bad") def test_something_erroring(self): - raise RuntimeError("Some error which was raised") + msg = "Some error which was raised" + raise RuntimeError(msg) self.assertTrue(True, msg="This should not fail in test_good_and_bad") diff --git a/python/grass/imaging/images2avi.py b/python/grass/imaging/images2avi.py index 9776b9c0db2..776cb1c6b95 100644 --- a/python/grass/imaging/images2avi.py +++ b/python/grass/imaging/images2avi.py @@ -193,7 +193,8 @@ def readAvi(filename, asNumpy=True): print(S.stderr.read()) # Clean up _cleanDir(tempDir) - raise RuntimeError("Could not read avi.") + msg = "Could not read avi." + raise RuntimeError(msg) # Read images images = images2ims.readIms(os.path.join(tempDir, "im*.jpg"), asNumpy) diff --git a/python/grass/imaging/images2gif.py b/python/grass/imaging/images2gif.py index d37ec0c4e32..2218233d7d9 100644 --- a/python/grass/imaging/images2gif.py +++ b/python/grass/imaging/images2gif.py @@ -133,9 +133,11 @@ def checkImages(images): pass # ok elif im.ndim == 3: if im.shape[2] not in [3, 4]: - raise ValueError("This array can not represent an image.") + msg = "This array can not represent an image." + raise ValueError(msg) else: - raise ValueError("This array can not represent an image.") + msg = "This array can not represent an image." + raise ValueError(msg) else: raise ValueError("Invalid image type: " + str(type(im))) @@ -267,7 +269,8 @@ def handleSubRectangles(self, images, subRectangles): if len(xy) == len(images): xy = list(xy) else: - raise ValueError("len(xy) doesn't match amount of images.") + msg = "len(xy) doesn't match amount of images." + raise ValueError(msg) else: xy = [xy for im in images] xy[0] = (0, 0) @@ -275,9 +278,10 @@ def handleSubRectangles(self, images, subRectangles): else: # Calculate xy using some basic image processing - # Check Numpy + # Check NumPy if np is None: - raise RuntimeError("Need Numpy to use auto-subRectangles.") + msg = "Need NumPy to use auto-subRectangles." + raise RuntimeError(msg) # First make numpy arrays if required for i in range(len(images)): @@ -286,9 +290,8 @@ def handleSubRectangles(self, images, subRectangles): tmp = im.convert() # Make without palette a = np.asarray(tmp) if len(a.shape) == 0: - raise MemoryError( - "Too little memory to convert PIL image to array" - ) + msg = "Too little memory to convert PIL image to array" + raise MemoryError(msg) images[i] = a # Determine the sub rectangles @@ -314,9 +317,10 @@ def getSubRectangles(self, ims): if len(ims) < 2: return ims, [(0, 0) for i in ims] - # We need numpy + # We need NumPy if np is None: - raise RuntimeError("Need Numpy to calculate sub-rectangles. ") + msg = "Need NumPy to calculate sub-rectangles." + raise RuntimeError(msg) # Prepare ims2 = [ims[0]] @@ -575,7 +579,8 @@ def writeGifVisvis( # Check PIL if PIL is None: - raise RuntimeError("Need PIL to write animated gif files.") + msg = "Need PIL to write animated gif files." + raise RuntimeError(msg) # Check images images = checkImages(images) @@ -596,7 +601,8 @@ def writeGifVisvis( if len(duration) == len(images): duration = list(duration) else: - raise ValueError("len(duration) doesn't match amount of images.") + msg = "len(duration) doesn't match amount of images." + raise ValueError(msg) else: duration = [duration for im in images] @@ -614,7 +620,8 @@ def writeGifVisvis( dispose = defaultDispose if hasattr(dispose, "__len__"): if len(dispose) != len(images): - raise ValueError("len(xy) doesn't match amount of images.") + msg = "len(xy) doesn't match amount of images." + raise ValueError(msg) else: dispose = [dispose for im in images] @@ -637,11 +644,13 @@ def readGif(filename, asNumpy=True): # Check PIL if PIL is None: - raise RuntimeError("Need PIL to read animated gif files.") + msg = "Need PIL to read animated gif files." + raise RuntimeError(msg) - # Check Numpy + # Check NumPy if np is None: - raise RuntimeError("Need Numpy to read animated gif files.") + msg = "Need NumPy to read animated gif files." + raise RuntimeError(msg) # Check whether it exists if not os.path.isfile(filename): @@ -659,7 +668,8 @@ def readGif(filename, asNumpy=True): tmp = pilIm.convert() # Make without palette a = np.asarray(tmp) if len(a.shape) == 0: - raise MemoryError("Too little memory to convert PIL image to array") + msg = "Too little memory to convert PIL image to array" + raise MemoryError(msg) # Store, and next images.append(a) pilIm.seek(pilIm.tell() + 1) @@ -795,15 +805,18 @@ def setconstants(self, samplefac, colors): self.a_s = {} def __init__(self, image, samplefac=10, colors=256): - # Check Numpy + # Check NumPy if np is None: - raise RuntimeError("Need Numpy for the NeuQuant algorithm.") + msg = "Need NumPy for the NeuQuant algorithm." + raise RuntimeError(msg) # Check image if image.size[0] * image.size[1] < NeuQuant.MAXPRIME: - raise OSError("Image is too small") + msg = "Image is too small" + raise OSError(msg) if image.mode != "RGBA": - raise OSError("Image mode should be RGBA.") + msg = "Image mode should be RGBA." + raise OSError(msg) # Initialize self.setconstants(samplefac, colors) diff --git a/python/grass/imaging/images2ims.py b/python/grass/imaging/images2ims.py index d86a2247952..d3bbc12afe0 100644 --- a/python/grass/imaging/images2ims.py +++ b/python/grass/imaging/images2ims.py @@ -81,9 +81,11 @@ def checkImages(images): pass # ok elif im.ndim == 3: if im.shape[2] not in [3, 4]: - raise ValueError("This array can not represent an image.") + msg = "This array can not represent an image." + raise ValueError(msg) else: - raise ValueError("This array can not represent an image.") + msg = "This array can not represent an image." + raise ValueError(msg) else: raise ValueError("Invalid image type: " + str(type(im))) @@ -145,7 +147,8 @@ def writeIms(filename, images): # Check PIL if PIL is None: - raise RuntimeError("Need PIL to write series of image files.") + msg = "Need PIL to write series of image files." + raise RuntimeError(msg) # Check images images = checkImages(images) @@ -185,11 +188,13 @@ def readIms(filename, asNumpy=True): # Check PIL if PIL is None: - raise RuntimeError("Need PIL to read a series of image files.") + msg = "Need PIL to read a series of image files." + raise RuntimeError(msg) - # Check Numpy + # Check NumPy if asNumpy and np is None: - raise RuntimeError("Need Numpy to return numpy arrays.") + msg = "Need NumPy to return numpy arrays." + raise RuntimeError(msg) # Get dirname and filename filename = os.path.abspath(filename) @@ -229,7 +234,8 @@ def readIms(filename, asNumpy=True): # Make numpy array a = np.asarray(im) if len(a.shape) == 0: - raise MemoryError("Too little memory to convert PIL image to array") + msg = "Too little memory to convert PIL image to array" + raise MemoryError(msg) # Add images.append(a) diff --git a/python/grass/imaging/images2swf.py b/python/grass/imaging/images2swf.py index c262a352272..6a5bbacae5c 100644 --- a/python/grass/imaging/images2swf.py +++ b/python/grass/imaging/images2swf.py @@ -126,9 +126,11 @@ def checkImages(images): pass # ok elif im.ndim == 3: if im.shape[2] not in [3, 4]: - raise ValueError("This array can not represent an image.") + msg = "This array can not represent an image." + raise ValueError(msg) else: - raise ValueError("This array can not represent an image.") + msg = "This array can not represent an image." + raise ValueError(msg) else: raise ValueError("Invalid image type: " + str(type(im))) @@ -177,7 +179,8 @@ def Append(self, bits): if isinstance(bits, int): bits = str(bits) if not isinstance(bits, string_types): - raise ValueError("Append bits as strings or integers!") + msg = "Append bits as strings or integers!" + raise ValueError(msg) # add bits for bit in bits: @@ -240,7 +243,8 @@ def intToBits(i: int, n: int | None = None) -> BitArray: # justify if n is not None: if len(bb) > n: - raise ValueError("intToBits fail: len larger than padlength.") + msg = f"{intToBits.__name__} fail: len larger than padlength." + raise ValueError(msg) bb = str(bb).rjust(n, "0") # done @@ -319,7 +323,8 @@ def signedIntToBits(i: int, n: int | None = None) -> BitArray: bb = "0" + str(bb) # always need the sign bit in front if n is not None: if len(bb) > n: - raise ValueError("signedIntToBits fail: len larger than padlength.") + msg = f"{signedIntToBits.__name__} fail: len larger than padlength." + raise ValueError(msg) bb = bb.rjust(n, "0") # was it negative? (then opposite bits) @@ -361,7 +366,8 @@ def floatsToBits(arr): bits = intToBits(31, 5) # 32 does not fit in 5 bits! for i in arr: if i < 0: - raise ValueError("Dit not implement negative floats!") + msg = "Dit not implement negative floats!" + raise ValueError(msg) i1 = int(i) i2 = i - i1 bits += intToBits(i1, 15) @@ -551,14 +557,16 @@ def __init__(self, im): if im.shape[2] == 4: tmp[:, :, 0] = im[:, :, 3] # swap channel where alpha is in else: - raise ValueError("Invalid shape to be an image.") + msg = "Invalid shape to be an image." + raise ValueError(msg) elif len(im.shape) == 2: tmp = np.ones((im.shape[0], im.shape[1], 4), dtype=np.uint8) * 255 for i in range(3): tmp[:, :, i + 1] = im[:, :] else: - raise ValueError("Invalid shape to be an image.") + msg = "Invalid shape to be an image." + raise ValueError(msg) # we changed the image to uint8 4 channels. # now compress! @@ -772,22 +780,25 @@ def writeSwf(filename, images, duration=0.1, repeat=True): """ - # Check Numpy + # Check NumPy if np is None: - raise RuntimeError("Need Numpy to write an SWF file.") + msg = "Need NumPy to write an SWF file." + raise RuntimeError(msg) # Check images (make all NumPy) images2 = [] images = checkImages(images) if not images: - raise ValueError("Image list is empty!") + msg = "Image list is empty!" + raise ValueError(msg) for im in images: if PIL and isinstance(im, PIL.Image.Image): if im.mode == "P": im = im.convert() im = np.asarray(im) if len(im.shape) == 0: - raise MemoryError("Too little memory to convert PIL image to array") + msg = "Too little memory to convert PIL image to array" + raise MemoryError(msg) images2.append(im) # Init @@ -798,7 +809,8 @@ def writeSwf(filename, images, duration=0.1, repeat=True): if len(duration) == len(images2): duration = list(duration) else: - raise ValueError("len(duration) doesn't match amount of images.") + msg = "len(duration) doesn't match amount of images." + raise ValueError(msg) else: duration = [duration for im in images2] @@ -836,9 +848,10 @@ def writeSwf(filename, images, duration=0.1, repeat=True): def _readPixels(bb, i, tagType, L1): """With pf's seed after the recordheader, reads the pixeldata.""" - # Check Numpy + # Check NumPy if np is None: - raise RuntimeError("Need Numpy to read an SWF file.") + msg = "Need NumPy to read an SWF file." + raise RuntimeError(msg) # Get info # charId = bb[i : i + 2] # unused @@ -898,11 +911,13 @@ def readSwf(filename, asNumpy=True): # Check PIL if (not asNumpy) and (PIL is None): - raise RuntimeError("Need PIL to return as PIL images.") + msg = "Need PIL to return as PIL images." + raise RuntimeError(msg) - # Check Numpy + # Check NumPy if np is None: - raise RuntimeError("Need Numpy to read SWF files.") + msg = "Need NumPy to read SWF files." + raise RuntimeError(msg) # Init images images = [] diff --git a/python/grass/jupyter/map.py b/python/grass/jupyter/map.py index 013ff693470..dc78be31208 100644 --- a/python/grass/jupyter/map.py +++ b/python/grass/jupyter/map.py @@ -163,7 +163,8 @@ def run(self, module, **kwargs): self._region_manager.adjust_rendering_size_from_region() gs.run_command(module, env=self._env, **kwargs) else: - raise ValueError("Module must begin with letter 'd'.") + msg = "Module must begin with letter 'd'." + raise ValueError(msg) def __getattr__(self, name): """Parse attribute to GRASS display module. Attribute should be in diff --git a/python/grass/jupyter/seriesmap.py b/python/grass/jupyter/seriesmap.py index ae6bde911b6..aaed821d1eb 100644 --- a/python/grass/jupyter/seriesmap.py +++ b/python/grass/jupyter/seriesmap.py @@ -158,9 +158,10 @@ def render(self): (i.e. show or save). """ if not self._baseseries_added: - raise RuntimeError( + msg = ( "Cannot render series since none has been added." "Use SeriesMap.add_rasters() or SeriesMap.add_vectors()" ) + raise RuntimeError(msg) tasks = [(i,) for i in range(self.baseseries)] self._render(tasks) diff --git a/python/grass/jupyter/timeseriesmap.py b/python/grass/jupyter/timeseriesmap.py index 2acfa575126..0379e19a4c0 100644 --- a/python/grass/jupyter/timeseriesmap.py +++ b/python/grass/jupyter/timeseriesmap.py @@ -170,7 +170,8 @@ def add_raster_series(self, baseseries, fill_gaps=False): :param bool fill_gaps: fill empty time steps with data from previous step """ if self._baseseries_added and self.baseseries != baseseries: - raise AttributeError("Cannot add more than one space time dataset") + msg = "Cannot add more than one space time dataset" + raise AttributeError(msg) self._element_type = "strds" check_timeseries_exists(baseseries, self._element_type) self.baseseries = baseseries @@ -193,7 +194,8 @@ def add_vector_series(self, baseseries, fill_gaps=False): :param bool fill_gaps: fill empty time steps with data from previous step """ if self._baseseries_added and self.baseseries != baseseries: - raise AttributeError("Cannot add more than one space time dataset") + msg = "Cannot add more than one space time dataset" + raise AttributeError(msg) self._element_type = "stvds" check_timeseries_exists(baseseries, self._element_type) self.baseseries = baseseries @@ -293,11 +295,12 @@ def _render_worker(self, date, layer, filename): def render(self): """Renders image for each time-step in space-time dataset.""" if not self._baseseries_added: - raise RuntimeError( + msg = ( "Cannot render space time dataset since none has been added." " Use TimeSeriesMap.add_raster_series() or " "TimeSeriesMap.add_vector_series() to add dataset" ) + raise RuntimeError(msg) # Create name for empty layers random_name_none = gs.append_random("none", 8) + ".png" diff --git a/python/grass/pygrass/gis/__init__.py b/python/grass/pygrass/gis/__init__.py index 29fecd3d699..c0d0bbde752 100644 --- a/python/grass/pygrass/gis/__init__.py +++ b/python/grass/pygrass/gis/__init__.py @@ -113,9 +113,11 @@ def make_mapset(mapset, location=None, gisdbase=None): :type gisdbase: str""" res = libgis.G_make_mapset(gisdbase, location, mapset) if res == -1: - raise GrassError("Cannot create new mapset") + msg = "Cannot create new mapset" + raise GrassError(msg) if res == -2: - raise GrassError("Illegal name") + msg = "Illegal name" + raise GrassError(msg) class Gisdbase: @@ -171,7 +173,8 @@ def __iter__(self): # TODO remove or complete this function def new_location(self): if libgis.G_make_location() != 0: - raise GrassError("Cannot create new location") + msg = "Cannot create new location" + raise GrassError(msg) def locations(self): """Return a list of locations that are available in the gisdbase: :: @@ -402,7 +405,8 @@ def current(self): def delete(self): """Delete the mapset""" if self.is_current(): - raise GrassError("The mapset is in use.") + msg = "The mapset is in use." + raise GrassError(msg) shutil.rmtree(self.path()) def path(self): @@ -459,7 +463,8 @@ def add(self, mapset): with open(self.spath, "a+") as f: f.write("%s\n" % mapset) else: - raise TypeError("Mapset not found") + msg = "Mapset not found" + raise TypeError(msg) def remove(self, mapset): """Remove mapset to the search path diff --git a/python/grass/pygrass/gis/region.py b/python/grass/pygrass/gis/region.py index 892a3664b49..50640c22494 100644 --- a/python/grass/pygrass/gis/region.py +++ b/python/grass/pygrass/gis/region.py @@ -448,7 +448,8 @@ def from_rast(self, raster_name): .. """ if not raster_name: - raise ValueError("Raster name or mapset are invalid") + msg = "Raster name or mapset are invalid" + raise ValueError(msg) mapset = get_mapset_raster(raster_name) @@ -602,7 +603,8 @@ def write(self): """ self.adjust() if libgis.G_put_window(self.byref()) < 0: - raise GrassError("Cannot change region (WIND file).") + msg = "Cannot change region (WIND file)." + raise GrassError(msg) def read_default(self): """ diff --git a/python/grass/pygrass/modules/interface/docstring.py b/python/grass/pygrass/modules/interface/docstring.py index 397338fcbb8..86c556559bf 100644 --- a/python/grass/pygrass/modules/interface/docstring.py +++ b/python/grass/pygrass/modules/interface/docstring.py @@ -47,7 +47,9 @@ def __get__(self, obj, type=None): return self.fget(obj) def __set__(self, obj, value): - raise AttributeError("can't set attribute") + msg = "Can't set attribute" + raise AttributeError(msg) def __delete__(self, obj): - raise AttributeError("can't delete attribute") + msg = "Can't delete attribute" + raise AttributeError(msg) diff --git a/python/grass/pygrass/modules/interface/env.py b/python/grass/pygrass/modules/interface/env.py index d3d6e371238..e355a5af30e 100644 --- a/python/grass/pygrass/modules/interface/env.py +++ b/python/grass/pygrass/modules/interface/env.py @@ -12,7 +12,8 @@ def get_env(): """Parse the GISRC file and return the GRASS variales""" gisrc = os.environ.get("GISRC") if gisrc is None: - raise RuntimeError("You are not in a GRASS session, GISRC not found.") + msg = "You are not in a GRASS session, GISRC not found." + raise RuntimeError(msg) with open(gisrc) as grc: return { k.strip(): v.strip() for k, v in [row.split(":", 1) for row in grc if row] diff --git a/python/grass/pygrass/modules/interface/module.py b/python/grass/pygrass/modules/interface/module.py index 7f70d82bac1..10c38a12990 100644 --- a/python/grass/pygrass/modules/interface/module.py +++ b/python/grass/pygrass/modules/interface/module.py @@ -548,7 +548,8 @@ def __init__(self, cmd, *args, **kargs): if isinstance(cmd, str): self.name = cmd else: - raise GrassError("Problem initializing the module {s}".format(s=cmd)) + msg = "Problem initializing the module {s}".format(s=cmd) + raise GrassError(msg) try: # call the command with --interface-description get_cmd_xml = Popen([cmd, "--interface-description"], stdout=PIPE) diff --git a/python/grass/pygrass/modules/interface/parameter.py b/python/grass/pygrass/modules/interface/parameter.py index d950cd40008..4c9b8571250 100644 --- a/python/grass/pygrass/modules/interface/parameter.py +++ b/python/grass/pygrass/modules/interface/parameter.py @@ -112,10 +112,11 @@ def check_string(value): good = True break if not good: - raise ValueError( - f"The Parameter <{param.name}>, must be one of the following " + msg = ( + f"The parameter <{param.name}>, must be one of the following " f"values: {param.values!r} not '{newvalue}'" ) + raise ValueError(msg) return ( ( [ @@ -148,7 +149,7 @@ class Parameter: >>> param.value = 3 Traceback (most recent call last): ... - ValueError: The Parameter , must be one of the following values: [2, 4, 6, 8] not '3' + ValueError: The parameter , must be one of the following values: [2, 4, 6, 8] not '3' ... """ # noqa: E501 @@ -160,7 +161,8 @@ def __init__(self, xparameter=None, diz=None): self.max = None diz = element2dict(xparameter) if xparameter is not None else diz if diz is None: - raise TypeError("Xparameter or diz are required") + msg = "xparameter or diz are required" + raise TypeError(msg) self.name = diz["name"] self.required = diz["required"] == "yes" self.multiple = diz["multiple"] == "yes" diff --git a/python/grass/pygrass/raster/__init__.py b/python/grass/pygrass/raster/__init__.py index 9967d62d98e..6578b96d9df 100644 --- a/python/grass/pygrass/raster/__init__.py +++ b/python/grass/pygrass/raster/__init__.py @@ -217,7 +217,8 @@ def open(self, mode=None, mtype=None, overwrite=None): raise OpenError(_("Raster type not defined")) self._fd = libraster.Rast_open_new(self.name, self._gtype) else: - raise OpenError("Open mode: %r not supported, valid mode are: r, w") + msg = "Open mode: %r not supported, valid mode are: r, w" + raise OpenError(msg) # read rows and cols from the active region self._rows = libraster.Rast_window_rows() self._cols = libraster.Rast_window_cols() @@ -339,7 +340,8 @@ def __setitem__(self, key, row): if key >= self._rows: raise IndexError(_("Index out of range: %r.") % key) return self.put_row(key, row) - raise TypeError("Invalid argument type.") + msg = "Invalid argument type." + raise TypeError(msg) @must_be_open def map2segment(self): diff --git a/python/grass/pygrass/raster/abstract.py b/python/grass/pygrass/raster/abstract.py index 68b5e501ed4..3215eb31191 100644 --- a/python/grass/pygrass/raster/abstract.py +++ b/python/grass/pygrass/raster/abstract.py @@ -398,15 +398,15 @@ def __getitem__(self, key): return self.get(x, y) if isinstance(key, int): if not self.is_open(): - raise IndexError("Can not operate on a closed map. Call open() first.") + msg = "Can not operate on a closed map. Call open() first." + raise IndexError(msg) if key < 0: # Handle negative indices key += self._rows if key >= self._rows: - raise IndexError( - "The row index {0} is out of range [0, {1}).".format( - key, self._rows - ) + msg = "The row index {0} is out of range [0, {1}).".format( + key, self._rows ) + raise IndexError(msg) return self.get_row(key) fatal("Invalid argument type.") diff --git a/python/grass/pygrass/raster/category.py b/python/grass/pygrass/raster/category.py index 9ace632d136..20fca524da5 100644 --- a/python/grass/pygrass/raster/category.py +++ b/python/grass/pygrass/raster/category.py @@ -121,9 +121,11 @@ def _chk_value(self, value): label, min_cat = value value = (label, min_cat, None) elif length < 2 or length > 3: - raise TypeError("Tuple with a length that is not supported.") + msg = "Tuple with a length that is not supported." + raise TypeError(msg) else: - raise TypeError("Only Tuple are supported.") + msg = "Only tuples are supported." + raise TypeError(msg) return value def __getitem__(self, index): @@ -204,7 +206,8 @@ def set_cat(self, index, value): elif index < (len(self)): self[index] = value else: - raise TypeError("Index outside range.") + msg = "Index outside range." + raise TypeError(msg) def reset(self): for i in range(len(self) - 1, -1, -1): @@ -244,7 +247,8 @@ def read(self): self.name, self.mapset, ctypes.byref(self.c_cats) ) if err == -1: - raise GrassError("Can not read the categories.") + msg = "Can not read the categories." + raise GrassError(msg) # copy from C struct to list self._read_cats() @@ -280,7 +284,8 @@ def set_cats_fmt(self, fmt, m1, a1, m2, a2): void Rast_set_cats_fmt() """ # TODO: add - raise ImplementationError("set_cats_fmt() is not implemented yet.") + msg = f"{self.set_cats_fmt.__name__}() is not implemented yet." + raise ImplementationError(msg) def read_rules(self, filename, sep=":"): """Copy categories from a rules file, default separator is ':', the @@ -308,7 +313,8 @@ def read_rules(self, filename, sep=":"): elif len(cat) == 3: label, min_cat, max_cat = cat else: - raise TypeError("Row length is greater than 3") + msg = "Row length is greater than 3" + raise TypeError(msg) self.append((label, min_cat, max_cat)) def write_rules(self, filename, sep=":"): diff --git a/python/grass/pygrass/raster/rowio.py b/python/grass/pygrass/raster/rowio.py index ed43c9a8452..a49da7efe26 100644 --- a/python/grass/pygrass/raster/rowio.py +++ b/python/grass/pygrass/raster/rowio.py @@ -64,7 +64,8 @@ def open(self, fd, rows, cols, mtype): ) == -1 ): - raise GrassError("Fatal error, Rowio not setup correctly.") + msg = f"Fatal error, {RowIO.__name__} not setup correctly." + raise GrassError(msg) def release(self): librowio.Rowio_release(ctypes.byref(self.c_rowio)) diff --git a/python/grass/pygrass/rpc/base.py b/python/grass/pygrass/rpc/base.py index e12bea9f985..5b811d2a7f7 100644 --- a/python/grass/pygrass/rpc/base.py +++ b/python/grass/pygrass/rpc/base.py @@ -49,7 +49,8 @@ def dummy_server(lock: _LockLike, conn: Connection) -> NoReturn: conn.close() sys.exit() if data[0] == 1: - raise Exception("Server process intentionally killed by exception") + msg = "Server process intentionally killed by exception" + raise Exception(msg) class RPCServerBase: diff --git a/python/grass/pygrass/utils.py b/python/grass/pygrass/utils.py index 2d6a2498848..46ceea7e50e 100644 --- a/python/grass/pygrass/utils.py +++ b/python/grass/pygrass/utils.py @@ -354,7 +354,8 @@ def r_export(rast, output="", fmt="png", **kargs): **kargs, ) return output - raise ValueError("Raster map does not exist.") + msg = "Raster map does not exist." + raise ValueError(msg) def get_lib_path(modname, libname=None): diff --git a/python/grass/pygrass/vector/__init__.py b/python/grass/pygrass/vector/__init__.py index 7313af1fd34..df18f3c110b 100644 --- a/python/grass/pygrass/vector/__init__.py +++ b/python/grass/pygrass/vector/__init__.py @@ -117,7 +117,8 @@ def next(self): def rewind(self): """Rewind vector map to cause reads to start at beginning.""" if libvect.Vect_rewind(self.c_mapinfo) == -1: - raise GrassError("Vect_rewind raise an error.") + msg = "Vect_rewind raise an error." + raise GrassError(msg) @must_be_open def write(self, geo_obj, cat=None, attrs=None): @@ -228,7 +229,8 @@ def write(self, geo_obj, cat=None, attrs=None): self.c_mapinfo, geo_obj.gtype, geo_obj.c_points, geo_obj.c_cats ) if result == -1: - raise GrassError("Not able to write the vector feature.") + msg = "Not able to write the vector feature." + raise GrassError(msg) if self._topo_level == 2: # return new feature id (on level 2) geo_obj.id = result @@ -645,7 +647,8 @@ def rewrite(self, geo_obj, cat, attrs=None, **kargs): self.c_mapinfo, cat, geo_obj.gtype, geo_obj.c_points, geo_obj.c_cats ) if result == -1: - raise GrassError("Not able to write the vector feature.") + msg = "Not able to write the vector feature." + raise GrassError(msg) # return offset into file where the feature starts geo_obj.offset = result @@ -658,7 +661,8 @@ def delete(self, feature_id): :type feature_id: int """ if libvect.Vect_rewrite_line(self.c_mapinfo, feature_id) == -1: - raise GrassError("C function: Vect_rewrite_line.") + msg = "C function: Vect_rewrite_line." + raise GrassError(msg) @must_be_open def restore(self, geo_obj): @@ -667,16 +671,19 @@ def restore(self, geo_obj): libvect.Vect_restore_line(self.c_mapinfo, geo_obj.offset, geo_obj.id) == -1 ): - raise GrassError("C function: Vect_restore_line.") + msg = "C function: Vect_restore_line." + raise GrassError(msg) else: - raise ValueError("The value have not an offset attribute.") + msg = "The value have not an offset attribute." + raise ValueError(msg) @must_be_open def bbox(self): - """Return the BBox of the vecor map""" + """Return the BBox of the vector map""" bbox = Bbox() if libvect.Vect_get_map_box(self.c_mapinfo, bbox.c_bbox) == 0: - raise GrassError("I can not find the Bbox.") + msg = "I can not find the Bbox." + raise GrassError(msg) return bbox def close(self, build=True, release=True): diff --git a/python/grass/pygrass/vector/abstract.py b/python/grass/pygrass/vector/abstract.py index 79307f0d354..00bef3997f2 100644 --- a/python/grass/pygrass/vector/abstract.py +++ b/python/grass/pygrass/vector/abstract.py @@ -284,7 +284,8 @@ def rename(self, newname): if not self.is_open(): utils.rename(self.name, newname, "vect") else: - raise GrassError("The map is open, not able to renamed it.") + msg = "The map is open, not able to rename it." + raise GrassError(msg) self._name = newname def is_3D(self): @@ -360,12 +361,14 @@ def open( if not self.exist() and self.mode != "w": raise OpenError("Map <%s> not found." % self._name) if libvect.Vect_set_open_level(self._topo_level) != 0: - raise OpenError("Invalid access level.") + msg = "Invalid access level." + raise OpenError(msg) # update the overwrite attribute self.overwrite = overwrite if overwrite is not None else self.overwrite # check if the mode is valid if self.mode not in {"r", "rw", "w"}: - raise ValueError("Mode not supported. Use one of: 'r', 'rw', 'w'.") + msg = "Mode not supported. Use one of: 'r', 'rw', 'w'." + raise ValueError(msg) # check if the map exist if self.exist() and self.mode in {"r", "rw"}: diff --git a/python/grass/pygrass/vector/basic.py b/python/grass/pygrass/vector/basic.py index f031e23ff98..86eed054340 100644 --- a/python/grass/pygrass/vector/basic.py +++ b/python/grass/pygrass/vector/basic.py @@ -311,13 +311,15 @@ def __getitem__(self, key): if key < 0: # Handle negative indices key += self.c_ilist.contents.n_values if key >= self.c_ilist.contents.n_values: - raise IndexError("Index out of range") + msg = "Index out of range" + raise IndexError(msg) return self.c_ilist.contents.value[key] raise ValueError("Invalid argument type: %r." % key) def __setitem__(self, key, value): if self.contains(value): - raise ValueError("Integer already in the list") + msg = "Integer already in the list" + raise ValueError(msg) self.c_ilist.contents.value[key] = int(value) def __len__(self): diff --git a/python/grass/pygrass/vector/geometry.py b/python/grass/pygrass/vector/geometry.py index b734161d1ea..9e4ff6e3b09 100644 --- a/python/grass/pygrass/vector/geometry.py +++ b/python/grass/pygrass/vector/geometry.py @@ -611,7 +611,8 @@ def buffer( dist_x = dist dist_y = dist elif not dist_x or not dist_y: - raise TypeError("TypeError: buffer expected 1 arguments, got 0") + msg = "buffer expected 1 arguments, got 0" + raise TypeError(msg) bound = Line() p_points = ctypes.pointer(bound.c_points) libvect.Vect_point_buffer2( @@ -675,7 +676,8 @@ def __getitem__(self, key): if key < 0: # Handle negative indices key += self.c_points.contents.n_points if key >= self.c_points.contents.n_points: - raise IndexError("Index out of range") + msg = "Index out of range" + raise IndexError(msg) return Point( self.c_points.contents.x[key], self.c_points.contents.y[key], @@ -743,7 +745,8 @@ def point_on_line(self, distance, angle=0, slope=0): ctypes.pointer(ctypes.c_double(angle)), ctypes.pointer(ctypes.c_double(slope)), ): - raise ValueError("Vect_point_on_line give an error.") + msg = "Vect_point_on_line gave an error." + raise ValueError(msg) pnt.is2D = self.is2D return pnt @@ -845,7 +848,8 @@ def insert(self, indx, pnt): if indx < 0: # Handle negative indices indx += self.c_points.contents.n_points if indx >= self.c_points.contents.n_points: - raise IndexError("Index out of range") + msg = "Index out of range" + raise IndexError(msg) x, y, z = get_xyz(pnt) libvect.Vect_line_insert_point(self.c_points, indx, x, y, z) @@ -949,7 +953,8 @@ def pop(self, indx): if indx < 0: # Handle negative indices indx += self.c_points.contents.n_points if indx >= self.c_points.contents.n_points: - raise IndexError("Index out of range") + msg = "Index out of range" + raise IndexError(msg) pnt = self[indx] libvect.Vect_line_delete_point(self.c_points, indx) return pnt @@ -968,7 +973,8 @@ def delete(self, indx): if indx < 0: # Handle negative indices indx += self.c_points.contents.n_points if indx >= self.c_points.contents.n_points: - raise IndexError("Index out of range") + msg = "Index out of range" + raise IndexError(msg) libvect.Vect_line_delete_point(self.c_points, indx) def prune(self): @@ -1024,7 +1030,8 @@ def remove(self, pnt): if pnt == point: libvect.Vect_line_delete_point(self.c_points, indx) return - raise ValueError("list.remove(x): x not in list") + msg = "list.remove(x): x not in list" + raise ValueError(msg) def reverse(self): """Reverse the order of vertices, using `Vect_line_reverse` @@ -1173,7 +1180,8 @@ def buffer( dist_x = dist dist_y = dist elif not dist_x or not dist_y: - raise TypeError("TypeError: buffer expected 1 arguments, got 0") + msg = "buffer expected 1 arguments, got 0" + raise TypeError(msg) p_bound = ctypes.pointer(ctypes.pointer(libvect.line_pnts())) pp_isle = ctypes.pointer(ctypes.pointer(ctypes.pointer(libvect.line_pnts()))) n_isles = ctypes.pointer(ctypes.c_int()) @@ -1296,7 +1304,8 @@ def to_wkb(self): TODO: Must be implemented """ - raise Exception("Not implemented") + msg = "Not implemented" + raise Exception(msg) def ilines(self, only_in=False, only_out=False): """Return a generator with all lines id connected to a node. @@ -1507,7 +1516,8 @@ def to_wkt(self): def to_wkb(self): """Return a "well know text" (WKB) geometry array. ::""" - raise Exception("Not implemented") + msg = "Not implemented" + raise Exception(msg) @mapinfo_must_be_set def points_geos(self): @@ -1723,7 +1733,8 @@ def buffer( dist_x = dist dist_y = dist elif not dist_x or not dist_y: - raise TypeError("TypeError: buffer expected 1 arguments, got 0") + msg = "buffer expected 1 arguments, got 0" + raise TypeError(msg) p_bound = ctypes.pointer(ctypes.pointer(libvect.line_pnts())) pp_isle = ctypes.pointer(ctypes.pointer(ctypes.pointer(libvect.line_pnts()))) n_isles = ctypes.pointer(ctypes.c_int()) @@ -1901,7 +1912,8 @@ def c_read_line(feature_id, c_mapinfo, c_points, c_cats): if feature_id < 0: # Handle negative indices feature_id += nmax + 1 if feature_id > nmax: - raise IndexError("Index out of range") + msg = "Index out of range" + raise IndexError(msg) if feature_id > 0: ftype = libvect.Vect_read_line(c_mapinfo, c_points, c_cats, feature_id) return feature_id, ftype, c_points, c_cats diff --git a/python/grass/pygrass/vector/table.py b/python/grass/pygrass/vector/table.py index a58b83b8077..f8758aa38e5 100644 --- a/python/grass/pygrass/vector/table.py +++ b/python/grass/pygrass/vector/table.py @@ -133,7 +133,8 @@ def limit(self, number): :type number: int """ if not isinstance(number, int): - raise ValueError("Must be an integer.") + msg = "Must be an integer." + raise ValueError(msg) self._limit = "LIMIT {number}".format(number=number) return self @@ -561,7 +562,8 @@ def cast(self, col_name, new_type): self.update_odict() else: # sqlite does not support rename columns: - raise DBError("SQLite does not support to cast columns.") + msg = "SQLite does not support to cast columns." + raise DBError(msg) def drop(self, col_name): """Drop a column from the table. @@ -663,7 +665,8 @@ def _get_layer(self): def _set_layer(self, number): if number <= 0: - raise TypeError("Number must be positive and greater than 0.") + msg = "Number must be positive and greater than 0." + raise TypeError(msg) self.c_fieldinfo.contents.number = number layer = property( diff --git a/python/grass/script/core.py b/python/grass/script/core.py index e6de4331b43..c3491d2e5e4 100644 --- a/python/grass/script/core.py +++ b/python/grass/script/core.py @@ -270,7 +270,8 @@ def make_command( if flags: flags = _make_val(flags) if "-" in flags: - raise ScriptError("'-' is not a valid flag") + msg = "'-' is not a valid flag" + raise ScriptError(msg) args.append("-" + flags) for opt, val in options.items(): if opt in _popen_args: @@ -866,16 +867,16 @@ def _parse_opts(lines: list) -> tuple[dict[str, str], dict[str, bool]]: try: var, val = line.split(b"=", 1) except ValueError: - raise SyntaxError("invalid output from g.parser: {}".format(line)) + msg = "invalid output from g.parser: {}".format(line) + raise SyntaxError(msg) try: var = decode(var) val = decode(val) except UnicodeError as error: - raise SyntaxError( - "invalid output from g.parser ({error}): {line}".format( - error=error, line=line - ) + msg = "invalid output from g.parser ({error}): {line}".format( + error=error, line=line ) + raise SyntaxError(msg) if var.startswith("flag_"): flags[var[5:]] = bool(int(val)) elif var.startswith("opt_"): @@ -883,9 +884,8 @@ def _parse_opts(lines: list) -> tuple[dict[str, str], dict[str, bool]]: elif var in {"GRASS_OVERWRITE", "GRASS_VERBOSE"}: os.environ[var] = val else: - raise SyntaxError( - "unexpected output variable from g.parser: {}".format(line) - ) + msg = "unexpected output variable from g.parser: {}".format(line) + raise SyntaxError(msg) return (options, flags) diff --git a/python/grass/script/imagery.py b/python/grass/script/imagery.py index 2c2c3868423..c0531541409 100644 --- a/python/grass/script/imagery.py +++ b/python/grass/script/imagery.py @@ -93,10 +93,12 @@ def group_to_dict( ) if dict_keys not in {"indices", "map_names", "semantic_labels"}: - raise ValueError(f"Invalid dictionary keys <{dict_keys}> requested") + msg = f"Invalid dictionary keys <{dict_keys}> requested" + raise ValueError(msg) if dict_values not in {"indices", "map_names", "semantic_labels", "metadata"}: - raise ValueError(f"Invalid dictionary values <{dict_values}> requested") + msg = f"Invalid dictionary values <{dict_values}> requested" + raise ValueError(msg) if subgroup and not maps_in_group: warning( diff --git a/python/grass/script/setup.py b/python/grass/script/setup.py index cadf05bbe38..bb10c03cbfb 100644 --- a/python/grass/script/setup.py +++ b/python/grass/script/setup.py @@ -404,9 +404,8 @@ def __enter__(self): :returns: reference to the object (self) """ if not self.active: - raise ValueError( - "Attempt to use inactive (finished) session as a context manager" - ) + msg = "Attempt to use inactive (finished) session as a context manager" + raise ValueError(msg) return self def __exit__(self, type, value, traceback): @@ -423,7 +422,8 @@ def finish(self): and finish the session. No GRASS modules can be called afterwards. """ if not self.active: - raise ValueError("Attempt to finish an already finished session") + msg = "Attempt to finish an already finished session" + raise ValueError(msg) self._active = False finish(env=self._env, start_time=self._start_time) diff --git a/python/grass/script/utils.py b/python/grass/script/utils.py index 7cbcc28ae4a..a6f82c3d803 100644 --- a/python/grass/script/utils.py +++ b/python/grass/script/utils.py @@ -193,7 +193,8 @@ def decode(bytes_, encoding=None): 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") + msg = "can only accept types str and bytes" + raise TypeError(msg) def encode(string, encoding=None): @@ -221,7 +222,8 @@ def encode(string, encoding=None): 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") + msg = "can only accept types str and bytes" + raise TypeError(msg) def text_to_string(text, encoding=None): @@ -500,9 +502,11 @@ def legalize_vector_name(name, fallback_prefix="x"): """ # The implementation is based on Vect_legal_filename(). if not name: - raise ValueError("name cannot be empty") + msg = "name cannot be empty" + raise ValueError(msg) if fallback_prefix and re.match(r"[^A-Za-z]", fallback_prefix[0]): - raise ValueError("fallback_prefix must start with an ASCII letter") + msg = "fallback_prefix must start with an ASCII letter" + raise ValueError(msg) if fallback_prefix and re.match(r"[^A-Za-z]", name[0], flags=re.ASCII): # We prefix here rather than just replace, because in cases of unique # identifiers, e.g., columns or node names, replacing the first @@ -587,21 +591,22 @@ def append_random(name, suffix_length=None, total_length=None): :func:`append_node_pid()` description. """ if suffix_length and total_length: - raise ValueError( - "Either suffix_length or total_length can be provided, not both" - ) + msg = "Either suffix_length or total_length can be provided, not both" + raise ValueError(msg) if not suffix_length and not total_length: - raise ValueError("suffix_length or total_length has to be provided") + msg = "suffix_length or total_length has to be provided" + raise ValueError(msg) if total_length: # remove len of name and one underscore name_length = len(name) suffix_length = total_length - name_length - 1 if suffix_length <= 0: - raise ValueError( + msg = ( "No characters left for the suffix:" " total_length <{total_length}> is too small" " or name <{name}> ({name_length}) is too long".format(**locals()) ) + raise ValueError(msg) # We don't do lower and upper case because that could cause conflicts in # contexts which are case-insensitive. # We use lowercase because that's what is in UUID4 hex string. diff --git a/python/grass/semantic_label/reader.py b/python/grass/semantic_label/reader.py index 591006fe352..1a9e60bf0a0 100644 --- a/python/grass/semantic_label/reader.py +++ b/python/grass/semantic_label/reader.py @@ -26,7 +26,8 @@ def __init__(self): os.path.join(os.environ["GISBASE"], "etc", "i.band.library", "*.json") ) if not self._json_files: - raise SemanticLabelReaderError("No semantic label definitions found") + msg = "No semantic label definitions found" + raise SemanticLabelReaderError(msg) self._read_config() @@ -38,9 +39,8 @@ def _read_config(self): with open(json_file) as fd: config = json.load(fd, object_pairs_hook=OrderedDict) except json.decoder.JSONDecodeError as e: - raise SemanticLabelReaderError( - "Unable to parse '{}': {}".format(json_file, e) - ) + msg = "Unable to parse '{}': {}".format(json_file, e) + raise SemanticLabelReaderError(msg) # check if configuration is valid self._check_config(config) @@ -58,13 +58,11 @@ def _check_config(config): for items in config.values(): for item in ("shortcut", "bands"): if item not in items.keys(): - raise SemanticLabelReaderError( - "Invalid band definition: <{}> is missing".format(item) - ) + msg = "Invalid band definition: <{}> is missing".format(item) + raise SemanticLabelReaderError(msg) if len(items["bands"]) < 1: - raise SemanticLabelReaderError( - "Invalid band definition: no bands defined" - ) + msg = "Invalid band definition: no bands defined" + raise SemanticLabelReaderError(msg) @staticmethod def _print_label_extended(label, item): @@ -116,13 +114,13 @@ def print_info(self, shortcut=None, band=None, semantic_label=None, extended=Fal if shortcut and re.match(shortcut, item["shortcut"]) is None: continue except re.error as e: - raise SemanticLabelReaderError("Invalid pattern: {}".format(e)) + msg = "Invalid pattern: {}".format(e) + raise SemanticLabelReaderError(msg) found = True if band and band not in item["bands"]: - raise SemanticLabelReaderError( - "Band <{}> not found in <{}>".format(band, shortcut) - ) + msg = "Band <{}> not found in <{}>".format(band, shortcut) + raise SemanticLabelReaderError(msg) # print generic information if extended: diff --git a/python/grass/temporal/abstract_map_dataset.py b/python/grass/temporal/abstract_map_dataset.py index c91020d4941..3b9cf272f0c 100644 --- a/python/grass/temporal/abstract_map_dataset.py +++ b/python/grass/temporal/abstract_map_dataset.py @@ -84,7 +84,8 @@ def check_resolution_with_current_region(self): :return: "finer" or "coarser" """ - raise ImplementationError("This method must be implemented in the subclasses") + msg = "This method must be implemented in the subclasses" + raise ImplementationError(msg) @abstractmethod def has_grass_timestamp(self): diff --git a/python/grass/temporal/datetime_math.py b/python/grass/temporal/datetime_math.py index 40450151a4b..9104ab4b689 100644 --- a/python/grass/temporal/datetime_math.py +++ b/python/grass/temporal/datetime_math.py @@ -875,7 +875,8 @@ def datetime_to_grass_datetime_string(dt: datetime | None) -> str: ] if dt is None: - raise Exception("Empty datetime object in datetime_to_grass_datetime_string") + msg = "Empty datetime object in datetime_to_grass_datetime_string" + raise Exception(msg) # Check for time zone info in the datetime object if dt.tzinfo is not None: diff --git a/python/grass/temporal/list_stds.py b/python/grass/temporal/list_stds.py index ea01bfb5607..c8517545aeb 100644 --- a/python/grass/temporal/list_stds.py +++ b/python/grass/temporal/list_stds.py @@ -275,7 +275,8 @@ def _write_table(rows, column_names, output_format, separator, file): separator = "," _write_csv(rows=rows, column_names=column_names, separator=separator, file=file) else: - raise ValueError(f"Unknown value '{output_format}' for output_format") + msg = f"Unknown value '{output_format}' for output_format" + raise ValueError(msg) def _get_get_registered_maps_as_objects_with_method(dataset, where, method, gran, dbif): @@ -287,15 +288,15 @@ def _get_get_registered_maps_as_objects_with_method(dataset, where, method, gran ) if method == "gran": if where: - raise ValueError( - f"The where parameter is not supported with method={method}" - ) + msg = f"The where parameter is not supported with method={method}" + raise ValueError(msg) if gran is not None and gran != "": return dataset.get_registered_maps_as_objects_by_granularity( gran=gran, dbif=dbif ) return dataset.get_registered_maps_as_objects_by_granularity(dbif=dbif) - raise ValueError(f"Invalid method '{method}'") + msg = f"Invalid method '{method}'" + raise ValueError(msg) def _get_get_registered_maps_as_objects_delta_gran( @@ -363,7 +364,8 @@ def _get_list_of_maps_delta_gran(dataset, columns, where, method, gran, dbif, ms elif column == "distance_from_begin": row.append(delta_first) else: - raise ValueError(f"Unsupported column '{column}'") + msg = f"Unsupported column '{column}'" + raise ValueError(msg) rows.append(row) return rows @@ -386,14 +388,14 @@ def _get_list_of_maps_stds( def check_columns(column_names, output_format, element_type): if element_type != "stvds" and "layer" in columns: - raise ValueError( - f"Column 'layer' is not allowed with temporal type '{element_type}'" - ) + msg = f"Column 'layer' is not allowed with temporal type '{element_type}'" + raise ValueError(msg) if output_format == "line" and len(column_names) > 1: - raise ValueError( + msg = ( f"'{output_format}' output_format can have only 1 column, " f"not {len(column_names)}" ) + raise ValueError(msg) # This method expects a list of objects for gap detection if method in {"delta", "deltagaps", "gran"}: diff --git a/python/grass/temporal/temporal_algebra.py b/python/grass/temporal/temporal_algebra.py index 4a01af910cc..3ddb2cbe223 100644 --- a/python/grass/temporal/temporal_algebra.py +++ b/python/grass/temporal/temporal_algebra.py @@ -3398,7 +3398,8 @@ def p_error(self, t): "syntax error on line %d, position %i token %s near '%s' expression " "'%s'" % (t.lineno, t.lexpos, t.type, t.value, self.expression) ) - raise SyntaxError("Unexpected syntax error") + msg = "Unexpected syntax error" + raise SyntaxError(msg) if __name__ == "__main__": diff --git a/scripts/db.univar/db.univar.py b/scripts/db.univar/db.univar.py index 4654e3011a0..859e0fd831c 100755 --- a/scripts/db.univar/db.univar.py +++ b/scripts/db.univar/db.univar.py @@ -277,7 +277,8 @@ def main(): sys.stdout.write("coeff_var=0\n") sys.stdout.write("sum=%.15g\n" % sum) else: - raise ValueError(f"Unknown output format {output_format}") + msg = f"Unknown output format {output_format}" + raise ValueError(msg) if not extend: return diff --git a/scripts/g.extension/testsuite/test_addons_download.py b/scripts/g.extension/testsuite/test_addons_download.py index 07be93cf878..111e591f90d 100644 --- a/scripts/g.extension/testsuite/test_addons_download.py +++ b/scripts/g.extension/testsuite/test_addons_download.py @@ -51,10 +51,9 @@ def setUp(self): if self.install_prefix.exists(): files = [path.name for path in self.install_prefix.iterdir()] if files: - raise RuntimeError( - f"Install prefix path '{self.install_prefix}' \ + msg = f"Install prefix path '{self.install_prefix}' \ contains files {','.join(files)}" - ) + raise RuntimeError(msg) def tearDown(self): """Remove created files""" diff --git a/scripts/g.extension/testsuite/test_addons_modules.py b/scripts/g.extension/testsuite/test_addons_modules.py index 9b99e7ac2ae..956b092bce4 100644 --- a/scripts/g.extension/testsuite/test_addons_modules.py +++ b/scripts/g.extension/testsuite/test_addons_modules.py @@ -81,11 +81,10 @@ def setUp(self): if os.path.exists(self.install_prefix): files = os.listdir(self.install_prefix) if files: - raise RuntimeError( - "Install prefix path '{}' contains files {}".format( - self.install_prefix, files - ) + msg = "Install prefix path '{}' contains files {}".format( + self.install_prefix, files ) + raise RuntimeError(msg) def tearDown(self): """Remove created files""" diff --git a/scripts/v.dissolve/v.dissolve.py b/scripts/v.dissolve/v.dissolve.py index cb03ae3591e..33a9aadcee0 100755 --- a/scripts/v.dissolve/v.dissolve.py +++ b/scripts/v.dissolve/v.dissolve.py @@ -391,17 +391,16 @@ def aggregate_attributes_sql( ): """Aggregate values in selected columns grouped by column using SQL backend""" if methods and len(columns_to_aggregate) != len(result_columns): - raise ValueError( - "Number of columns_to_aggregate and result_columns must be the same" - ) + msg = "Number of columns_to_aggregate and result_columns must be the same" + raise ValueError(msg) if methods and len(columns_to_aggregate) != len(methods): - raise ValueError("Number of columns_to_aggregate and methods must be the same") + msg = "Number of columns_to_aggregate and methods must be the same" + raise ValueError(msg) if not methods: for result_column in result_columns: if " " not in result_column: - raise ValueError( - f"Column {result_column} from result_columns without type" - ) + msg = f"Column {result_column} from result_columns without type" + raise ValueError(msg) if methods: select_columns = [ f"{method}({agg_column})" @@ -470,10 +469,11 @@ def aggregate_attributes_univar( ): """Aggregate values in selected columns grouped by column using v.db.univar""" if len(columns_to_aggregate) != len(methods) != len(result_columns): - raise ValueError( + msg = ( "Number of columns_to_aggregate, methods, and result_columns " "must be the same" ) + raise ValueError(msg) records = json.loads( gs.read_command( "v.db.select", diff --git a/scripts/v.dissolve/v_dissolve.ipynb b/scripts/v.dissolve/v_dissolve.ipynb index 085b23828d8..9767c1260e2 100644 --- a/scripts/v.dissolve/v_dissolve.ipynb +++ b/scripts/v.dissolve/v_dissolve.ipynb @@ -278,12 +278,12 @@ " areas_by_zip = zip_records_by_town[town_name]\n", " # Check number ZIP codes.\n", " if len(areas_by_zip) != town_zip_codes:\n", - " raise RuntimeError(f'Incorrect number of zipcodes in town {row[\"NAME\"]}')\n", + " msg = f'Incorrect number of zipcodes in town {row[\"NAME\"]}'\n", + " raise RuntimeError(msg)\n", " # Check total area.\n", " if round(sum(areas_by_zip)) != round(town_area):\n", - " raise RuntimeError(\n", - " f'Incorrect area for {row[\"NAME\"]}: {sum(areas_by_zip)} != {town_area}'\n", - " )\n", + " msg = f'Incorrect area for {row[\"NAME\"]}: {sum(areas_by_zip)} != {town_area}'\n", + " raise RuntimeError(msg)\n", "print(\"No exceptions. Test passed.\")" ] } diff --git a/scripts/wxpyimgview/wxpyimgview_gui.py b/scripts/wxpyimgview/wxpyimgview_gui.py index b0f89deee80..b5338dc0db8 100644 --- a/scripts/wxpyimgview/wxpyimgview_gui.py +++ b/scripts/wxpyimgview/wxpyimgview_gui.py @@ -117,12 +117,14 @@ def read_bmp_header(self, header): magic, bmfh, bmih = struct.unpack("2s12s40s10x", header) if gs.decode(magic) != "BM": - raise SyntaxError("Invalid magic number") + msg = "Invalid magic number" + raise SyntaxError(msg) size, res1, res2, hsize = struct.unpack("