A line variable is called a line, and a format string is one string

The mechanical tail of the ruff pass, all of it behaviour-preserving.

`E741`: 29 uses of the ambiguous `l`, which reads as a `1` in most fonts.
Twenty-four of them held a rendered line and are now `ln`; three held an MVT
`Layer` and are now `layer`; two were a map label sorted by rank, now `lab`.
Renaming only the flagged line and then re-running `F821` was the check — a
half-renamed comprehension leaves a name nothing defines, so the linter finds
what a careful read might not.

`UP031`: 15 `%`-format strings become `.format` calls. `UP007`: the `CellStyle`
and `LabelT` aliases become `X | Y`; both are annotation-only, so the runtime
value never mattered. `E702`: four semicolon-chained `await` lines in
`test_device_state` get a line each.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Jean-Pierre MartineauandClaude Opus 5 committed 2026-09-06 20:14:42 -04:00
1 parent 61b6387269
commit e9a4f644d8
16 files changed
+61 -56

No files matched your search

@@ -179,8 +179,7 @@ def install():
total = (time.perf_counter() - t_disp) * 1000
_state["t_dispatch"] = None
_rows.append(
"%.3f,%s,%s,%.2f,%.2f,%.2f,%.2f,%.2f,%.2f,%.2f,%d,%.2f"
% (
"{:.3f},{},{},{:.2f},{:.2f},{:.2f},{:.2f},{:.2f},{:.2f},{:.2f},{:d},{:.2f}".format(
time.time(), _state["screen"] or "-", action,
handle, ms("header"), ms("compose"), ms("dialog"),
ms("parse"), dt * 1000, total,
@@ -206,10 +205,10 @@ def _flush():
def main():
with open(TRACE + ".log", "a") as fh:
fh.write("install start %.3f argv=%r\n" % (time.time(), sys.argv))
fh.write(f"install start {time.time():.3f} argv={sys.argv!r}\n")
install()
with open(TRACE + ".log", "a") as fh:
fh.write("install done %.3f\n" % time.time())
fh.write(f"install done {time.time():.3f}\n")
import atexit
atexit.register(_flush)
+1 -2
View File
@@ -45,7 +45,6 @@ Beyond timelines, the module owns the app's two other braille conventions:
from __future__ import annotations
from collections.abc import Callable, Sequence
from typing import Union
from rich.text import Text
@@ -88,7 +87,7 @@ _RIGHT_BITS = (0x80, 0x20, 0x10, 0x08)
#: How a lit cell is styled: a fixed Rich style name, or a callable given the
#: cell's present readings (one or two values) returning the style — the hook the
#: Time Machine uses to colour an SNR band by each slice's quality.
CellStyle = Union[str, Callable[[list[float]], str]]
CellStyle = str | Callable[[list[float]], str]
class _Gap:
+1 -1
View File
@@ -442,7 +442,7 @@ def _compose(
# ever taking space from a street that has none, so a name is drawn once per frame.
placed = 0
named: set[str] = set()
for label in sorted(frame.labels, key=lambda l: l.rank):
for label in sorted(frame.labels, key=lambda lab: lab.rank):
if placed >= max_labels:
break
if viewport.zoom < label.min_zoom or label.text in named:
+1 -2
View File
@@ -35,7 +35,6 @@ from dataclasses import dataclass
from typing import (
TYPE_CHECKING,
Any,
Union,
)
from rich.cells import cell_len
@@ -50,7 +49,7 @@ if TYPE_CHECKING:
#: What a command row's label may be: plain text, or styled text whose spans survive the
#: icon cut (an err-tinted destructive row, a live unread badge).
LabelT = Union[str, Text]
LabelT = str | Text
#: The app's status-atom separator, in its two widths. ``·`` chains atoms (the standards'
+1 -1
View File
@@ -186,7 +186,7 @@ _ARROW_GAP_DOTS = 2
#: value in this range folds to the console's dark-grey slot, so the rule survives the
#: 16-colour quantizer unchanged.
_OFF_ROUTE: RGB = (110, 110, 110)
_OFF_ROUTE_HEX = "#%02x%02x%02x" % _OFF_ROUTE
_OFF_ROUTE_HEX = "#{:02x}{:02x}{:02x}".format(*_OFF_ROUTE)
#: Most distinct paths the lane order is optimised over by exhaustive search. Beyond it the
#: search space (``(n-1)!`` orders of the non-central lanes) is too large, so a barycentre
+12 -14
View File
@@ -26,7 +26,7 @@ def find_uf2_drive():
if os.name == "nt":
import string
candidates = ["%s:\\" % d for d in string.ascii_uppercase]
candidates = [f"{d}:\\" for d in string.ascii_uppercase]
else:
for base in ("/media", "/run/media", "/mnt", "/Volumes"):
candidates += glob.glob(os.path.join(base, "*"))
@@ -57,7 +57,7 @@ def touch_1200():
if "2886" in (p.hwid or ""): # Seeed Studio USB VID
try:
serial.Serial(p.device, 1200).close()
print(" sent 1200-baud bootloader touch to %s" % p.device)
print(f" sent 1200-baud bootloader touch to {p.device}")
time.sleep(0.3)
except Exception:
pass
@@ -101,18 +101,17 @@ def check_drive_is_ours(drive, force=False):
info = read_uf2_info(drive)
model = info.get("Model", "?")
softdev = info.get("SoftDevice", "?")
print(" %s reports: %s / %s" % (drive, model, softdev))
print(f" {drive} reports: {model} / {softdev}")
problems = []
if "xiao" not in model.lower():
problems.append("this is a %r bootloader, not a XIAO" % model)
problems.append(f"this is a {model!r} bootloader, not a XIAO")
if "6." in softdev:
problems.append("%s expects the app at 0x26000; this build is linked for S140 v7" % softdev)
problems.append(f"{softdev} expects the app at 0x26000; this build is linked for S140 v7")
if problems and not force:
sys.exit(
"ERROR: refusing to flash %s --\n - %s\n"
"Unplug the other board, or re-run with --force if you are sure."
% (drive, "\n - ".join(problems))
"ERROR: refusing to flash {} --\n - {}\n"
"Unplug the other board, or re-run with --force if you are sure.".format(drive, "\n - ".join(problems))
)
return True
@@ -122,7 +121,7 @@ def main():
force = "--force" in sys.argv[1:]
uf2 = args[0] if args else os.path.join(HERE, "meshcore-xiao-radio.uf2")
if not os.path.exists(uf2):
sys.exit("ERROR: firmware not found: %s\n(run build-firmware.sh first)" % uf2)
sys.exit(f"ERROR: firmware not found: {uf2}\n(run build-firmware.sh first)")
print(">> looking for XIAO bootloader drive ...")
drive = find_uf2_drive()
@@ -137,16 +136,15 @@ def main():
if drive and drive == before:
# The letter was already there before we touched anything, so it may belong to some
# other board entirely -- check what it says rather than trusting the letter.
print(" note: %s was already mounted before the touch" % drive)
print(f" note: {drive} was already mounted before the touch")
if not drive:
port = bootloader_port()
if port:
sys.exit(
"ERROR: the XIAO is in its bootloader on %s but exposes no UF2 drive.\n"
f"ERROR: the XIAO is in its bootloader on {port} but exposes no UF2 drive.\n"
"This bootloader presents a serial port only, so copy-to-drive can't work.\n"
"Flash it over serial DFU instead, from your MeshCore checkout:\n"
" pio run -e Xiao_nrf52_companion_radio_serial -t upload --upload-port %s"
% (port, port)
f" pio run -e Xiao_nrf52_companion_radio_serial -t upload --upload-port {port}"
)
sys.exit(
"ERROR: no UF2 bootloader drive and no XIAO bootloader serial port found.\n"
@@ -154,7 +152,7 @@ def main():
)
check_drive_is_ours(drive, force=force)
print(">> flashing %s -> %s" % (os.path.basename(uf2), drive))
print(f">> flashing {os.path.basename(uf2)} -> {drive}")
with open(uf2, "rb") as src:
data = src.read()
with open(os.path.join(drive, "firmware.uf2"), "wb") as dst:
+1 -1
View File
@@ -926,7 +926,7 @@ def test_wrapped_body_hangs_under_the_first_line() -> None:
text = " ".join(["word"] * 20)
messages = [ChatMessage(text=text, peer="d4e5f6a7", created_at=base)]
screen = _screen(_StubSession(), send=None, messages=messages)
body_lines = [_strip_ansi(l) for l in screen._body_lines(text, messages[0], 30)]
body_lines = [_strip_ansi(ln) for ln in screen._body_lines(text, messages[0], 30)]
assert len(body_lines) > 1 # it actually wrapped
stamp = base.astimezone().strftime("%H:%M")
+14 -4
View File
@@ -249,10 +249,14 @@ def test_invalidation_forces_a_re_read() -> None:
ds = _devstate(dev)
async def run() -> None:
await ds.self_info(); await ds.path_hash_mode(); await ds.channel_slots(); await ds.contacts()
await ds.self_info()
await ds.path_hash_mode()
await ds.channel_slots()
await ds.contacts()
# invalidate_config drops self-info + path-hash mode together (the config editor's write).
ds.invalidate_config()
await ds.self_info(); await ds.path_hash_mode()
await ds.self_info()
await ds.path_hash_mode()
assert dev.self_info_calls == 2 and dev.mode_calls == 2
# channels and contacts were untouched by that invalidation.
assert dev.channel_calls == 2 and dev.contacts_calls == 1
@@ -269,9 +273,15 @@ def test_reset_clears_everything() -> None:
ds = _devstate(dev)
async def run() -> None:
await ds.self_info(); await ds.contacts(); await ds.path_hash_mode(); await ds.channel_capacity()
await ds.self_info()
await ds.contacts()
await ds.path_hash_mode()
await ds.channel_capacity()
ds.reset()
await ds.self_info(); await ds.contacts(); await ds.path_hash_mode(); await ds.channel_capacity()
await ds.self_info()
await ds.contacts()
await ds.path_hash_mode()
await ds.channel_capacity()
asyncio.run(run())
assert dev.self_info_calls == 2
+1 -1
View File
@@ -332,7 +332,7 @@ async def test_previous_stamp_sits_on_its_own_line() -> None:
old = _trace(4.0)
old.timestamp = utcnow() - timedelta(hours=3)
screen, _ = _trace_screen(previous=old)
stamp_line = next(l for l in screen.render_body(100) if "(previous" in l)
stamp_line = next(ln for ln in screen.render_body(100) if "(previous" in ln)
assert "→" not in stamp_line # the route stays on the line above
+4 -4
View File
@@ -423,7 +423,7 @@ def _street_labels_placed(cols: int, rows: int, zoom: int) -> int:
_draw_tile(frame, layers, 14, 4843, 5861)
placed = 0
for label in sorted(frame.labels, key=lambda l: l.rank):
for label in sorted(frame.labels, key=lambda lab: lab.rank):
if vp.zoom < label.min_zoom:
continue
for ax, ay in ((label.x, label.y), *label.alts):
@@ -905,7 +905,7 @@ def test_decoded_layers_survive_a_round_trip() -> None:
restored = loads_layers(dumps_layers(original, stamp="x"), stamp="x")
assert restored is not None
assert [(l.name, l.extent) for l in restored] == [(l.name, l.extent) for l in original]
assert [(layer.name, layer.extent) for layer in restored] == [(layer.name, layer.extent) for layer in original]
for before, after in zip(original, restored, strict=True):
assert after.features == before.features
@@ -946,8 +946,8 @@ def test_basemap_source_writes_and_reuses_a_decoded_sidecar(tmp_path: Path) -> N
tile.write_bytes(b"junk that cannot decode")
second = src.load_tile(14, 4843, 5861)
assert second is not None
assert [(l.name, len(l.features)) for l in second] == [
(l.name, len(l.features)) for l in first
assert [(layer.name, len(layer.features)) for layer in second] == [
(layer.name, len(layer.features)) for layer in first
]
+1 -1
View File
@@ -274,7 +274,7 @@ def test_paths_screen_direct_arrival_and_empty_state() -> None:
screen = _screen([Arrival(when=now, hops=(), snr=2.5)])
body = _plain(screen.render_body(76))
assert "❯ Alice → ★" in body
route = next(l for l in body.splitlines() if l.startswith("❯"))
route = next(ln for ln in body.splitlines() if ln.startswith("❯"))
assert "direct" not in route
assert body.splitlines()[body.splitlines().index(route) + 1].strip().startswith("direct")
empty = _screen([], matched=False)
+13 -13
View File
@@ -687,9 +687,9 @@ def test_node_detail_routes_stage_spends_the_caption_and_top_air_on_the_fan() ->
screen.handle("tab") # onto Routes
screen.note_viewport(viewport)
lines = screen.render_body(49)
strip_idx = next(i for i, l in enumerate(lines) if "Routes" in _plain([l]) and "│" in _plain([l]))
rule_idx = next(i for i, l in enumerate(lines) if set(_plain([l])) == {"─"} and i > strip_idx)
return [_plain([l]) for l in lines[strip_idx + 2 : rule_idx]] # past the strip's own rule
strip_idx = next(i for i, ln in enumerate(lines) if "Routes" in _plain([ln]) and "│" in _plain([ln]))
rule_idx = next(i for i, ln in enumerate(lines) if set(_plain([ln])) == {"─"} and i > strip_idx)
return [_plain([ln]) for ln in lines[strip_idx + 2 : rule_idx]] # past the strip's own rule
set_platform(PICOCALC)
pico = _stage(22)
@@ -702,7 +702,7 @@ def test_node_detail_routes_stage_spends_the_caption_and_top_air_on_the_fan() ->
assert any("node → you, as heard" in line for line in desktop) # …and its caption
# Both rows land in the drawing, not in the chrome: from the same viewport the console
# grants this ceiling-bound fan two more canvas rows than the captioned desktop stage.
drawn = [l for l in desktop if "node → you" not in l]
drawn = [ln for ln in desktop if "node → you" not in ln]
assert len(pico) == len(drawn) + 2
@@ -726,7 +726,7 @@ def test_node_detail_screen_context_hangs_under_the_pathline() -> None:
body = _plain(lines)
assert "f2 3d aa …" in body # the pathline, opens-marked
assert "weakest -6.0 dB" in body and "★ best" in body # the context, drawn too
path_idx = next(i for i, l in enumerate(lines) if "f2 3d aa" in _plain([l]))
path_idx = next(i for i, ln in enumerate(lines) if "f2 3d aa" in _plain([ln]))
assert _plain([lines[path_idx]]).startswith("❯ f2 3d aa") # the pointer leads the pathline
context_line = _plain([lines[path_idx + 1]])
assert context_line.startswith(" weakest") # hanging two columns under it, no pointer
@@ -745,7 +745,7 @@ def test_node_detail_screen_context_line_absent_when_theres_nothing_to_show() ->
screen = _screen(routes=routes, tabs=[_Tab("Routes", "routes")])
screen.note_viewport(30)
lines = screen.render_body(72)
path_idx = next(i for i, l in enumerate(lines) if "f2 aa" in _plain([l]))
path_idx = next(i for i, ln in enumerate(lines) if "f2 aa" in _plain([ln]))
# Nothing at all hangs under a route that earned no context: the pathline is the last
# thing the page draws (the tab carries no action rows), not a muted context line.
rest = _plain(lines[path_idx + 1:]).strip()
@@ -772,14 +772,14 @@ def test_node_detail_screen_hscrolls_the_selected_pathline() -> None:
assert "f2 00 01 02" in body # unscrolled, the chain's start shows
assert "←→ scroll" in screen.footer_hint # the overflow earns the footer atom
row = next(l for l in _plain(screen.render_body(72)).splitlines() if l.startswith("❯"))
row = next(ln for ln in _plain(screen.render_body(72)).splitlines() if ln.startswith("❯"))
assert row.rstrip().endswith("…") # the right edge marks the remainder, before any scroll
screen.handle("right")
screen.handle("right")
body = _plain(screen.render_body(72))
assert "f2 00 01 02" not in body # the view has shifted away from the start
row = next(l for l in body.splitlines() if l.startswith("❯"))
row = next(ln for ln in body.splitlines() if ln.startswith("❯"))
assert row.startswith("❯ …") # …and now a mark says the line continues behind us, too
screen.handle("left")
@@ -788,7 +788,7 @@ def test_node_detail_screen_hscrolls_the_selected_pathline() -> None:
for _ in range(20): # run the scroll to its stop
screen.handle("right")
row = next(l for l in _plain(screen.render_body(72)).splitlines() if l.startswith("❯"))
row = next(ln for ln in _plain(screen.render_body(72)).splitlines() if ln.startswith("❯"))
# The clamp lands where the tail is actually readable: the line's own end — its last hop
# — is on screen rather than cropped behind a right-hand edge mark promising a remainder
# the keys can no longer reach. Only the left mark is left drawn; the opens-further `…`
@@ -796,7 +796,7 @@ def test_node_detail_screen_hscrolls_the_selected_pathline() -> None:
assert row.rstrip().endswith("aa") and row.count("…") == 1
screen.handle("right") # …and the stop holds: nothing moves past it
assert next(
l for l in _plain(screen.render_body(72)).splitlines() if l.startswith("❯")
ln for ln in _plain(screen.render_body(72)).splitlines() if ln.startswith("❯")
) == row
screen.handle("down") # onto route 1 — abandons route 0's scroll, short row can't scroll
@@ -832,7 +832,7 @@ def test_node_detail_route_row_cracks_a_chip_path_at_both_edges() -> None:
def selected_row() -> str:
return next(
l for l in _plain(screen.render_body(72)).splitlines() if l.startswith("❯")
ln for ln in _plain(screen.render_body(72)).splitlines() if ln.startswith("❯")
)
row = selected_row()
@@ -864,7 +864,7 @@ def test_node_detail_route_row_spends_no_lane_cells_on_the_opens_marker() -> Non
screen = _screen(routes=routes, tabs=[_Tab("Routes", "routes")])
screen.note_viewport(30)
row = next(
l for l in _plain(screen.render_body(72)).splitlines() if l.startswith("❯")
ln for ln in _plain(screen.render_body(72)).splitlines() if ln.startswith("❯")
)
assert row == "❯ " + "x" * avail # whole, uncut, and no mark squeezed in
# …and with nothing to scroll, ←→ stay inert and unadvertised.
@@ -881,7 +881,7 @@ def test_node_detail_route_row_spends_no_lane_cells_on_the_opens_marker() -> Non
screen = _screen(routes=roomy, tabs=[_Tab("Routes", "routes")])
screen.note_viewport(30)
row = next(
l for l in _plain(screen.render_body(72)).splitlines() if l.startswith("❯")
ln for ln in _plain(screen.render_body(72)).splitlines() if ln.startswith("❯")
)
assert row == "❯ " + "x" * (avail - 2) + " …"
+3 -3
View File
@@ -316,7 +316,7 @@ def test_packet_viewer_from_row_leads_with_the_node_type_mark() -> None:
from meshterm.core.models import NODE_TYPE_REPEATER
def from_row(viewer: PacketViewer) -> str:
return next(l for l in _stripped(viewer.render_body(80)) if l.startswith("from"))
return next(ln for ln in _stripped(viewer.render_body(80)) if ln.startswith("from"))
advertised = PacketEntry(
when=utcnow(), kind="advert", node="3d63", name="Hub", node_type=NODE_TYPE_REPEATER
@@ -366,8 +366,8 @@ def test_packet_viewer_lays_out_what_a_frame_addressed() -> None:
prefix_bytes=1, self_name="Waymarker",
)
lines = _stripped(viewer.render_body(80))
to_row = next(l for l in lines if l.startswith("to"))
from_row = next(l for l in lines if l.startswith("from"))
to_row = next(ln for ln in lines if ln.startswith("to"))
from_row = next(ln for ln in lines if ln.startswith("from"))
assert "Waymarker" in to_row and "c0" in to_row # the name, then the hash it was named by
assert "Alice" in from_row and "a1" in from_row
# …and neither is repeated by the generic raw dump at the foot of the card.
+1 -1
View File
@@ -62,7 +62,7 @@ def _row(*, selected: bool) -> Text:
def _hues(ansi: str) -> set[str]:
"""The truecolor foregrounds the rendered row actually emitted, as ``#rrggbb``."""
return {
"#%02x%02x%02x" % tuple(int(part) for part in match.groups())
"#{:02x}{:02x}{:02x}".format(*tuple(int(part) for part in match.groups()))
for match in re.finditer(r"\x1b\[[\d;]*?38;2;(\d+);(\d+);(\d+)m", ansi)
}
+1 -1
View File
@@ -657,7 +657,7 @@ def test_composer_use_row_names_the_action_not_the_path() -> None:
def use_row(screen: PathComposerScreen) -> str:
body = plain(screen.render_body(90))
row = next(l for l in body.splitlines() if "Use this path" in l)
row = next(ln for ln in body.splitlines() if "Use this path" in ln)
return row.replace("❯", "").strip()
armed = _composer(_topo(trace_paths=walks), hops=["3d63c6429436"])
+3 -3
View File
@@ -147,7 +147,7 @@ def test_walk_graph_labels_names_in_full_when_the_canvas_has_room() -> None:
screen.note_viewport(24)
# The canvas rows are everything above the legend line.
lines = _plain(screen.render_body(80)).split("\n")
canvas = "\n".join(lines[: next(i for i, l in enumerate(lines) if "edge = SNR" in l)])
canvas = "\n".join(lines[: next(i for i, ln in enumerate(lines) if "edge = SNR" in ln)])
assert "Lakesidetechnique" in canvas # 17 chars, drawn whole — no "Lakesidetechniq…"
assert "Repeater-Downtown-01" in canvas # 20 chars, whole
@@ -184,7 +184,7 @@ def test_walk_selected_link_lights_the_route_that_reaches_it() -> None:
screen.handle("down")
ansi_lines = screen.render_body(80)
legend = next(i for i, l in enumerate(ansi_lines) if "edge = SNR" in _plain([l]))
legend = next(i for i, ln in enumerate(ansi_lines) if "edge = SNR" in _plain([ln]))
canvas = "".join(ansi_lines[:legend])
def code(rgb: tuple[int, int, int]) -> str:
@@ -415,7 +415,7 @@ def test_walk_echoes_the_find_query_above_the_matches_it_narrows() -> None:
for _ in "al":
device.handle("backspace")
assert not any(line.strip().startswith("/") for line in
(_plain(l) for l in device.render_body(53)))
(_plain(ln) for ln in device.render_body(53)))
finally:
set_platform(REGULAR)