Skip to content
This repository has been archived by the owner on Jun 22, 2024. It is now read-only.

Commit

Permalink
more ruff rules
Browse files Browse the repository at this point in the history
  • Loading branch information
giampaolo committed Feb 8, 2024
1 parent 5f0a409 commit 61dfd67
Show file tree
Hide file tree
Showing 17 changed files with 46 additions and 25 deletions.
6 changes: 5 additions & 1 deletion docs/conf.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
# -*- coding: utf-8 -*-
#

# Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

# psutil documentation build configuration file, created by
# sphinx-quickstart on Wed Oct 19 21:54:30 2016.
#
Expand Down
3 changes: 1 addition & 2 deletions psutil/_pslinux.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,6 @@

# fmt: off
__extra__all__ = [
#
'PROCFS_PATH',
# io prio constants
"IOPRIO_CLASS_NONE", "IOPRIO_CLASS_RT", "IOPRIO_CLASS_BE",
Expand Down Expand Up @@ -1355,7 +1354,7 @@ def disk_partitions(all=False):
if device in ("/dev/root", "rootfs"):
device = RootFsDeviceFinder().find() or device
if not all:
if device == '' or fstype not in fstypes:
if not device or fstype not in fstypes:
continue
maxfile = maxpath = None # set later
ntuple = _common.sdiskpart(
Expand Down
3 changes: 1 addition & 2 deletions psutil/_pswindows.py
Original file line number Diff line number Diff line change
Expand Up @@ -239,7 +239,6 @@ def virtual_memory():
"""System virtual memory as a namedtuple."""
mem = cext.virtual_mem()
totphys, availphys, totsys, availsys = mem
#
total = totphys
avail = availphys
free = availphys
Expand Down Expand Up @@ -515,7 +514,7 @@ def win_service_get(name):
return service


class WindowsService:
class WindowsService: # noqa: PLW1641
"""Represents an installed Windows service."""

def __init__(self, name, display_name):
Expand Down
6 changes: 3 additions & 3 deletions psutil/tests/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -737,9 +737,9 @@ def wrapper(*args, **kwargs):
self.sleep()
continue
if PY3:
raise exc
raise exc # noqa: PLE0704
else:
raise
raise # noqa: PLE0704

# This way the user of the decorated function can change config
# parameters.
Expand Down Expand Up @@ -1944,7 +1944,7 @@ def is_namedtuple(x):
"""Check if object is an instance of namedtuple."""
t = type(x)
b = t.__bases__
if len(b) != 1 or b[0] != tuple:
if len(b) != 1 or b[0] is not tuple:
return False
f = getattr(t, '_fields', None)
if not isinstance(f, tuple):
Expand Down
3 changes: 0 additions & 3 deletions psutil/tests/test_linux.py
Original file line number Diff line number Diff line change
Expand Up @@ -1342,7 +1342,6 @@ def test_emulate_exclude_partitions(self):
ret = psutil.disk_io_counters(perdisk=False, nowrap=False)
self.assertIsNone(ret)

#
def is_storage_device(name):
return name == 'nvme0n1'

Expand Down Expand Up @@ -1936,15 +1935,13 @@ def get_test_file(fname):
break
raise RuntimeError("timeout looking for test file")

#
testfn = self.get_testfn()
with open(testfn, "w"):
self.assertEqual(get_test_file(testfn).mode, "w")
with open(testfn):
self.assertEqual(get_test_file(testfn).mode, "r")
with open(testfn, "a"):
self.assertEqual(get_test_file(testfn).mode, "a")
#
with open(testfn, "r+"):
self.assertEqual(get_test_file(testfn).mode, "r+")
with open(testfn, "w+"):
Expand Down
4 changes: 2 additions & 2 deletions psutil/tests/test_process.py
Original file line number Diff line number Diff line change
Expand Up @@ -965,7 +965,7 @@ def test_cpu_affinity(self):
self.assertEqual(
p.cpu_affinity(), list(os.sched_getaffinity(p.pid))
)
#

self.assertRaises(TypeError, p.cpu_affinity, 1)
p.cpu_affinity(initial)
# it should work with all iterables, not only lists
Expand Down Expand Up @@ -1344,7 +1344,7 @@ def assert_raises_nsp(fun, fun_name):

@unittest.skipIf(not POSIX, 'POSIX only')
def test_zombie_process(self):
parent, zombie = self.spawn_zombie()
_parent, zombie = self.spawn_zombie()
self.assertProcessZombie(zombie)

@unittest.skipIf(not POSIX, 'POSIX only')
Expand Down
2 changes: 1 addition & 1 deletion psutil/tests/test_system.py
Original file line number Diff line number Diff line change
Expand Up @@ -344,7 +344,7 @@ def test_cpu_count_logical(self):
self.assertIsNotNone(logical)
self.assertEqual(logical, len(psutil.cpu_times(percpu=True)))
self.assertGreaterEqual(logical, 1)
#

if os.path.exists("/proc/cpuinfo"):
with open("/proc/cpuinfo") as fd:
cpuinfo_data = fd.read()
Expand Down
21 changes: 20 additions & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,13 @@
target-version = ["py37"]
line-length = 79
skip-string-normalization = true
# https://black.readthedocs.io/en/stable/the_black_code_style/future_style.html
preview = true
enable-unstable-feature = ["multiline_string_handling", "string_processing", "wrap_long_dict_values_in_parens"]

[tool.ruff]
# https://beta.ruff.rs/docs/settings/
preview = true
target-version = "py37"
line-length = 79

Expand Down Expand Up @@ -38,23 +41,39 @@ ignore = [
"D", # pydocstyle
"DTZ", # flake8-datetimez
"ERA001", # Found commented-out code
"F841", # Local variable `parent` is assigned to but never used
"FBT", # flake8-boolean-trap (makes zero sense)
"FIX", # Line contains TODO / XXX / ..., consider resolving the issue
"FLY", # flynt (PYTHON2.7 COMPAT)
"FURB101", # `open` and `read` should be replaced by `Path(src).read_text()`
"FURB113", # Use `x.extend(('a', 'b', 'c'))` instead of repeatedly calling `x.append()`
"FURB118", # [*] Use `operator.add` instead of defining a lambda
"FURB140", # [*] Use `itertools.starmap` instead of the generator
"FURB145", # [*] Prefer `copy` method over slicing (PYTHON2.7 COMPAT)
"INP", # flake8-no-pep420
"N801", # Class name `async_chat` should use CapWords convention (ASYNCORE COMPAT)
"N802", # Function name X should be lowercase.
"N806", # Variable X in function should be lowercase.
"N818", # Exception name `FooBar` should be named with an Error suffix
"PERF", # Perflint
"PGH004", # Use specific rule codes when using `noqa`
"PLC0415", # `import` should be at the top-level of a file
"PLC2701", # Private name import `x` from external module `y`
"PLR0904", # Too many public methods (x > y)
"PLR0911", # Too many return statements (8 > 6)
"PLR0912", # Too many branches (x > y)
"PLR0913", # Too many arguments in function definition (x > y)
"PLR0915", # Too many statements (92 > 50)
"PLR0914", # Too many local variables (x/y)
"PLR0915", # Too many statements (x > y)
"PLR0917", # Too many positional arguments (x/y)
"PLR1702", # Too many nested blocks (x > y)
"PLR1704", # Redefining argument with the local name `type_`
"PLR2004", # Magic value used in comparison, consider replacing X with a constant variable
"PLR5501", # Use `elif` instead of `else` then `if`, to reduce indentation
"PLR6201", # Use a `set` literal when testing for membership
"PLR6301", # Method `x` could be a function, class method, or static method
"PLW0603", # Using the global statement to update `lineno` is discouraged
"PLW1514", # `open` in text mode without explicit `encoding` argument
"PLW2901", # `for` loop variable `x` overwritten by assignment target
"PT", # flake8-pytest-style
"PTH", # flake8-use-pathlib
Expand Down
3 changes: 2 additions & 1 deletion scripts/disk_usage.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
/dev/sda6 345.9G 83.8G 244.5G 24% ext4 /home
/dev/sda1 296.0M 43.1M 252.9M 14% vfat /boot/efi
/dev/sda2 600.0M 312.4M 287.6M 52% fuseblk /media/Recovery
"""

import os
Expand All @@ -26,7 +27,7 @@ def main():
print(templ % ("Device", "Total", "Used", "Free", "Use ", "Type", "Mount"))
for part in psutil.disk_partitions(all=False):
if os.name == 'nt':
if 'cdrom' in part.opts or part.fstype == '':
if 'cdrom' in part.opts or not part.fstype:
# skip cd-rom drives with no disk in it; they may raise
# ENOENT, pop-up a Windows GUI error for a non-ready
# partition or just hang.
Expand Down
2 changes: 1 addition & 1 deletion scripts/ifconfig.py
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ def main():
print(" netmask : %s" % addr.netmask)
if addr.ptp:
print(" p2p : %s" % addr.ptp)
print("")
print()


if __name__ == '__main__':
Expand Down
2 changes: 1 addition & 1 deletion scripts/internal/download_wheels_appveyor.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ def get_file_urls():
print_color("no artifacts found", 'red')
sys.exit(1)
else:
for url in sorted(urls, key=lambda x: os.path.basename(x)):
for url in sorted(urls, key=os.path.basename):
yield url


Expand Down
1 change: 1 addition & 0 deletions scripts/internal/print_announce.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@

"""Prints release announce based on HISTORY.rst file content.
See: https://pip.pypa.io/en/stable/reference/pip_install/#hash-checking-mode.
"""

import os
Expand Down
2 changes: 1 addition & 1 deletion scripts/internal/print_api_speed.py
Original file line number Diff line number Diff line change
Expand Up @@ -181,7 +181,7 @@ def main():
print_timings()

# --- process
print("")
print()
print_header("PROCESS APIS")
ignore = [
'send_signal',
Expand Down
2 changes: 1 addition & 1 deletion scripts/internal/print_downloads.py
Original file line number Diff line number Diff line change
Expand Up @@ -141,7 +141,7 @@ def main():
downs = downloads()

print("# Download stats")
print("")
print()
s = "psutil download statistics of the last %s days (last update " % DAYS
s += "*%s*).\n" % LAST_UPDATE
s += "Generated via [pypistats.py](%s) script.\n" % GITHUB_SCRIPT_URL
Expand Down
4 changes: 2 additions & 2 deletions scripts/internal/winmake.py
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,7 @@ def safe_rmtree(path):
def onerror(fun, path, excinfo):
exc = excinfo[1]
if exc.errno != errno.ENOENT:
raise
raise # noqa: PLE0704

existed = os.path.isdir(path)
shutil.rmtree(path, onerror=onerror)
Expand Down Expand Up @@ -181,7 +181,7 @@ def safe_rmtree(path):
def onerror(fun, path, excinfo):
exc = excinfo[1]
if exc.errno != errno.ENOENT:
raise
raise # noqa: PLE0704

existed = os.path.isdir(path)
shutil.rmtree(path, onerror=onerror)
Expand Down
5 changes: 3 additions & 2 deletions scripts/procsmem.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
20513 giampao /opt/sublime_text/sublime_text 65.8M 73.0M 0B 87.9M
3976 giampao compiz 115.0M 117.0M 0B 130.9M
32486 giampao skype 145.1M 147.5M 0B 149.6M
"""

from __future__ import print_function
Expand Down Expand Up @@ -89,8 +90,8 @@ def main():
p.pid,
p._info["username"][:7] if p._info["username"] else "",
convert_bytes(p._uss),
convert_bytes(p._pss) if p._pss != "" else "",
convert_bytes(p._swap) if p._swap != "" else "",
convert_bytes(p._pss) if p._pss else "",
convert_bytes(p._swap) if p._swap else "",
convert_bytes(p._rss),
cmd,
)
Expand Down
2 changes: 1 addition & 1 deletion scripts/winservices.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ def main():
)
print(s)
print("binpath: %s" % info['binpath'])
print("")
print()


if __name__ == '__main__':
Expand Down

0 comments on commit 61dfd67

Please sign in to comment.