Skip to content

Commit

Permalink
style: Fix if-else-block-instead-of-if-exp (SIM108) (part 2) (#4562)
Browse files Browse the repository at this point in the history
* 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
  • Loading branch information
echoix authored Oct 21, 2024
1 parent 9d699d5 commit 67a1609
Show file tree
Hide file tree
Showing 64 changed files with 124 additions and 445 deletions.
10 changes: 2 additions & 8 deletions python/grass/app/runtime.py
Original file line number Diff line number Diff line change
Expand Up @@ -79,10 +79,7 @@ def append_left_addon_paths(paths, config_dir, env):
# addons (base)
addon_base = env.get("GRASS_ADDON_BASE")
if not addon_base:
if MACOS:
name = "Addons"
else:
name = "addons"
name = "addons" if not MACOS else "Addons"
addon_base = os.path.join(config_dir, name)
env["GRASS_ADDON_BASE"] = addon_base

Expand Down Expand Up @@ -174,10 +171,7 @@ def set_python_path_variable(install_path, env):
"""Set PYTHONPATH to find GRASS Python package in subprocesses"""
path = env.get("PYTHONPATH")
etcpy = os.path.join(install_path, "etc", "python")
if path:
path = etcpy + os.pathsep + path
else:
path = etcpy
path = etcpy + os.pathsep + path if path else etcpy
env["PYTHONPATH"] = path


Expand Down
6 changes: 1 addition & 5 deletions python/grass/benchmark/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,11 +47,7 @@ def join_results_cli(args):
def select_only(result):
return result.label == args.only

if args.only:
select_function = select_only
else:
select_function = None

select_function = select_only if args.only else None
results = join_results_from_files(
source_filenames=args.results,
prefixes=args.prefixes,
Expand Down
10 changes: 2 additions & 8 deletions python/grass/benchmark/plots.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,10 +25,7 @@ def get_pyplot(to_file):
"""
import matplotlib as mpl # pylint: disable=import-outside-toplevel

if to_file:
backend = "agg"
else:
backend = None
backend = "agg" if to_file else None
if backend:
mpl.use(backend)

Expand Down Expand Up @@ -124,10 +121,7 @@ def num_cells_plot(results, filename=None, title=None, show_resolution=False):

x_ticks = set()
for result in results:
if show_resolution:
x = result.resolutions
else:
x = result.cells
x = result.resolutions if show_resolution else result.cells
x_ticks.update(x)
plt.plot(x, result.times, label=result.label)
if hasattr(result, "all_times"):
Expand Down
10 changes: 3 additions & 7 deletions python/grass/exceptions/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,13 +71,9 @@ def __init__(self, module, code, returncode, errors=None):
"""
# CalledProcessError has undocumented constructor
super().__init__(returncode, module)
if not module or module in code:
# No need to include module name if it is directly in code
# of if it is not set.
executed = code
else:
# Make sure module name is there if provided and not in code.
executed = f"{module} {code}"
# No need to include module name if it is directly in code of if it is not set.
# Otherwise, make sure module name is there if provided and not in code.
executed = code if not module or module in code else f"{module} {code}"
if errors:
# We assume actual errors, e.g., captured stderr.
err = _("See the following errors:\n{errors}").format(errors=errors)
Expand Down
14 changes: 4 additions & 10 deletions python/grass/gunittest/case.py
Original file line number Diff line number Diff line change
Expand Up @@ -691,10 +691,7 @@ def assertFileMd5(self, filename, md5, text=False, msg=None):
at the end of file (as for example, Git or PEP8 requires).
"""
self.assertFileExists(filename, msg=msg)
if text:
actual = text_file_md5(filename)
else:
actual = file_md5(filename)
actual = text_file_md5(filename) if text else file_md5(filename)
if actual != md5:
standardMsg = (
"File <{name}> does not have the right MD5 sum.\n"
Expand Down Expand Up @@ -1339,12 +1336,9 @@ def runModule(cls, module, expecting_stdout=False, **kwargs):
errors = " The errors are:\n" + module.outputs.stderr
else:
errors = " There were no error messages."
if module.outputs.stdout:
# this is not appropriate for translation but we don't want
# and don't need testing to be translated
got = "only whitespace."
else:
got = "nothing."
# This is not appropriate for translation but we don't want
# and don't need testing to be translated
got = "only whitespace." if module.outputs.stdout else "nothing."
raise RuntimeError(
"Module call "
+ module.get_python()
Expand Down
5 changes: 1 addition & 4 deletions python/grass/gunittest/invoker.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,10 +54,7 @@ def update_keyval_file(filename, module, returncode):
keyval["name"] = module.name
keyval["tested_dir"] = module.tested_dir
if "status" not in keyval.keys():
if returncode is None or returncode:
status = "failed"
else:
status = "passed"
status = "failed" if returncode is None or returncode else "passed"
keyval["status"] = status
keyval["returncode"] = returncode
keyval["test_file_authors"] = test_file_authors
Expand Down
5 changes: 1 addition & 4 deletions python/grass/gunittest/multireport.py
Original file line number Diff line number Diff line change
Expand Up @@ -119,10 +119,7 @@ def median(values):

smedian = median(successes)
smax = max(successes)
if successes[-1] < smedian:
color = "r"
else:
color = "g"
color = "r" if successes[-1] < smedian else "g"
# another possibility is to color according to the gradient, ideally
# on the whole curve but that's much more complicated

Expand Down
22 changes: 5 additions & 17 deletions python/grass/gunittest/reporters.py
Original file line number Diff line number Diff line change
Expand Up @@ -234,11 +234,8 @@ def get_svn_path_authors(path, from_date=None):
:returns: a set of authors
"""
if from_date is None:
# this is the SVN default for local copies
revision_range = "BASE:1"
else:
revision_range = "BASE:{%s}" % from_date
# "BASE:1" is the SVN default for local copies
revision_range = "BASE:1" if from_date is None else "BASE:{%s}" % from_date
try:
# TODO: allow also usage of --limit
p = subprocess.Popen(
Expand Down Expand Up @@ -487,10 +484,7 @@ def tail(filename, n):

def returncode_to_html_text(returncode, timed_out=None):
if returncode:
if timed_out is not None:
extra = f" (timeout >{timed_out}s)"
else:
extra = ""
extra = f" (timeout >{timed_out}s)" if timed_out is not None else ""
return f'<span style="color: red">FAILED{extra}</span>'
# alternatives: SUCCEEDED, passed, OK
return '<span style="color: green">succeeded</span>'
Expand Down Expand Up @@ -857,10 +851,7 @@ def finish(self):

# this shoul be moved to some additional meta passed in constructor
svn_info = get_svn_info()
if not svn_info:
svn_revision = ""
else:
svn_revision = svn_info["revision"]
svn_revision = "" if not svn_info else svn_info["revision"]

summary = {}
summary["files_total"] = self.test_files
Expand Down Expand Up @@ -1025,10 +1016,7 @@ def end_file_test(
num_failed = test_summary.get("failures", 0)
num_failed += test_summary.get("errors", 0)
if num_failed:
if num_failed > 1:
text = " ({f} tests failed)"
else:
text = " ({f} test failed)"
text = " ({f} tests failed)" if num_failed > 1 else " ({f} test failed)"
self._stream.write(text.format(f=num_failed))
self._stream.write("\n")
# TODO: here we lost the possibility to include also file name
Expand Down
5 changes: 1 addition & 4 deletions python/grass/jupyter/map3d.py
Original file line number Diff line number Diff line change
Expand Up @@ -210,10 +210,7 @@ def render(self, **kwargs):
with Display(
size=(self._width, self._height), **additional_kwargs
) as display:
if has_env_copy:
env = display.env()
else:
env = os.environ.copy()
env = display.env() if has_env_copy else os.environ.copy()
self._region_manager.set_region_from_command(env=env, **kwargs)
self.overlay.region_manager.set_region_from_env(env)
gs.run_command(module, env=env, **kwargs)
Expand Down
7 changes: 2 additions & 5 deletions python/grass/pydispatch/signal.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
from grass.pydispatch import dispatcher


def _islambda(function):
def _islambda(function) -> bool:
"""
Tests if object is a lambda function.
Expand Down Expand Up @@ -146,10 +146,7 @@ class connects to the signal::
will print
"""
if weak is None:
if _islambda(handler):
weak = False
else:
weak = True
weak = not _islambda(handler)
dispatcher.connect(receiver=handler, signal=self, weak=weak)

def disconnect(self, handler, weak=True):
Expand Down
5 changes: 1 addition & 4 deletions python/grass/pygrass/modules/interface/parameter.py
Original file line number Diff line number Diff line change
Expand Up @@ -337,10 +337,7 @@ def __doc__(self):
..
"""
if hasattr(self, "values"):
if self.isrange:
vals = self.isrange
else:
vals = ", ".join([repr(val) for val in self.values])
vals = self.isrange or ", ".join([repr(val) for val in self.values])
else:
vals = False
if self.keydescvalues:
Expand Down
5 changes: 1 addition & 4 deletions python/grass/pygrass/vector/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -859,10 +859,7 @@ def features_to_wkb_list(self, bbox=None, feature_type="point", field=1):
ok = libvect.Vect_cat_get(
ctypes.byref(line_c), field, ctypes.byref(cat)
)
if ok < 1:
pcat = None
else:
pcat = cat.value
pcat = None if ok < 1 else cat.value

wkb_list.append((f_id, pcat, ctypes.string_at(barray, size.value)))
libgis.G_free(barray)
Expand Down
5 changes: 1 addition & 4 deletions python/grass/pygrass/vector/geometry.py
Original file line number Diff line number Diff line change
Expand Up @@ -810,10 +810,7 @@ def extend(self, line, forward=True):
"""
# set direction
if forward:
direction = libvect.GV_FORWARD
else:
direction = libvect.GV_BACKWARD
direction = libvect.GV_FORWARD if forward else libvect.GV_BACKWARD
# check if is a Line object
if isinstance(line, Line):
c_points = line.c_points
Expand Down
5 changes: 1 addition & 4 deletions python/grass/pygrass/vector/table.py
Original file line number Diff line number Diff line change
Expand Up @@ -1261,10 +1261,7 @@ def create(self, cols, name=None, overwrite=False, cursor=None):
"""
cur = cursor or self.conn.cursor()
coldef = ",\n".join(["%s %s" % col for col in cols])
if name:
newname = name
else:
newname = self.name
newname = name or self.name
try:
cur.execute(sql.CREATE_TAB.format(tname=newname, coldef=coldef))
self.conn.commit()
Expand Down
15 changes: 3 additions & 12 deletions python/grass/script/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -334,10 +334,7 @@ def get_module_and_code(args, kwargs):
args = make_command(*args, **kwargs)
# Since we are in error handler, let's be extra cautious
# about an empty command.
if args:
module = args[0]
else:
module = None
module = args[0] if args else None
code = " ".join(args)
return module, code

Expand Down Expand Up @@ -1699,10 +1696,7 @@ def mapsets(search_path=False, env=None):
:return: list of mapsets
"""
if search_path:
flags = "p"
else:
flags = "l"
flags = "p" if search_path else "l"
mapsets = read_command("g.mapsets", flags=flags, sep="newline", quiet=True, env=env)
if not mapsets:
fatal(_("Unable to list mapsets"))
Expand Down Expand Up @@ -2033,10 +2027,7 @@ def create_environment(gisdbase, location, mapset, env=None):
f.write("GISDBASE: {g}\n".format(g=gisdbase))
f.write("LOCATION_NAME: {l}\n".format(l=location))
f.write("GUI: text\n")
if env:
env = env.copy()
else:
env = os.environ.copy()
env = env.copy() if env else os.environ.copy()
env["GISRC"] = f.name
# remove mapset-specific env vars
env = sanitize_mapset_environment(env)
Expand Down
5 changes: 1 addition & 4 deletions python/grass/script/raster.py
Original file line number Diff line number Diff line change
Expand Up @@ -218,10 +218,7 @@ def raster_what(map, coord, env=None, localized=False):
query
:param env:
"""
if isinstance(map, (bytes, str)):
map_list = [map]
else:
map_list = map
map_list = [map] if isinstance(map, (bytes, str)) else map

coord_list = []
if isinstance(coord, tuple):
Expand Down
10 changes: 2 additions & 8 deletions python/grass/script/task.py
Original file line number Diff line number Diff line change
Expand Up @@ -345,14 +345,8 @@ def _process_params(self):
for ki in node_key_desc.findall("item"):
key_desc.append(ki.text)

if p.get("multiple", "no") == "yes":
multiple = True
else:
multiple = False
if p.get("required", "no") == "yes":
required = True
else:
required = False
multiple = p.get("multiple", "no") == "yes"
required = p.get("required", "no") == "yes"

if (
self.task.blackList["enabled"]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -65,15 +65,9 @@ def main():
argument = sys.argv[1]
sizes = argument.split(",", 1)
size = sizes[0]
if len(sizes) > 1:
remaining = sizes[1]
else:
remaining = None
remaining = sizes[1] if len(sizes) > 1 else None
nesting = int(sys.argv[2])
if len(sys.argv) == 4:
map_name = sys.argv[3]
else:
map_name = None
map_name = sys.argv[3] if len(sys.argv) == 4 else None
call_use_temp_region(
script=this_file,
size=size,
Expand Down
20 changes: 4 additions & 16 deletions python/grass/script/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -190,10 +190,7 @@ def decode(bytes_, encoding=None):
if isinstance(bytes_, str):
return bytes_
if isinstance(bytes_, bytes):
if encoding is None:
enc = _get_encoding()
else:
enc = encoding
enc = _get_encoding() if encoding is None else encoding
return bytes_.decode(enc)
# only text should be used
raise TypeError("can only accept types str and bytes")
Expand Down Expand Up @@ -221,10 +218,7 @@ def encode(string, encoding=None):
if isinstance(string, bytes):
return string
if isinstance(string, str):
if encoding is None:
enc = _get_encoding()
else:
enc = encoding
enc = _get_encoding() if encoding is None else encoding
return string.encode(enc)
# if something else than text
raise TypeError("can only accept types str and bytes")
Expand Down Expand Up @@ -276,10 +270,7 @@ def parse_key_val(s, sep="=", dflt=None, val_type=None, vsep=None):
for line in lines:
kv = line.split(sep, 1)
k = decode(kv[0].strip())
if len(kv) > 1:
v = decode(kv[1].strip())
else:
v = dflt
v = decode(kv[1].strip()) if len(kv) > 1 else dflt

if val_type:
result[k] = val_type(v)
Expand Down Expand Up @@ -353,10 +344,7 @@ def convert(text):
return int(text) if text.isdigit() else text.lower()

def alphanum_key(actual_key):
if key:
sort_key = key(actual_key)
else:
sort_key = actual_key
sort_key = key(actual_key) if key else actual_key
return [convert(c) for c in re.split("([0-9]+)", sort_key)]

items.sort(key=alphanum_key)
Expand Down
Loading

0 comments on commit 67a1609

Please sign in to comment.