Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use f-strings #2483

Merged
merged 13 commits into from
Dec 20, 2024
18 changes: 9 additions & 9 deletions .github/workflows/issues.py
Original file line number Diff line number Diff line change
Expand Up @@ -194,29 +194,29 @@ def get_issue():

def log(msg):
if '\n' in msg or "\r\n" in msg:
print(">>>\n%s\n<<<" % msg, flush=True)
print(f">>>\n{msg}\n<<<", flush=True)
else:
print(">>> %s <<<" % msg, flush=True)
print(f">>> {msg} <<<", flush=True)


def add_label(issue, label):
def should_add(issue, label):
if has_label(issue, label):
log("already has label %r" % (label))
log(f"already has label {label!r}")
return False

for left, right in ILLOGICAL_PAIRS:
if label == left and has_label(issue, right):
log("already has label" % (label))
log(f"already has label f{label}")
return False

return not has_label(issue, label)

if not should_add(issue, label):
log("should not add label %r" % label)
log(f"should not add label {label!r}")
return

log("add label %r" % label)
log(f"add label {label!r}")
issue.add_to_labels(label)


Expand Down Expand Up @@ -329,16 +329,16 @@ def on_new_pr(issue):
def main():
issue = get_issue()
stype = "PR" if is_pr(issue) else "issue"
log("running issue bot for %s %r" % (stype, issue))
log(f"running issue bot for {stype} {issue!r}")

if is_event_new_issue():
log("created new issue %s" % issue)
log(f"created new issue {issue}")
add_labels_from_text(issue, issue.title)
if issue.body:
add_labels_from_new_body(issue, issue.body)
on_new_issue(issue)
elif is_event_new_pr():
log("created new PR %s" % issue)
log(f"created new PR {issue}")
add_labels_from_text(issue, issue.title)
if issue.body:
add_labels_from_new_body(issue, issue.body)
Expand Down
4 changes: 2 additions & 2 deletions docs/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ def get_version():

# General information about the project.
project = PROJECT_NAME
copyright = '2009-%s, %s' % (THIS_YEAR, AUTHOR)
copyright = f"2009-{THIS_YEAR}, {AUTHOR}"
author = AUTHOR

# The version info for the project you're documenting, acts as replacement for
Expand Down Expand Up @@ -267,7 +267,7 @@ def get_version():
# html_search_scorer = 'scorer.js'

# Output file base name for HTML help builder.
htmlhelp_basename = '%s-doc' % PROJECT_NAME
htmlhelp_basename = f"{PROJECT_NAME}-doc"

# -- Options for LaTeX output ---------------------------------------------

Expand Down
43 changes: 22 additions & 21 deletions psutil/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -135,7 +135,8 @@
PROCFS_PATH = "/proc"

else: # pragma: no cover
raise NotImplementedError('platform %s is not supported' % sys.platform)
msg = f"platform {sys.platform} is not supported"
raise NotImplementedError(msg)


