Skip to content

Commit

Permalink
style: Enable flake8-errmsg rules and fix errors (#4845)
Browse files Browse the repository at this point in the history
* style: Fix raw-string-in-exception (EM101)

Exception must not use a string literal, assign to variable first

Produces a clearer stack trace, without duplicating the text of the error message

Ruff rule: https://docs.astral.sh/ruff/rules/raw-string-in-exception/

* style: Fix f-string-in-exception (EM102)
Exception must not use an f-string literal, assign to variable first

Produces a clearer stack trace, without duplicating the text of the error message

Ruff rule: https://docs.astral.sh/ruff/rules/f-string-in-exception/

* style: Fix dot-format-in-exception (EM103)
Exception must not use a `.format()` string directly, assign to variable first

Produces a clearer stack trace, without duplicating the text of the error message

Ruff rule: https://docs.astral.sh/ruff/rules/dot-format-in-exception/

* checks(ruff): Enable checking for EM101, EM102 and EM103 rules

* Fix doctest typo according to current error message
  • Loading branch information
echoix authored Dec 20, 2024
1 parent 2326a4f commit fd945ae
Show file tree
Hide file tree
Showing 66 changed files with 423 additions and 271 deletions.
5 changes: 2 additions & 3 deletions gui/wxpython/animation/data.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
3 changes: 2 additions & 1 deletion gui/wxpython/core/globalvar.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
16 changes: 8 additions & 8 deletions gui/wxpython/core/layerlist.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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

Expand All @@ -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)
Expand Down
3 changes: 2 additions & 1 deletion gui/wxpython/core/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down
6 changes: 4 additions & 2 deletions gui/wxpython/gmodeler/model.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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)

Expand Down
18 changes: 12 additions & 6 deletions gui/wxpython/gui_core/mapdisp.py
Original file line number Diff line number Diff line change
Expand Up @@ -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."""
Expand Down Expand Up @@ -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
Expand All @@ -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)"""
Expand Down
12 changes: 8 additions & 4 deletions gui/wxpython/iscatt/plots.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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
Expand All @@ -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
Expand Down
5 changes: 3 additions & 2 deletions gui/wxpython/lmgr/frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
5 changes: 3 additions & 2 deletions gui/wxpython/main_window/frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
3 changes: 2 additions & 1 deletion lib/gis/testsuite/test_gis_lib_getl.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
11 changes: 6 additions & 5 deletions lib/init/grass.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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():
Expand Down
1 change: 1 addition & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
6 changes: 4 additions & 2 deletions python/grass/app/runtime.py
Original file line number Diff line number Diff line change
Expand Up @@ -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}"
Expand Down
3 changes: 2 additions & 1 deletion python/grass/benchmark/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
5 changes: 2 additions & 3 deletions python/grass/benchmark/plots.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
6 changes: 4 additions & 2 deletions python/grass/experimental/create.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
16 changes: 8 additions & 8 deletions python/grass/experimental/mapset.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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
Expand Down Expand Up @@ -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)
Expand All @@ -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
Expand Down
6 changes: 4 additions & 2 deletions python/grass/grassdb/history.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down Expand Up @@ -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):
Expand Down
Loading

0 comments on commit fd945ae

Please sign in to comment.