Skip to content

Commit

Permalink
Enforce ruff rule raw-string-in-exception rule (#2324)
Browse files Browse the repository at this point in the history
  • Loading branch information
giampaolo authored Oct 26, 2023
1 parent e9dabbb commit 902fada
Show file tree
Hide file tree
Showing 13 changed files with 55 additions and 27 deletions.
10 changes: 10 additions & 0 deletions HISTORY.rst
Original file line number Diff line number Diff line change
@@ -1,5 +1,15 @@
*Bug tracker at https://github.com/giampaolo/psutil/issues*

5.9.7 (IN DEVELOPMENT)
======================

XXXX-XX-XX

**Enhancements**

- 2324_: enforce Ruff rule `raw-string-in-exception`, which helps providing
clearer tracebacks when exceptions are raised by psutil.

5.9.6
=====

Expand Down
3 changes: 2 additions & 1 deletion docs/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,8 @@ def get_version():
assert num.isdigit(), ret
return ret
else:
raise ValueError("couldn't find version string")
msg = "couldn't find version string"
raise ValueError(msg)


VERSION = get_version()
Expand Down
16 changes: 10 additions & 6 deletions psutil/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -715,8 +715,8 @@ def username(self):
if POSIX:
if pwd is None:
# might happen if python was installed from sources
raise ImportError(
"requires pwd module shipped with standard python")
msg = "requires pwd module shipped with standard python"
raise ImportError(msg)
real_uid = self.uids().real
try:
return pwd.getpwuid(real_uid).pw_name
Expand Down Expand Up @@ -803,7 +803,8 @@ def ionice(self, ioclass=None, value=None):
"""
if ioclass is None:
if value is not None:
raise ValueError("'ioclass' argument must be specified")
msg = "'ioclass' argument must be specified"
raise ValueError(msg)
return self._proc.ionice_get()
else:
self._raise_if_pid_reused()
Expand Down Expand Up @@ -1198,10 +1199,12 @@ def _send_signal(self, sig):
self._raise_if_pid_reused()
if self.pid == 0:
# see "man 2 kill"
raise ValueError(
msg = (
"preventing sending signal to process with PID 0 as it "
"would affect every process in the process group of the "
"calling process (os.getpid()) instead of PID 0")
"calling process (os.getpid()) instead of PID 0"
)
raise ValueError(msg)
try:
os.kill(self.pid, sig)
except ProcessLookupError:
Expand Down Expand Up @@ -1288,7 +1291,8 @@ def wait(self, timeout=None):
To wait for multiple Process(es) use psutil.wait_procs().
"""
if timeout is not None and not timeout >= 0:
raise ValueError("timeout must be a positive integer")
msg = "timeout must be a positive integer"
raise ValueError(msg)
if self._exitcode is not _SENTINEL:
return self._exitcode
self._exitcode = self._proc.wait(timeout)
Expand Down
15 changes: 9 additions & 6 deletions psutil/_compat.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,15 +83,17 @@ def super(type_=_SENTINEL, type_or_obj=_SENTINEL, framedepth=1):
# Get the function's first positional argument.
type_or_obj = f.f_locals[f.f_code.co_varnames[0]]
except (IndexError, KeyError):
raise RuntimeError('super() used in a function with no args')
msg = 'super() used in a function with no args'
raise RuntimeError(msg)
try:
# Get the MRO so we can crawl it.
mro = type_or_obj.__mro__
except (AttributeError, RuntimeError):
try:
mro = type_or_obj.__class__.__mro__
except AttributeError:
raise RuntimeError('super() used in a non-newstyle class')
msg = 'super() used in a non-newstyle class'
raise RuntimeError(msg)
for type_ in mro:
# Find the class that owns the currently-executing method.
for meth in type_.__dict__.values():
Expand All @@ -118,7 +120,8 @@ def super(type_=_SENTINEL, type_or_obj=_SENTINEL, framedepth=1):
continue
break # found
else:
raise RuntimeError('super() called outside a method')
msg = 'super() called outside a method'
raise RuntimeError(msg)

# Dispatch to builtin super().
if type_or_obj is not _SENTINEL:
Expand Down Expand Up @@ -199,9 +202,9 @@ def FileExistsError(inst):
except FileExistsError:
pass
except OSError:
raise RuntimeError(
"broken or incompatible Python implementation, see: "
"https://github.com/giampaolo/psutil/issues/1659")
msg = ("broken or incompatible Python implementation, see: "
"https://github.com/giampaolo/psutil/issues/1659")
raise RuntimeError(msg)


# --- stdlib additions
Expand Down
3 changes: 2 additions & 1 deletion psutil/_psbsd.py
Original file line number Diff line number Diff line change
Expand Up @@ -253,7 +253,8 @@ def per_cpu_times():
if cpu_count_logical() == 1:
return [cpu_times()]
if per_cpu_times.__called__:
raise NotImplementedError("supported only starting from FreeBSD 8")
msg = "supported only starting from FreeBSD 8"
raise NotImplementedError(msg)
per_cpu_times.__called__ = True
return [cpu_times()]

Expand Down
10 changes: 6 additions & 4 deletions psutil/_pslinux.py
Original file line number Diff line number Diff line change
Expand Up @@ -745,8 +745,8 @@ def cpu_freq():
# https://github.com/giampaolo/psutil/issues/1071
curr = bcat(pjoin(path, "cpuinfo_cur_freq"), fallback=None)
if curr is None:
raise NotImplementedError(
"can't find current frequency file")
msg = "can't find current frequency file"
raise NotImplementedError(msg)
curr = int(curr) / 1000
max_ = int(bcat(pjoin(path, "scaling_max_freq"))) / 1000
min_ = int(bcat(pjoin(path, "scaling_min_freq"))) / 1000
Expand Down Expand Up @@ -2157,7 +2157,8 @@ def ionice_set(self, ioclass, value):
if value and ioclass in (IOPRIO_CLASS_IDLE, IOPRIO_CLASS_NONE):
raise ValueError("%r ioclass accepts no value" % ioclass)
if value < 0 or value > 7:
raise ValueError("value not in 0-7 range")
msg = "value not in 0-7 range"
raise ValueError(msg)
return cext.proc_ioprio_set(self.pid, ioclass, value)

if prlimit is not None:
Expand All @@ -2168,7 +2169,8 @@ def rlimit(self, resource_, limits=None):
# we don't want that. We should never get here though as
# PID 0 is not supported on Linux.
if self.pid == 0:
raise ValueError("can't use prlimit() against PID 0 process")
msg = "can't use prlimit() against PID 0 process"
raise ValueError(msg)
try:
if limits is None:
# get
Expand Down
4 changes: 3 additions & 1 deletion psutil/_psposix.py
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,9 @@ def wait_pid(pid, timeout=None, proc_name=None,
timeout=0 is also possible (either return immediately or raise).
"""
if pid <= 0:
raise ValueError("can't wait for PID 0") # see "man waitpid"
# see "man waitpid"
msg = "can't wait for PID 0"
raise ValueError(msg)
interval = 0.0001
flags = 0
if timeout is not None:
Expand Down
3 changes: 2 additions & 1 deletion psutil/_pssunos.py
Original file line number Diff line number Diff line change
Expand Up @@ -151,7 +151,8 @@ def swap_memory():

lines = stdout.strip().split('\n')[1:]
if not lines:
raise RuntimeError('no swap device(s) configured')
msg = 'no swap device(s) configured'
raise RuntimeError(msg)
total = free = 0
for line in lines:
line = line.split()
Expand Down
9 changes: 6 additions & 3 deletions psutil/_pswindows.py
Original file line number Diff line number Diff line change
Expand Up @@ -891,9 +891,11 @@ def send_signal(self, sig):
getattr(signal, "CTRL_BREAK_EVENT", object())):
os.kill(self.pid, sig)
else:
raise ValueError(
msg = (
"only SIGTERM, CTRL_C_EVENT and CTRL_BREAK_EVENT signals "
"are supported on Windows")
"are supported on Windows"
)
raise ValueError(msg)

@wrap_exceptions
def wait(self, timeout=None):
Expand Down Expand Up @@ -1045,7 +1047,8 @@ def ionice_get(self):
@wrap_exceptions
def ionice_set(self, ioclass, value):
if value:
raise TypeError("value argument not accepted on Windows")
msg = "value argument not accepted on Windows"
raise TypeError(msg)
if ioclass not in (IOPRIO_VERYLOW, IOPRIO_LOW, IOPRIO_NORMAL,
IOPRIO_HIGH):
raise ValueError("%s is not a valid priority" % ioclass)
Expand Down
2 changes: 1 addition & 1 deletion psutil/tests/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -1806,7 +1806,7 @@ def reload_module(module):

def import_module_by_path(path):
name = os.path.splitext(os.path.basename(path))[0]
if sys.version_info[0] == 2:
if sys.version_info[0] < 3:
import imp
return imp.load_source(name, path)
else:
Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,6 @@ ignore = [
"COM812", # Trailing comma missing
"D", # pydocstyle
"DTZ", # flake8-datetimez
"EM", # flake8-errmsg
"ERA001", # Found commented-out code
"FBT", # flake8-boolean-trap (makes zero sense)
"FIX", # Line contains TODO / XXX / ..., consider resolving the issue
Expand Down Expand Up @@ -71,6 +70,7 @@ ignore = [
[tool.ruff.per-file-ignores]
# T201 == print(), T203 == pprint()
".github/workflows/*" = ["T201", "T203"]
"psutil/tests/*" = ["EM101"] # raw-string-in-exception
"psutil/tests/runner.py" = ["T201", "T203"]
"scripts/*" = ["T201", "T203"]
"scripts/internal/*" = ["T201", "T203"]
Expand Down
2 changes: 1 addition & 1 deletion scripts/internal/winmake.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@
"wheel",
]

if sys.version_info[0] == 2:
if sys.version_info[0] < 3:
DEPS.append('mock')
DEPS.append('ipaddress')
DEPS.append('enum34')
Expand Down
3 changes: 2 additions & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,8 @@ def get_version():
for num in ret.split('.'):
assert num.isdigit(), ret
return ret
raise ValueError("couldn't find version string")
msg = "couldn't find version string"
raise ValueError(msg)


VERSION = get_version()
Expand Down

0 comments on commit 902fada

Please sign in to comment.