Skip to content

Commit

Permalink
New ruff rules (#2489)
Browse files Browse the repository at this point in the history
  • Loading branch information
giampaolo authored Dec 28, 2024
1 parent 107daa1 commit 623e6e0
Show file tree
Hide file tree
Showing 24 changed files with 162 additions and 208 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/issues.py
Original file line number Diff line number Diff line change
Expand Up @@ -159,7 +159,7 @@ def get_repo():

@functools.lru_cache()
def _get_event_data():
with open(open(os.environ["GITHUB_EVENT_PATH"])) as f:
with open(os.environ["GITHUB_EVENT_PATH"]) as f:
ret = json.load(f)
pp(ret)
return ret
Expand Down
50 changes: 25 additions & 25 deletions psutil/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,16 +51,16 @@
from ._common import CONN_SYN_RECV
from ._common import CONN_SYN_SENT
from ._common import CONN_TIME_WAIT
from ._common import FREEBSD # NOQA
from ._common import FREEBSD
from ._common import LINUX
from ._common import MACOS
from ._common import NETBSD # NOQA
from ._common import NETBSD
from ._common import NIC_DUPLEX_FULL
from ._common import NIC_DUPLEX_HALF
from ._common import NIC_DUPLEX_UNKNOWN
from ._common import OPENBSD # NOQA
from ._common import OPENBSD
from ._common import OSX # deprecated alias
from ._common import POSIX # NOQA
from ._common import POSIX
from ._common import POWER_TIME_UNKNOWN
from ._common import POWER_TIME_UNLIMITED
from ._common import STATUS_DEAD
Expand Down Expand Up @@ -93,24 +93,24 @@
PROCFS_PATH = "/proc"

from . import _pslinux as _psplatform
from ._pslinux import IOPRIO_CLASS_BE # NOQA
from ._pslinux import IOPRIO_CLASS_IDLE # NOQA
from ._pslinux import IOPRIO_CLASS_NONE # NOQA
from ._pslinux import IOPRIO_CLASS_RT # NOQA
from ._pslinux import IOPRIO_CLASS_BE # noqa: F401
from ._pslinux import IOPRIO_CLASS_IDLE # noqa: F401
from ._pslinux import IOPRIO_CLASS_NONE # noqa: F401
from ._pslinux import IOPRIO_CLASS_RT # noqa: F401

elif WINDOWS:
from . import _pswindows as _psplatform
from ._psutil_windows import ABOVE_NORMAL_PRIORITY_CLASS # NOQA
from ._psutil_windows import BELOW_NORMAL_PRIORITY_CLASS # NOQA
from ._psutil_windows import HIGH_PRIORITY_CLASS # NOQA
from ._psutil_windows import IDLE_PRIORITY_CLASS # NOQA
from ._psutil_windows import NORMAL_PRIORITY_CLASS # NOQA
from ._psutil_windows import REALTIME_PRIORITY_CLASS # NOQA
from ._pswindows import CONN_DELETE_TCB # NOQA
from ._pswindows import IOPRIO_HIGH # NOQA
from ._pswindows import IOPRIO_LOW # NOQA
from ._pswindows import IOPRIO_NORMAL # NOQA
from ._pswindows import IOPRIO_VERYLOW # NOQA
from ._psutil_windows import ABOVE_NORMAL_PRIORITY_CLASS # noqa: F401
from ._psutil_windows import BELOW_NORMAL_PRIORITY_CLASS # noqa: F401
from ._psutil_windows import HIGH_PRIORITY_CLASS # noqa: F401
from ._psutil_windows import IDLE_PRIORITY_CLASS # noqa: F401
from ._psutil_windows import NORMAL_PRIORITY_CLASS # noqa: F401
from ._psutil_windows import REALTIME_PRIORITY_CLASS # noqa: F401
from ._pswindows import CONN_DELETE_TCB # noqa: F401
from ._pswindows import IOPRIO_HIGH # noqa: F401
from ._pswindows import IOPRIO_LOW # noqa: F401
from ._pswindows import IOPRIO_NORMAL # noqa: F401
from ._pswindows import IOPRIO_VERYLOW # noqa: F401

elif MACOS:
from . import _psosx as _psplatform
Expand All @@ -120,8 +120,8 @@

elif SUNOS:
from . import _pssunos as _psplatform
from ._pssunos import CONN_BOUND # NOQA
from ._pssunos import CONN_IDLE # NOQA
from ._pssunos import CONN_BOUND # noqa: F401
from ._pssunos import CONN_IDLE # noqa: F401

# This is public writable API which is read from _pslinux.py and
# _pssunos.py via sys.modules.
Expand Down Expand Up @@ -1201,7 +1201,7 @@ def memory_maps(self, grouped=True):
except KeyError:
d[path] = nums
nt = _psplatform.pmmap_grouped
return [nt(path, *d[path]) for path in d] # NOQA
return [nt(path, *d[path]) for path in d]
else:
nt = _psplatform.pmmap_ext
return [nt(*x) for x in it]
Expand Down Expand Up @@ -1442,7 +1442,7 @@ def __getattribute__(self, name):
def wait(self, timeout=None):
if self.__subproc.returncode is not None:
return self.__subproc.returncode
ret = super().wait(timeout) # noqa
ret = super().wait(timeout)
self.__subproc.returncode = ret
return ret

Expand Down Expand Up @@ -1536,7 +1536,7 @@ def remove(pid):
_pmap = pmap


process_iter.cache_clear = lambda: _pmap.clear() # noqa
process_iter.cache_clear = lambda: _pmap.clear() # noqa: PLW0108
process_iter.cache_clear.__doc__ = "Clear process_iter() internal cache."


Expand Down Expand Up @@ -1619,7 +1619,7 @@ def check_gone(proc, timeout):
check_gone(proc, timeout)
else:
check_gone(proc, max_timeout)
alive = alive - gone # noqa PLR6104
alive = alive - gone # noqa: PLR6104

if alive:
# Last attempt over processes survived so far.
Expand Down
12 changes: 5 additions & 7 deletions psutil/_common.py
Original file line number Diff line number Diff line change
Expand Up @@ -269,9 +269,7 @@ def _infodict(self, attrs):
info = collections.OrderedDict()
for name in attrs:
value = getattr(self, name, None)
if value: # noqa
info[name] = value
elif name == "pid" and value == 0:
if value or (name == "pid" and value == 0):
info[name] = value
return info

Expand Down Expand Up @@ -876,9 +874,9 @@ def print_color(
): # pragma: no cover
"""Print a colorized version of string."""
if not term_supports_colors():
print(s, file=file) # NOQA
print(s, file=file)
elif POSIX:
print(hilite(s, color, bold), file=file) # NOQA
print(hilite(s, color, bold), file=file)
else:
import ctypes

Expand Down Expand Up @@ -906,7 +904,7 @@ def print_color(
handle = GetStdHandle(handle_id)
SetConsoleTextAttribute(handle, color)
try:
print(s, file=file) # NOQA
print(s, file=file)
finally:
SetConsoleTextAttribute(handle, DEFAULT_COLOR)

Expand All @@ -925,6 +923,6 @@ def debug(msg):
msg = f"ignoring {msg}"
else:
msg = f"ignoring {msg!r}"
print( # noqa
print( # noqa: T201
f"psutil-debug [{fname}:{lineno}]> {msg}", file=sys.stderr
)
8 changes: 4 additions & 4 deletions psutil/_psbsd.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
import os
from collections import defaultdict
from collections import namedtuple
from xml.etree import ElementTree # noqa ICN001
from xml.etree import ElementTree # noqa: ICN001

from . import _common
from . import _psposix
Expand Down Expand Up @@ -192,8 +192,8 @@ def virtual_memory():
# #2233), so zabbix seems to be wrong. Htop calculates it
# differently, and the used value seem more realistic, so let's
# match htop.
# https://github.com/htop-dev/htop/blob/e7f447b/netbsd/NetBSDProcessList.c#L162 # noqa
# https://github.com/zabbix/zabbix/blob/af5e0f8/src/libs/zbxsysinfo/netbsd/memory.c#L135 # noqa
# https://github.com/htop-dev/htop/blob/e7f447b/netbsd/NetBSDProcessList.c#L162
# https://github.com/zabbix/zabbix/blob/af5e0f8/src/libs/zbxsysinfo/netbsd/memory.c#L135
used = active + wired
avail = total - used
else:
Expand All @@ -202,7 +202,7 @@ def virtual_memory():
# * https://people.freebsd.org/~rse/dist/freebsd-memory
# * https://www.cyberciti.biz/files/scripts/freebsd-memory.pl.txt
# matches zabbix:
# * https://github.com/zabbix/zabbix/blob/af5e0f8/src/libs/zbxsysinfo/freebsd/memory.c#L143 # noqa
# * https://github.com/zabbix/zabbix/blob/af5e0f8/src/libs/zbxsysinfo/freebsd/memory.c#L143
avail = inactive + cached + free
used = active + wired + cached

Expand Down
6 changes: 3 additions & 3 deletions psutil/_pslinux.py
Original file line number Diff line number Diff line change
Expand Up @@ -934,7 +934,7 @@ def process_unix(file, family, inodes, filter_pid=None):
f"error while parsing {file}; malformed line {line!r}"
)
raise RuntimeError(msg) # noqa: B904
if inode in inodes: # noqa
if inode in inodes: # noqa: SIM108, SIM401
# With UNIX sockets we can have a single inode
# referencing many file descriptors.
pairs = inodes[inode]
Expand Down Expand Up @@ -1327,7 +1327,7 @@ def sensors_temperatures():
basenames2 = glob.glob(
'/sys/devices/platform/coretemp.*/hwmon/hwmon*/temp*_*'
)
repl = re.compile('/sys/devices/platform/coretemp.*/hwmon/')
repl = re.compile(r"/sys/devices/platform/coretemp.*/hwmon/")
for name in basenames2:
altname = repl.sub('/sys/class/hwmon/', name)
if altname not in basenames:
Expand Down Expand Up @@ -1480,7 +1480,7 @@ def multi_bcat(*paths):
# Get the first available battery. Usually this is "BAT0", except
# some rare exceptions:
# https://github.com/giampaolo/psutil/issues/1238
root = os.path.join(POWER_SUPPLY_PATH, sorted(bats)[0])
root = os.path.join(POWER_SUPPLY_PATH, min(bats))

# Base metrics.
energy_now = multi_bcat(root + "/energy_now", root + "/charge_now")
Expand Down
8 changes: 4 additions & 4 deletions psutil/_pswindows.py
Original file line number Diff line number Diff line change
Expand Up @@ -983,10 +983,10 @@ def open_files(self):
# Convert the first part in the corresponding drive letter
# (e.g. "C:\") by using Windows's QueryDosDevice()
raw_file_names = cext.proc_open_files(self.pid)
for _file in raw_file_names:
_file = convert_dos_path(_file)
if isfile_strict(_file):
ntuple = _common.popenfile(_file, -1)
for file in raw_file_names:
file = convert_dos_path(file)
if isfile_strict(file):
ntuple = _common.popenfile(file, -1)
ret.add(ntuple)
return list(ret)

Expand Down
16 changes: 8 additions & 8 deletions psutil/tests/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -707,14 +707,14 @@ def wrapper(*args, **kwargs):
for _ in self:
try:
return fun(*args, **kwargs)
except self.exception as _: # NOQA
except self.exception as _:
exc = _
if self.logfun is not None:
self.logfun(exc)
self.sleep()
continue

raise exc # noqa: PLE0704
raise exc

# This way the user of the decorated function can change config
# parameters.
Expand Down Expand Up @@ -890,7 +890,7 @@ class fake_pytest:
"""

@staticmethod
def main(*args, **kw): # noqa ARG004
def main(*args, **kw): # noqa: ARG004
"""Mimics pytest.main(). It has the same effect as running
`python3 -m unittest -v` from the project root directory.
"""
Expand Down Expand Up @@ -1228,7 +1228,7 @@ def _check_mem(self, fun, times, retries, tolerance):
return
else:
if idx == 1:
print() # NOQA
print() # noqa: T201
self._log(msg)
times += increase
prev_mem = mem
Expand Down Expand Up @@ -1365,17 +1365,17 @@ def print_sysinfo():
pinfo.pop('memory_maps', None)
info['proc'] = pprint.pformat(pinfo)

print("=" * 70, file=sys.stderr) # NOQA
print("=" * 70, file=sys.stderr) # noqa: T201
for k, v in info.items():
print("{:<17} {}".format(k + ":", v), file=sys.stderr) # noqa: T201
print("=" * 70, file=sys.stderr) # NOQA
print("=" * 70, file=sys.stderr) # noqa: T201
sys.stdout.flush()

# if WINDOWS:
# os.system("tasklist")
# elif shutil.which("ps"):
# os.system("ps aux")
# print("=" * 70, file=sys.stderr) # NOQA
# print("=" * 70, file=sys.stderr)

sys.stdout.flush()

Expand Down Expand Up @@ -1621,7 +1621,7 @@ def retry_on_failure(retries=NO_RETRIES):
"""

def logfun(exc):
print(f"{exc!r}, retrying", file=sys.stderr) # NOQA
print(f"{exc!r}, retrying", file=sys.stderr) # noqa: T201

return retry(
exception=AssertionError, timeout=None, retries=retries, logfun=logfun
Expand Down
22 changes: 11 additions & 11 deletions psutil/tests/test_connections.py
Original file line number Diff line number Diff line change
Expand Up @@ -184,15 +184,15 @@ def test_unix_tcp(self):
testfn = self.get_testfn()
with closing(bind_unix_socket(testfn, type=SOCK_STREAM)) as sock:
conn = self.check_socket(sock)
assert conn.raddr == "" # noqa
assert conn.raddr == ""
assert conn.status == psutil.CONN_NONE

@pytest.mark.skipif(not POSIX, reason="POSIX only")
def test_unix_udp(self):
testfn = self.get_testfn()
with closing(bind_unix_socket(testfn, type=SOCK_STREAM)) as sock:
conn = self.check_socket(sock)
assert conn.raddr == "" # noqa
assert conn.raddr == ""
assert conn.status == psutil.CONN_NONE


Expand Down Expand Up @@ -239,8 +239,8 @@ def test_unix(self):
assert len(cons) == 2
if LINUX or FREEBSD or SUNOS or OPENBSD:
# remote path is never set
assert cons[0].raddr == "" # noqa
assert cons[1].raddr == "" # noqa
assert cons[0].raddr == ""
assert cons[1].raddr == ""
# one local address should though
assert testfn == (cons[0].laddr or cons[1].laddr)
else:
Expand Down Expand Up @@ -356,14 +356,14 @@ def check_conn(proc, conn, family, type, laddr, raddr, status, kinds):
# launch various subprocess instantiating a socket of various
# families and types to enrich psutil results
tcp4_proc = self.pyrun(tcp4_template)
tcp4_addr = eval(wait_for_file(testfile, delete=True)) # noqa
tcp4_addr = eval(wait_for_file(testfile, delete=True))
udp4_proc = self.pyrun(udp4_template)
udp4_addr = eval(wait_for_file(testfile, delete=True)) # noqa
udp4_addr = eval(wait_for_file(testfile, delete=True))
if supports_ipv6():
tcp6_proc = self.pyrun(tcp6_template)
tcp6_addr = eval(wait_for_file(testfile, delete=True)) # noqa
tcp6_addr = eval(wait_for_file(testfile, delete=True))
udp6_proc = self.pyrun(udp6_template)
udp6_addr = eval(wait_for_file(testfile, delete=True)) # noqa
udp6_addr = eval(wait_for_file(testfile, delete=True))
else:
tcp6_proc = None
udp6_proc = None
Expand Down Expand Up @@ -560,7 +560,7 @@ def test_net_connection_constants(self):
ints.append(num)
strs.append(str_)
if SUNOS:
psutil.CONN_IDLE # noqa
psutil.CONN_BOUND # noqa
psutil.CONN_IDLE # noqa: B018
psutil.CONN_BOUND # noqa: B018
if WINDOWS:
psutil.CONN_DELETE_TCB # noqa
psutil.CONN_DELETE_TCB # noqa: B018
11 changes: 6 additions & 5 deletions psutil/tests/test_linux.py
Original file line number Diff line number Diff line change
Expand Up @@ -1763,9 +1763,10 @@ def open_mock(name, *args, **kwargs):
return orig_open(name, *args, **kwargs)

def glob_mock(path):
if path == '/sys/class/hwmon/hwmon*/temp*_*': # noqa
return []
elif path == '/sys/class/hwmon/hwmon*/device/temp*_*':
if path in {
'/sys/class/hwmon/hwmon*/temp*_*',
'/sys/class/hwmon/hwmon*/device/temp*_*',
}:
return []
elif path == '/sys/class/thermal/thermal_zone*':
return ['/sys/class/thermal/thermal_zone0']
Expand All @@ -1780,7 +1781,7 @@ def glob_mock(path):
with mock.patch("builtins.open", side_effect=open_mock):
with mock.patch('glob.glob', create=True, side_effect=glob_mock):
temp = psutil.sensors_temperatures()['name'][0]
assert temp.label == '' # noqa
assert temp.label == ''
assert temp.current == 30.0
assert temp.high == 50.0
assert temp.critical == 50.0
Expand Down Expand Up @@ -2055,7 +2056,7 @@ def test_exe_mocked(self):
):
ret = psutil.Process().exe()
assert m.called
assert ret == "" # noqa
assert ret == ""

def test_issue_1014(self):
# Emulates a case where smaps file does not exist. In this case
Expand Down
2 changes: 1 addition & 1 deletion psutil/tests/test_misc.py
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ def test_error__repr__(self):
assert repr(psutil.Error()) == "psutil.Error()"

def test_error__str__(self):
assert str(psutil.Error()) == "" # noqa
assert str(psutil.Error()) == ""

def test_no_such_process__repr__(self):
assert (
Expand Down
Loading

0 comments on commit 623e6e0

Please sign in to comment.