# fmt: off
Expand Down Expand Up @@ -223,15 +224,15 @@
if int(__version__.replace('.', '')) != getattr(
_psplatform.cext, 'version', None
):
msg = "version conflict: %r C extension " % _psplatform.cext.__file__
msg = f"version conflict: {_psplatform.cext.__file__!r} C extension "
msg += "module was built for another version of psutil"
if hasattr(_psplatform.cext, 'version'):
msg += " (%s instead of %s)" % (
'.'.join([x for x in str(_psplatform.cext.version)]),
__version__,
)
else:
msg += " (different than %s)" % __version__
msg += f" (different than {__version__})"
msg += "; you may try to 'pip uninstall psutil', manually remove %s" % (
getattr(
_psplatform.cext,
Expand Down Expand Up @@ -323,12 +324,12 @@ def _init(self, pid, _ignore_nsp=False):
pid = os.getpid()
else:
if pid < 0:
msg = "pid must be a positive integer (got %s)" % pid
msg = f"pid must be a positive integer (got {pid})"
raise ValueError(msg)
try:
_psplatform.cext.check_pid_range(pid)
except OverflowError:
msg = "process PID out of range (got %s)" % pid
msg = f"process PID out of range (got {pid})"
raise NoSuchProcess(pid, msg=msg)

self._pid = pid
Expand Down Expand Up @@ -419,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 @@ -553,7 +554,7 @@ def as_dict(self, attrs=None, ad_value=None):
valid_names = _as_dict_attrnames
if attrs is not None:
if not isinstance(attrs, (list, tuple, set, frozenset)):
msg = "invalid attrs type %s" % type(attrs)
msg = f"invalid attrs type {type(attrs)}"
raise TypeError(msg)
attrs = set(attrs)
invalid_names = attrs - valid_names
Expand Down Expand Up @@ -1046,7 +1047,7 @@ def cpu_percent(self, interval=None):
"""
blocking = interval is not None and interval > 0.0
if interval is not None and interval < 0:
msg = "interval is not positive (got %r)" % interval
msg = f"interval is not positive (got {interval!r})"
raise ValueError(msg)
num_cpus = cpu_count() or 1

Expand Down Expand Up @@ -1156,9 +1157,9 @@ def memory_percent(self, memtype="rss"):
"""
valid_types = list(_psplatform.pfullmem._fields)
if memtype not in valid_types:
msg = "invalid memtype %r; valid types are %r" % (
memtype,
tuple(valid_types),
msg = (
f"invalid memtype {memtype!r}; valid types are"
f" {tuple(valid_types)!r}"
)
raise ValueError(msg)
fun = (
Expand All @@ -1175,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 Expand Up @@ -1438,9 +1439,9 @@ def __getattribute__(self, name):
try:
return object.__getattribute__(self.__subproc, name)
except AttributeError:
msg = "%s instance has no attribute '%s'" % (
self.__class__.__name__,
name,
msg = (
f"{self.__class__.__name__} instance has no attribute"
f" '{name}'"
)
raise AttributeError(msg)

Expand Down Expand Up @@ -1524,7 +1525,7 @@ def remove(pid):
remove(pid)
while _pids_reused:
pid = _pids_reused.pop()
debug("refreshing Process instance for reused PID %s" % pid)
debug(f"refreshing Process instance for reused PID {pid}")
remove(pid)
try:
ls = sorted(list(pmap.items()) + list(dict.fromkeys(new_pids).items()))
Expand Down Expand Up @@ -1596,12 +1597,12 @@ def check_gone(proc, timeout):
callback(proc)

if timeout is not None and not timeout >= 0:
msg = "timeout must be a positive integer, got %s" % timeout
msg = f"timeout must be a positive integer, got {timeout}"
raise ValueError(msg)
gone = set()
alive = set(procs)
if callback is not None and not callable(callback):
msg = "callback %r is not a callable" % callback
msg = f"callback {callback!r} is not a callable"
raise TypeError(msg)
if timeout is not None:
deadline = _timer() + timeout
Expand Down Expand Up @@ -1801,7 +1802,7 @@ def cpu_percent(interval=None, percpu=False):
tid = threading.current_thread().ident
blocking = interval is not None and interval > 0.0
if interval is not None and interval < 0:
msg = "interval is not positive (got %r)" % interval
msg = f"interval is not positive (got {interval})"
raise ValueError(msg)

def calculate(t1, t2):
Expand Down Expand Up @@ -1861,7 +1862,7 @@ def cpu_times_percent(interval=None, percpu=False):
tid = threading.current_thread().ident
blocking = interval is not None and interval > 0.0
if interval is not None and interval < 0:
msg = "interval is not positive (got %r)" % interval
msg = f"interval is not positive (got {interval!r})"
raise ValueError(msg)

def calculate(t1, t2):
Expand Down Expand Up @@ -2243,7 +2244,7 @@ def net_if_addrs():
# https://github.com/giampaolo/psutil/issues/786
separator = ":" if POSIX else "-"
while addr.count(separator) < 5:
addr += "%s00" % separator
addr += f"{separator}00"
ret[name].append(_common.snicaddr(fam, addr, mask, broadcast, ptp))
return dict(ret)

Expand Down
26 changes: 13 additions & 13 deletions psutil/_common.py
Original file line number Diff line number Diff line change
Expand Up @@ -289,8 +289,8 @@ def __str__(self):
def __repr__(self):
# invoked on `repr(Error)`
info = self._infodict(("pid", "ppid", "name", "seconds", "msg"))
details = ", ".join(["%s=%r" % (k, v) for k, v in info.items()])
return "psutil.%s(%s)" % (self.__class__.__name__, details)
details = ", ".join([f"{k}={v!r}" for k, v in info.items()])
return f"psutil.{self.__class__.__name__}({details})"


class NoSuchProcess(Error):
Expand Down Expand Up @@ -356,7 +356,7 @@ def __init__(self, seconds, pid=None, name=None):
self.seconds = seconds
self.pid = pid
self.name = name
self.msg = "timeout after %s seconds" % seconds
self.msg = f"timeout after {seconds} seconds"

def __reduce__(self):
return (self.__class__, (self.seconds, self.pid, self.name))
Expand Down Expand Up @@ -863,13 +863,12 @@ 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')
return '\x1b[%sm%s\x1b[0m' % (';'.join(attr), s)
return f"\x1b[{';'.join(attr)}m{s}\x1b[0m"


def print_color(
Expand All @@ -894,10 +893,11 @@ def print_color(
try:
color = colors[color]
except KeyError:
raise ValueError(
"invalid color %r; choose between %r"
% (color, list(colors.keys()))
msg = (
f"invalid color {color!r}; choose between"
f" {list(colors.keys())!r}"
)
raise ValueError(msg)
if bold and color <= 7:
color += 8

Expand All @@ -922,9 +922,9 @@ def debug(msg):
if isinstance(msg, Exception):
if isinstance(msg, OSError):
# ...because str(exc) may contain info about the file name
msg = "ignoring %s" % msg
msg = f"ignoring {msg}"
else:
msg = "ignoring %r" % msg
msg = f"ignoring {msg!r}"
print( # noqa
"psutil-debug [%s:%s]> %s" % (fname, lineno, msg), file=sys.stderr
f"psutil-debug [{fname}:{lineno}]> {msg}", file=sys.stderr
)
13 changes: 7 additions & 6 deletions psutil/_psaix.py
Original file line number Diff line number Diff line change
Expand Up @@ -146,7 +146,8 @@ def cpu_count_cores():
stdout, stderr = p.communicate()
stdout, stderr = (x.decode(sys.stdout.encoding) for x in (stdout, stderr))
if p.returncode != 0:
raise RuntimeError("%r command error\n%s" % (cmd, stderr))
msg = f"{cmd!r} command error\n{stderr}"
raise RuntimeError(msg)
processors = stdout.strip().splitlines()
return len(processors) or None

Expand Down Expand Up @@ -430,7 +431,7 @@ def threads(self):
# is no longer there.
if not retlist:
# will raise NSP if process is gone
os.stat('%s/%s' % (self._procfs_path, self.pid))
os.stat(f"{self._procfs_path}/{self.pid}")
return retlist

@wrap_exceptions
Expand All @@ -443,7 +444,7 @@ def net_connections(self, kind='inet'):
# is no longer there.
if not ret:
# will raise NSP if process is gone
os.stat('%s/%s' % (self._procfs_path, self.pid))
os.stat(f"{self._procfs_path}/{self.pid}")
return ret

@wrap_exceptions
Expand Down Expand Up @@ -489,10 +490,10 @@ def terminal(self):
def cwd(self):
procfs_path = self._procfs_path
try:
result = os.readlink("%s/%s/cwd" % (procfs_path, self.pid))
result = os.readlink(f"{procfs_path}/{self.pid}/cwd")
return result.rstrip('/')
except FileNotFoundError:
os.stat("%s/%s" % (procfs_path, self.pid)) # raise NSP or AD
os.stat(f"{procfs_path}/{self.pid}") # raise NSP or AD
return ""

@wrap_exceptions
Expand Down Expand Up @@ -539,7 +540,7 @@ def open_files(self):
def num_fds(self):
if self.pid == 0: # no /proc/0/fd
return 0
return len(os.listdir("%s/%s/fd" % (self._procfs_path, self.pid)))
return len(os.listdir(f"{self._procfs_path}/{self.pid}/fd"))

@wrap_exceptions
def num_ctx_switches(self):
Expand Down
Loading
Loading