Skip to content

Commit

Permalink
style: Fixes literal-membership (PLR6201) for other code (OSGeo#3954)
Browse files Browse the repository at this point in the history
Concerns Pylint rule "use-set-for-membership / R6201"

Using `ruff check --output-format=concise --select PLR6201 --preview --unsafe-fixes --fix`, but reverting some changes where it wasn't clear if it was safe.
  • Loading branch information
echoix authored Jul 1, 2024
1 parent 614e1e7 commit ffa270b
Show file tree
Hide file tree
Showing 43 changed files with 87 additions and 87 deletions.
2 changes: 1 addition & 1 deletion display/d.mon/render_cmd.py
Original file line number Diff line number Diff line change
Expand Up @@ -173,7 +173,7 @@ def read_stdin(cmd):
width, height, legfile = read_env_file(os.path.join(path, "env"))
if mon.startswith("wx"):
mapfile = tempfile.NamedTemporaryFile(dir=path).name
if cmd[0] in ("d.barscale", "d.legend", "d.northarrow", "d.legend.vect"):
if cmd[0] in {"d.barscale", "d.legend", "d.northarrow", "d.legend.vect"}:
mapfile += ".png"
else:
mapfile += ".ppm"
Expand Down
20 changes: 10 additions & 10 deletions lib/init/grass.py
Original file line number Diff line number Diff line change
Expand Up @@ -624,7 +624,7 @@ def read_gui(gisrc, default_gui):
grass_gui = default_gui

# FIXME oldtcltk, gis.m, d.m no longer exist (remove this around 7.2)
if grass_gui in ["d.m", "gis.m", "oldtcltk", "tcltk"]:
if grass_gui in {"d.m", "gis.m", "oldtcltk", "tcltk"}:
warning(_("GUI <%s> not supported in this version") % grass_gui)
grass_gui = default_gui

Expand All @@ -648,7 +648,7 @@ def check_gui(expected_gui):
# Check if we are running X windows by checking the DISPLAY variable
if os.getenv("DISPLAY") or WINDOWS or MACOS:
# Check if python is working properly
if expected_gui in ("wxpython", "gtext"):
if expected_gui in {"wxpython", "gtext"}:
nul = open(os.devnull, "w")
p = Popen(
[os.environ["GRASS_PYTHON"]],
Expand Down Expand Up @@ -1476,13 +1476,13 @@ def get_shell():

def get_grass_env_file(sh, grass_config_dir):
"""Get name of the shell-specific GRASS environment (rc) file"""
if sh in ["csh", "tcsh"]:
if sh in {"csh", "tcsh"}:
grass_env_file = os.path.join(grass_config_dir, "cshrc")
elif sh in ["bash", "msh", "cygwin", "sh"]:
elif sh in {"bash", "msh", "cygwin", "sh"}:
grass_env_file = os.path.join(grass_config_dir, "bashrc")
elif sh == "zsh":
grass_env_file = os.path.join(grass_config_dir, "zshrc")
elif sh in ["cmd", "powershell"]:
elif sh in {"cmd", "powershell"}:
grass_env_file = os.path.join(grass_config_dir, "env.bat")
else:
grass_env_file = os.path.join(grass_config_dir, "bashrc")
Expand Down Expand Up @@ -1959,7 +1959,7 @@ def print_params(params):
for arg in params:
if arg == "path":
sys.stdout.write("%s\n" % GISBASE)
elif arg in ["python_path", "python-path"]:
elif arg in {"python_path", "python-path"}:
sys.stdout.write("%s\n" % gpath("etc", "python"))
elif arg == "arch":
val = grep("ARCH", linesplat)
Expand Down Expand Up @@ -2272,7 +2272,7 @@ def main():

# A shell is activated when using TTY.
# Explicit --[g]text in command line, forces a shell to be activated.
force_shell = grass_gui in ["text", "gtext"]
force_shell = grass_gui in {"text", "gtext"}
use_shell = io_is_interactive() or force_shell
if not use_shell:
# If no shell is used, always use actual GUI as GUI, even when "text" is set as
Expand Down Expand Up @@ -2518,16 +2518,16 @@ def main():
_("Launching <%s> GUI in the background, please wait...")
% grass_gui
)
if sh in ["csh", "tcsh"]:
if sh in {"csh", "tcsh"}:
shell_process = csh_startup(mapset_settings.full_mapset, grass_env_file)
elif sh in ["zsh"]:
elif sh in {"zsh"}:
shell_process = sh_like_startup(
mapset_settings.full_mapset,
mapset_settings.location,
grass_env_file,
"zsh",
)
elif sh in ["bash", "msh", "cygwin"]:
elif sh in {"bash", "msh", "cygwin"}:
shell_process = sh_like_startup(
mapset_settings.full_mapset,
mapset_settings.location,
Expand Down
2 changes: 1 addition & 1 deletion man/build_class_graphical.py
Original file line number Diff line number Diff line change
Expand Up @@ -145,7 +145,7 @@ def generate_page_for_category(
)
output.write(header_graphical_index_tmpl)

if module_family.lower() not in ["general", "postscript"]:
if module_family.lower() not in {"general", "postscript"}:
if module_family == "raster3d":
# covert keyword to nice form
module_family = "3D raster"
Expand Down
2 changes: 1 addition & 1 deletion man/build_class_rest.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
f = open(filename + ".tmp", "wb")

write_rest_header(f, "GRASS GIS %s Reference Manual: %s" % (grass_version, modclass))
if modclass.lower() not in ["general", "miscellaneous", "postscript"]:
if modclass.lower() not in {"general", "miscellaneous", "postscript"}:
f.write(
modclass_intro_tmpl.substitute(
modclass=modclass, modclass_lower=modclass.lower()
Expand Down
4 changes: 2 additions & 2 deletions man/build_html.py
Original file line number Diff line number Diff line change
Expand Up @@ -436,9 +436,9 @@ def html_files(cls=None, ignore_gui=True):
for cmd in sorted(os.listdir(html_dir)):
if (
cmd.endswith(".html")
and (cls in [None, "*"] or cmd.startswith(cls + "."))
and (cls in {None, "*"} or cmd.startswith(cls + "."))
and (cls != "*" or len(cmd.split(".")) >= 3)
and cmd not in ["full_index.html", "index.html"]
and cmd not in {"full_index.html", "index.html"}
and cmd not in exclude_mods
and (ignore_gui and not cmd.startswith("wxGUI.") or not ignore_gui)
):
Expand Down
4 changes: 2 additions & 2 deletions man/build_rest.py
Original file line number Diff line number Diff line change
Expand Up @@ -314,9 +314,9 @@ def rest_files(cls=None):
for cmd in sorted(os.listdir(rest_dir)):
if (
cmd.endswith(".txt")
and (cls in [None, "*"] or cmd.startswith(cls + "."))
and (cls in {None, "*"} or cmd.startswith(cls + "."))
and (cls != "*" or len(cmd.split(".")) >= 3)
and cmd not in ["full_index.txt", "index.txt"]
and cmd not in {"full_index.txt", "index.txt"}
and cmd not in exclude_mods
and not cmd.startswith("wxGUI.")
):
Expand Down
2 changes: 1 addition & 1 deletion man/parser_standard_options.py
Original file line number Diff line number Diff line change
Expand Up @@ -222,7 +222,7 @@ def _repr_html_(self):

options = OptTable(parse_options(cfile.readlines(), startswith=args.startswith))
outform = args.format
if outform in ["csv", "html"]:
if outform in {"csv", "html"}:
print(getattr(options, outform)(), file=args.output)
args.output.close()
else:
Expand Down
4 changes: 2 additions & 2 deletions python/grass/benchmark/plots.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ def nprocs_plot(results, filename=None, title=None, metric="time"):
plt.plot(x, result.times, label=result.label)
plt.fill_between(x, mins, maxes, color="gray", alpha=0.3)
ylabel = "Time [s]"
elif metric in ["speedup", "efficiency"]:
elif metric in {"speedup", "efficiency"}:
ylabel = metric.title()
plt.plot(x, getattr(result, metric), label=result.label)
else:
Expand All @@ -96,7 +96,7 @@ def nprocs_plot(results, filename=None, title=None, metric="time"):
plt.title(title)
elif metric == "times":
plt.title("Execution time by processing elements")
elif metric in ["speedup", "efficiency"]:
elif metric in {"speedup", "efficiency"}:
plt.title(f"{metric.title()} by processing elements")
if filename:
plt.savefig(filename)
Expand Down
2 changes: 1 addition & 1 deletion python/grass/jupyter/map3d.py
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,7 @@ def cleanup(tmpdir):
"because pyvirtualdisplay cannot be imported"
).format(screen_backend)
)
elif screen_backend in ["simple", "pyvirtualdisplay"]:
elif screen_backend in {"simple", "pyvirtualdisplay"}:
self._screen_backend = screen_backend
else:
raise ValueError(
Expand Down
4 changes: 2 additions & 2 deletions python/grass/pygrass/modules/grid/grid.py
Original file line number Diff line number Diff line change
Expand Up @@ -479,7 +479,7 @@ def __init__(
# if overlap > 0, r.patch won't work properly
if not patch_backend:
self.patch_backend = "RasterRow"
elif patch_backend not in ("r.patch", "RasterRow"):
elif patch_backend not in {"r.patch", "RasterRow"}:
raise RuntimeError(
_("Parameter patch_backend must be 'r.patch' or 'RasterRow'")
)
Expand Down Expand Up @@ -625,7 +625,7 @@ def define_mapset_inputs(self):
"""Add the mapset information to the input maps"""
for inmap in self.module.inputs:
inm = self.module.inputs[inmap]
if inm.type in ("raster", "vector") and inm.value:
if inm.type in {"raster", "vector"} and inm.value:
if "@" not in inm.value:
mset = get_mapset_raster(inm.value)
inm.value = inm.value + "@%s" % mset
Expand Down
2 changes: 1 addition & 1 deletion python/grass/pygrass/modules/interface/flag.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ def __init__(self, xflag=None, diz=None):
diz = read.element2dict(xflag) if xflag is not None else diz
self.name = diz["name"]
self.special = (
True if self.name in ("verbose", "overwrite", "quiet", "run") else False
True if self.name in {"verbose", "overwrite", "quiet", "run"} else False
)
self.description = diz.get("description", None)
self.default = diz.get("default", None)
Expand Down
2 changes: 1 addition & 1 deletion python/grass/pygrass/modules/interface/module.py
Original file line number Diff line number Diff line change
Expand Up @@ -563,7 +563,7 @@ def __init__(self, cmd, *args, **kargs):
tree = fromstring(self.xml)

for e in tree:
if e.tag not in ("parameter", "flag"):
if e.tag not in {"parameter", "flag"}:
self.__setattr__(e.tag, GETFROMTAG[e.tag](e))

#
Expand Down
2 changes: 1 addition & 1 deletion python/grass/pygrass/raster/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -313,7 +313,7 @@ def _get_mode(self):
return self._mode

def _set_mode(self, mode):
if mode and mode.lower() not in ("r", "w", "rw"):
if mode and mode.lower() not in {"r", "w", "rw"}:
str_err = _("Mode type: {0} not supported ('r', 'w','rw')")
raise ValueError(str_err.format(mode))
self._mode = mode
Expand Down
6 changes: 3 additions & 3 deletions python/grass/pygrass/raster/abstract.py
Original file line number Diff line number Diff line change
Expand Up @@ -323,7 +323,7 @@ def _get_mtype(self):

def _set_mtype(self, mtype):
"""Private method to change the Raster type"""
if mtype.upper() not in ("CELL", "FCELL", "DCELL"):
if mtype.upper() not in {"CELL", "FCELL", "DCELL"}:
str_err = "Raster type: {0} not supported ('CELL','FCELL','DCELL')"
raise ValueError(_(str_err).format(mtype))
self._mtype = mtype
Expand All @@ -335,7 +335,7 @@ def _get_mode(self):
return self._mode

def _set_mode(self, mode):
if mode.upper() not in ("R", "W"):
if mode.upper() not in {"R", "W"}:
str_err = _("Mode type: {0} not supported ('r', 'w')")
raise ValueError(str_err.format(mode))
self._mode = mode
Expand All @@ -346,7 +346,7 @@ def _get_overwrite(self):
return self._overwrite

def _set_overwrite(self, overwrite):
if overwrite not in (True, False):
if overwrite not in {True, False}:
str_err = _("Overwrite type: {0} not supported (True/False)")
raise ValueError(str_err.format(overwrite))
self._overwrite = overwrite
Expand Down
2 changes: 1 addition & 1 deletion python/grass/pygrass/raster/category.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ def _get_mtype(self):
return self._mtype

def _set_mtype(self, mtype):
if mtype.upper() not in ("CELL", "FCELL", "DCELL"):
if mtype.upper() not in {"CELL", "FCELL", "DCELL"}:
raise ValueError(_("Raster type: {0} not supported".format(mtype)))
self._mtype = mtype
self._gtype = RTYPE[self.mtype]["grass type"]
Expand Down
6 changes: 3 additions & 3 deletions python/grass/pygrass/vector/abstract.py
Original file line number Diff line number Diff line change
Expand Up @@ -368,11 +368,11 @@ def open(
# 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"):
if self.mode not in {"r", "rw", "w"}:
raise ValueError("Mode not supported. Use one of: 'r', 'rw', 'w'.")

# check if the map exist
if self.exist() and self.mode in ("r", "rw"):
if self.exist() and self.mode in {"r", "rw"}:
# open in READ mode
if self.mode == "r":
openvect = libvect.Vect_open_old2(
Expand All @@ -392,7 +392,7 @@ def open(
openvect = libvect.Vect_open_new(self.c_mapinfo, self.name, with_z)
self.dblinks = DBlinks(self.c_mapinfo)

if self.mode in ("w", "rw") and tab_cols:
if self.mode in {"w", "rw"} and tab_cols:
# create a link
link = Link(
layer,
Expand Down
8 changes: 4 additions & 4 deletions python/grass/script/array.py
Original file line number Diff line number Diff line change
Expand Up @@ -155,7 +155,7 @@ def __new__(cls, mapname=None, null=None, dtype=numpy.double, env=None):
else:
raise ValueError(_("Invalid kind <%s>") % kind)

if size not in [1, 2, 4, 8]:
if size not in {1, 2, 4, 8}:
raise ValueError(_("Invalid size <%d>") % size)

gcore.run_command(
Expand Down Expand Up @@ -202,7 +202,7 @@ def write(self, mapname, title=None, null=None, overwrite=None, quiet=None):
raise ValueError(_("Invalid FP size <%d>") % size)
size = None
elif kind in "biu":
if size not in [1, 2, 4]:
if size not in {1, 2, 4}:
raise ValueError(_("Invalid integer size <%d>") % size)
flags = None
else:
Expand Down Expand Up @@ -267,7 +267,7 @@ def __new__(cls, mapname=None, null=None, dtype=numpy.double, env=None):
else:
raise ValueError(_("Invalid kind <%s>") % kind)

if size not in [1, 2, 4, 8]:
if size not in {1, 2, 4, 8}:
raise ValueError(_("Invalid size <%d>") % size)

gcore.run_command(
Expand Down Expand Up @@ -310,7 +310,7 @@ def write(self, mapname, null=None, overwrite=None, quiet=None):
if size != 4 and size != 8:
raise ValueError(_("Invalid FP size <%d>") % size)
elif kind in "biu":
if size not in [1, 2, 4, 8]:
if size not in {1, 2, 4, 8}:
raise ValueError(_("Invalid integer size <%d>") % size)
flags = "i"
else:
Expand Down
8 changes: 4 additions & 4 deletions python/grass/script/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -884,7 +884,7 @@ def _parse_opts(lines):
flags[var[5:]] = bool(int(val))
elif var.startswith("opt_"):
options[var[4:]] = val
elif var in ["GRASS_OVERWRITE", "GRASS_VERBOSE"]:
elif var in {"GRASS_OVERWRITE", "GRASS_VERBOSE"}:
os.environ[var] = val
else:
raise SyntaxError(
Expand Down Expand Up @@ -1288,13 +1288,13 @@ def region_env(region3d=False, flags=None, env=None, **kwargs):
grass_region = ""
for line in fd.readlines():
key, value = map(lambda x: x.strip(), line.split(":", 1))
if kwargs and key not in ("proj", "zone"):
if kwargs and key not in {"proj", "zone"}:
continue
if (
not kwargs
and not region3d
and key
in (
in {
"top",
"bottom",
"cols3",
Expand All @@ -1303,7 +1303,7 @@ def region_env(region3d=False, flags=None, env=None, **kwargs):
"e-w resol3",
"n-s resol3",
"t-b resol",
)
}
):
continue

Expand Down
6 changes: 3 additions & 3 deletions python/grass/script/db.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ def db_describe(table, env=None, **args):
if key.startswith("Column "):
n = int(key.split(" ")[1])
cols.insert(n, f[1:])
elif key in ["ncols", "nrows"]:
elif key in {"ncols", "nrows"}:
result[key] = int(f[1])
else:
result[key] = f[1:]
Expand Down Expand Up @@ -238,7 +238,7 @@ def db_begin_transaction(driver):
:return: SQL command as string
"""
if driver in ("sqlite", "pg"):
if driver in {"sqlite", "pg"}:
return "BEGIN"
if driver == "mysql":
return "START TRANSACTION"
Expand All @@ -250,6 +250,6 @@ def db_commit_transaction(driver):
:return: SQL command as string
"""
if driver in ("sqlite", "pg", "mysql"):
if driver in {"sqlite", "pg", "mysql"}:
return "COMMIT"
return ""
6 changes: 3 additions & 3 deletions python/grass/script/task.py
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ def get_name(self):
"""Get task name"""
if sys.platform == "win32":
name, ext = os.path.splitext(self.name)
if ext in (".py", ".sh"):
if ext in {".py", ".sh"}:
return name
else:
return self.name
Expand Down Expand Up @@ -641,7 +641,7 @@ def cmdtuple_to_list(cmd):
cmdList.append("--" + flag)

for k, v in cmd[1].items():
if k in ("flags", "help", "verbose", "quiet", "overwrite"):
if k in {"flags", "help", "verbose", "quiet", "overwrite"}:
continue
if " " in v:
v = '"%s"' % v
Expand All @@ -667,7 +667,7 @@ def cmdlist_to_tuple(cmd):
dcmd[str(key)] = value.replace('"', "")
elif item[:2] == "--": # long flags
flag = item[2:]
if flag in ("help", "verbose", "quiet", "overwrite"):
if flag in {"help", "verbose", "quiet", "overwrite"}:
dcmd[str(flag)] = True
elif len(item) == 2 and item[0] == "-": # -> flags
if "flags" not in dcmd:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ def main():
remaining = None
nesting = 0
map_name = None
elif len(sys.argv) not in [3, 4]:
elif len(sys.argv) not in {3, 4}:
gs.fatal(
"Usage: <script name> <size[,size,...]> <nesting level> [<map name>]\n"
" <script name> The name of this file ({name})\n"
Expand Down
Loading

0 comments on commit ffa270b

Please sign in to comment.