Convert legacy string formatting to f-strings (#4685)

* the changes

* Update driver.py
This commit is contained in:
GiGaGon 2025-06-05 18:51:26 -07:00 committed by GitHub
parent e5e5dad792
commit 7987951e24
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
5 changed files with 19 additions and 34 deletions

View File

@ -77,7 +77,7 @@ def blackify(base_branch: str, black_command: str, logger: logging.Logger) -> in
git("commit", "--allow-empty", "-aqC", commit)
for commit in commits:
git("branch", "-qD", "%s-black" % commit)
git("branch", "-qD", f"{commit}-black")
return 0

View File

@ -28,16 +28,16 @@ def escape(m: re.Match[str]) -> str:
if tail.startswith("x"):
hexes = tail[1:]
if len(hexes) < 2:
raise ValueError("invalid hex string escape ('\\%s')" % tail)
raise ValueError(f"invalid hex string escape ('\\{tail}')")
try:
i = int(hexes, 16)
except ValueError:
raise ValueError("invalid hex string escape ('\\%s')" % tail) from None
raise ValueError(f"invalid hex string escape ('\\{tail}')") from None
else:
try:
i = int(tail, 8)
except ValueError:
raise ValueError("invalid octal string escape ('\\%s')" % tail) from None
raise ValueError(f"invalid octal string escape ('\\{tail}')") from None
return chr(i)

View File

@ -140,7 +140,7 @@ def calcfirst(self, name: str) -> None:
if label in self.first:
fset = self.first[label]
if fset is None:
raise ValueError("recursion for rule %r" % name)
raise ValueError(f"recursion for rule {name!r}")
else:
self.calcfirst(label)
fset = self.first[label]
@ -155,8 +155,8 @@ def calcfirst(self, name: str) -> None:
for symbol in itsfirst:
if symbol in inverse:
raise ValueError(
"rule %s is ambiguous; %s is in the first sets of %s as well"
" as %s" % (name, symbol, label, inverse[symbol])
f"rule {name} is ambiguous; {symbol} is in the first sets of"
f" {label} as well as {inverse[symbol]}"
)
inverse[symbol] = label
self.first[name] = totalset
@ -237,16 +237,16 @@ def dump_nfa(self, name: str, start: "NFAState", finish: "NFAState") -> None:
j = len(todo)
todo.append(next)
if label is None:
print(" -> %d" % j)
print(f" -> {j}")
else:
print(" %s -> %d" % (label, j))
print(f" {label} -> {j}")
def dump_dfa(self, name: str, dfa: Sequence["DFAState"]) -> None:
print("Dump of DFA for", name)
for i, state in enumerate(dfa):
print(" State", i, state.isfinal and "(final)" or "")
for label, next in sorted(state.arcs.items()):
print(" %s -> %d" % (label, dfa.index(next)))
print(f" {label} -> {dfa.index(next)}")
def simplify_dfa(self, dfa: list["DFAState"]) -> None:
# This is not theoretically optimal, but works well enough.
@ -330,15 +330,12 @@ def parse_atom(self) -> tuple["NFAState", "NFAState"]:
return a, z
else:
self.raise_error(
"expected (...) or NAME or STRING, got %s/%s", self.type, self.value
f"expected (...) or NAME or STRING, got {self.type}/{self.value}"
)
raise AssertionError
def expect(self, type: int, value: Optional[Any] = None) -> str:
if self.type != type or (value is not None and self.value != value):
self.raise_error(
"expected %s/%s, got %s/%s", type, value, self.type, self.value
)
self.raise_error(f"expected {type}/{value}, got {self.type}/{self.value}")
value = self.value
self.gettoken()
return value
@ -350,12 +347,7 @@ def gettoken(self) -> None:
self.type, self.value, self.begin, self.end, self.line = tup
# print token.tok_name[self.type], repr(self.value)
def raise_error(self, msg: str, *args: Any) -> NoReturn:
if args:
try:
msg = msg % args
except Exception:
msg = " ".join([msg] + list(map(str, args)))
def raise_error(self, msg: str) -> NoReturn:
raise SyntaxError(
msg, (str(self.filename), self.end[0], self.end[1], self.line)
)

View File

@ -206,9 +206,7 @@ def printtoken(
) -> None: # for testing
(srow, scol) = srow_col
(erow, ecol) = erow_col
print(
"%d,%d-%d,%d:\t%s\t%s" % (srow, scol, erow, ecol, tok_name[type], repr(token))
)
print(f"{srow},{scol}-{erow},{ecol}:\t{tok_name[type]}\t{token!r}")
if __name__ == "__main__": # testing

View File

@ -268,11 +268,7 @@ def __init__(
def __repr__(self) -> str:
"""Return a canonical string representation."""
assert self.type is not None
return "{}({}, {!r})".format(
self.__class__.__name__,
type_repr(self.type),
self.children,
)
return f"{self.__class__.__name__}({type_repr(self.type)}, {self.children!r})"
def __str__(self) -> str:
"""
@ -421,10 +417,9 @@ def __repr__(self) -> str:
from .pgen2.token import tok_name
assert self.type is not None
return "{}({}, {!r})".format(
self.__class__.__name__,
tok_name.get(self.type, self.type),
self.value,
return (
f"{self.__class__.__name__}({tok_name.get(self.type, self.type)},"
f" {self.value!r})"
)
def __str__(self) -> str:
@ -527,7 +522,7 @@ def __repr__(self) -> str:
args = [type_repr(self.type), self.content, self.name]
while args and args[-1] is None:
del args[-1]
return "{}({})".format(self.__class__.__name__, ", ".join(map(repr, args)))
return f"{self.__class__.__name__}({', '.join(map(repr, args))})"
def _submatch(self, node, results=None) -> bool:
raise NotImplementedError