Skip to content

Commit

Permalink
more f-strings
Browse files Browse the repository at this point in the history
  • Loading branch information
giampaolo committed Dec 20, 2024
1 parent 9d1e8dc commit b6693b9
Show file tree
Hide file tree
Showing 13 changed files with 55 additions and 53 deletions.
4 changes: 2 additions & 2 deletions psutil/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -420,7 +420,7 @@ def __str__(self):
return "%s.%s(%s)" % (
self.__class__.__module__,
self.__class__.__name__,
", ".join(["%s=%r" % (k, v) for k, v in info.items()]),
", ".join([f"{k}={v!r}" for k, v in info.items()]),
)

__repr__ = __str__
Expand Down Expand Up @@ -1176,7 +1176,7 @@ def memory_percent(self, memtype="rss"):
# we should never get here
msg = (
"can't calculate process memory percent because total physical"
" system memory is not positive (%r)" % (total_phymem)
f" system memory is not positive ({total_phymem!r})"
)
raise ValueError(msg)
return (value / float(total_phymem)) * 100
Expand Down
5 changes: 2 additions & 3 deletions psutil/_common.py
Original file line number Diff line number Diff line change
Expand Up @@ -863,9 +863,8 @@ def hilite(s, color=None, bold=False): # pragma: no cover
try:
color = colors[color]
except KeyError:
raise ValueError(
"invalid color %r; choose between %s" % (list(colors.keys()))
)
msg = f"invalid color {color!r}; choose amongst {list(colors.keys())}"
raise ValueError(msg)
attr.append(color)
if bold:
attr.append('1')
Expand Down
7 changes: 4 additions & 3 deletions psutil/_psbsd.py
Original file line number Diff line number Diff line change
Expand Up @@ -964,9 +964,10 @@ def rlimit(self, resource, limits=None):
return cext.proc_getrlimit(self.pid, resource)
else:
if len(limits) != 2:
raise ValueError(
"second argument must be a (soft, hard) tuple, got %s"
% repr(limits)
msg = (
"second argument must be a (soft, hard) tuple, got"
f" {limits!r}"
)
raise ValueError(msg)
soft, hard = limits
return cext.proc_setrlimit(self.pid, resource, soft, hard)
30 changes: 16 additions & 14 deletions psutil/_pslinux.py
Original file line number Diff line number Diff line change
Expand Up @@ -324,9 +324,8 @@ def calculate_avail_vmem(mems):
slab_reclaimable = mems[b'SReclaimable:']
except KeyError as err:
debug(
"%s is missing from /proc/meminfo; using an approximation for "
"calculating available memory"
% err.args[0]
f"{err.args[0]} is missing from /proc/meminfo; using an"
" approximation for calculating available memory"
)
return fallback
try:
Expand Down Expand Up @@ -1149,11 +1148,11 @@ def read_sysfs():
elif os.path.exists('/sys/block'):
gen = read_sysfs()
else:
raise NotImplementedError(
"%s/diskstats nor /sys/block filesystem are available on this "
"system"
% get_procfs_path()
msg = (
f"{get_procfs_path()}/diskstats nor /sys/block are available on"
" this system"
)
raise NotImplementedError(msg)

retdict = {}
for entry in gen:
Expand Down Expand Up @@ -1856,10 +1855,11 @@ def io_counters(self):
fields[b'wchar'], # write chars
)
except KeyError as err:
raise ValueError(
"%r field was not found in %s; found fields are %r"
% (err.args[0], fname, fields)
msg = (
f"{err.args[0]!r} field was not found in {fname}; found"
f" fields are {fields!r}"
)
raise ValueError(msg)

@wrap_exceptions
def cpu_times(self):
Expand Down Expand Up @@ -2068,11 +2068,13 @@ def num_ctx_switches(
data = self._read_status_file()
ctxsw = _ctxsw_re.findall(data)
if not ctxsw:
raise NotImplementedError(
"'voluntary_ctxt_switches' and 'nonvoluntary_ctxt_switches'"
"lines were not found in %s/%s/status; the kernel is "
"probably older than 2.6.23" % (self._procfs_path, self.pid)
msg = (
"'voluntary_ctxt_switches' and"
" 'nonvoluntary_ctxt_switches'lines were not found in"
f" {self._procfs_path}/{self.pid}/status; the kernel is"
" probably older than 2.6.23"
)
raise NotImplementedError(msg)
else:
return _common.pctxsw(int(ctxsw[0]), int(ctxsw[1]))

Expand Down
27 changes: 14 additions & 13 deletions psutil/tests/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -289,7 +289,7 @@ def __init__(self):

def __repr__(self):
name = self.__class__.__name__
return '<%s running=%s at %#x>' % (name, self._running, id(self))
return f"<{name} running={self._running} at {id(self):#x}>"

def __enter__(self):
self.start()
Expand Down Expand Up @@ -391,16 +391,16 @@ def spawn_children_pair():
tfile = None
testfn = get_testfn(dir=os.getcwd())
try:
s = textwrap.dedent("""\
s = textwrap.dedent(f"""\
import subprocess, os, sys, time
s = "import os, time;"
s += "f = open('%s', 'w');"
s += "f = open('{os.path.basename(testfn)}', 'w');"
s += "f.write(str(os.getpid()));"
s += "f.close();"
s += "[time.sleep(0.1) for x in range(100 * 6)];"
p = subprocess.Popen([r'%s', '-c', s])
p = subprocess.Popen([r'{PYTHON_EXE}', '-c', s])
p.wait()
""" % (os.path.basename(testfn), PYTHON_EXE))
""")
# On Windows if we create a subprocess with CREATE_NO_WINDOW flag
# set (which is the default) a "conhost.exe" extra process will be
# spawned as a child. We don't want that.
Expand Down Expand Up @@ -1179,10 +1179,11 @@ def _check_fds(self, fun):
after = self._get_num_fds()
diff = after - before
if diff < 0:
raise self.fail(
"negative diff %r (gc probably collected a "
"resource from a previous test)" % diff
msg = (
f"negative diff {diff!r} (gc probably collected a"
" resource from a previous test)"
)
raise self.fail(msg)
if diff > 0:
type_ = "fd" if POSIX else "handle"
if diff > 1:
Expand Down Expand Up @@ -1526,9 +1527,9 @@ def test_class_coverage(cls, test_class, ls):
for fun_name, _, _ in ls:
meth_name = 'test_' + fun_name
if not hasattr(test_class, meth_name):
msg = "%r class should define a '%s' method" % (
test_class.__class__.__name__,
meth_name,
msg = (
f"{test_class.__class__.__name__!r} class should define a"
f" {meth_name!r} method"
)
raise AttributeError(msg)

Expand Down Expand Up @@ -1657,8 +1658,8 @@ def wrapper(*args, **kwargs):
if not only_if:
raise
msg = (
"%r was skipped because it raised NotImplementedError"
% fun.__name__
f"{fun.__name__!r} was skipped because it raised"
" NotImplementedError"
)
raise pytest.skip(msg)

Expand Down
4 changes: 2 additions & 2 deletions psutil/tests/test_aix.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ def test_virtual_memory(self):
"available",
"mmode",
]:
re_pattern += r"(?P<%s>\S+)\s+" % (field,)
re_pattern += rf"(?P<{field}>\S+)\s+"
matchobj = re.search(re_pattern, out)

assert matchobj is not None
Expand Down Expand Up @@ -104,7 +104,7 @@ def test_cpu_stats(self):
"S5rd",
"sysc",
]:
re_pattern += r"(?P<%s>\S+)\s+" % (field,)
re_pattern += rf"(?P<{field}>\S+)\s+"
matchobj = re.search(re_pattern, out)

assert matchobj is not None
Expand Down
6 changes: 3 additions & 3 deletions psutil/tests/test_connections.py
Original file line number Diff line number Diff line change
Expand Up @@ -522,14 +522,14 @@ def test_multi_sockets_procs(self):
for _ in range(times):
fname = self.get_testfn()
fnames.append(fname)
src = textwrap.dedent("""\
src = textwrap.dedent(f"""\
import time, os
from psutil.tests import create_sockets
with create_sockets():
with open(r'%s', 'w') as f:
with open(r'{fname}', 'w') as f:
f.write("hello")
[time.sleep(0.1) for x in range(100)]
""" % fname)
""")
sproc = self.pyrun(src)
pids.append(sproc.pid)

Expand Down
6 changes: 2 additions & 4 deletions psutil/tests/test_linux.py
Original file line number Diff line number Diff line change
Expand Up @@ -146,7 +146,7 @@ def free_swap():
nt = collections.namedtuple('free', 'total used free')
return nt(int(total), int(used), int(free))
raise ValueError(
"can't find 'Swap' in 'free' output:\n%s" % '\n'.join(lines)
f"can't find 'Swap' in 'free' output:\n{'\n'.join(lines)}"
)


Expand All @@ -167,9 +167,7 @@ def free_physmem():
'free', 'total used free shared output'
)
return nt(total, used, free, shared, out)
raise ValueError(
"can't find 'Mem' in 'free' output:\n%s" % '\n'.join(lines)
)
raise ValueError(f"can't find 'Mem' in 'free' output:\n{'\n'.join(lines)}")


def vmstat(stat):
Expand Down
4 changes: 2 additions & 2 deletions psutil/tests/test_misc.py
Original file line number Diff line number Diff line change
Expand Up @@ -941,8 +941,8 @@ def test_coverage(self):
if 'test_' + os.path.splitext(name)[0] not in meths:
# self.assert_stdout(name)
raise self.fail(
'no test defined for %r script'
% os.path.join(SCRIPTS_DIR, name)
"no test defined for"
f" {os.path.join(SCRIPTS_DIR, name)!r} script"
)

@pytest.mark.skipif(not POSIX, reason="POSIX only")
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 @@ -1072,8 +1072,8 @@ def test_open_files(self):

# another process
cmdline = (
"import time; f = open(r'%s', 'r'); [time.sleep(0.1) for x in"
" range(100)];" % testfn
f"import time; f = open(r'{testfn}', 'r'); [time.sleep(0.1) for x"
" in range(100)];"
)
p = self.spawn_psproc([PYTHON_EXE, "-c", cmdline])

Expand Down
5 changes: 3 additions & 2 deletions scripts/internal/bench_oneshot.py
Original file line number Diff line number Diff line change
Expand Up @@ -126,8 +126,9 @@ def call_oneshot(funs):

def main():
print(
"%s methods involved on platform %r (%s iterations, psutil %s):"
% (len(names), sys.platform, ITERATIONS, psutil.__version__)
f"{len(names)} methods involved on platform"
f" {sys.platform!r} ({ITERATIONS} iterations, psutil"
f" {psutil.__version__}):"
)
for name in sorted(names):
print(" " + name)
Expand Down
4 changes: 2 additions & 2 deletions scripts/internal/bench_oneshot_2.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,8 +37,8 @@ def main():
args = runner.parse_args()
if not args.worker:
print(
"%s methods involved on platform %r (psutil %s):"
% (len(names), sys.platform, psutil.__version__)
f"{len(names)} methods involved on platform"
f" {sys.platform!r} (psutil {psutil.__version__}):"
)
for name in sorted(names):
print(" " + name)
Expand Down
2 changes: 1 addition & 1 deletion scripts/internal/winmake.py
Original file line number Diff line number Diff line change
Expand Up @@ -467,7 +467,7 @@ def get_python(path):
'312-64',
)
for v in vers:
pypath = r'C:\\python%s\python.exe' % v
pypath = rf"C:\\python{v}\python.exe"
if path in pypath and os.path.isfile(pypath):
return pypath

Expand Down

0 comments on commit b6693b9

Please sign in to comment.