Skip to content

Commit ae119bf

Browse files
Apply ruff/pyupgrade rule UP031
Use format specifiers instead of percent format Leave out tests for now.
1 parent 274248a commit ae119bf

38 files changed

+151
-198
lines changed

distributed/_concurrent_futures_thread.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -117,7 +117,7 @@ def __init__(self, max_workers=None, thread_name_prefix=""):
117117
self._shutdown = False
118118
self._shutdown_lock = threading.Lock()
119119
self._thread_name_prefix = thread_name_prefix or (
120-
"ThreadPoolExecutor-%d" % next(self._counter)
120+
f"ThreadPoolExecutor-{next(self._counter)}"
121121
)
122122

123123
def submit(self, fn, *args, **kwargs):
@@ -144,9 +144,8 @@ def weakref_cb(_, q=self._work_queue):
144144
# idle threads than items in the work queue.
145145
num_threads = len(self._threads)
146146
if num_threads < self._max_workers:
147-
thread_name = "%s_%d" % (self._thread_name_prefix or self, num_threads)
148147
t = threading.Thread(
149-
name=thread_name,
148+
name=f"{self._thread_name_prefix or self}_{num_threads}",
150149
target=_worker,
151150
args=(weakref.ref(self, weakref_cb), self._work_queue),
152151
)

distributed/batched.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -72,7 +72,7 @@ def __repr__(self):
7272
if self.closed():
7373
return "<BatchedSend: closed>"
7474
else:
75-
return "<BatchedSend: %d in buffer>" % len(self.buffer)
75+
return f"<BatchedSend: {len(self.buffer)} in buffer>"
7676

7777
__str__ = __repr__
7878

distributed/cfexecutor.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -56,8 +56,7 @@ def __init__(self, client, **kwargs):
5656
sk = set(kwargs)
5757
if not sk <= self._allowed_kwargs:
5858
raise TypeError(
59-
"unsupported arguments to ClientExecutor: %s"
60-
% sorted(sk - self._allowed_kwargs)
59+
f"unsupported arguments to ClientExecutor: {sorted(sk - self._allowed_kwargs)}"
6160
)
6261
self._client = client
6362
self._futures = weakref.WeakSet()
@@ -127,7 +126,7 @@ def map(self, fn, *iterables, **kwargs):
127126
end_time = timeout + time()
128127
kwargs.pop("chunksize", None)
129128
if kwargs:
130-
raise TypeError("unexpected arguments to map(): %s" % sorted(kwargs))
129+
raise TypeError(f"unexpected arguments to map(): {sorted(kwargs)}")
131130

132131
fs = self._client.map(fn, *iterables, **self._kwargs)
133132

distributed/client.py

Lines changed: 3 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1378,17 +1378,8 @@ def __repr__(self):
13781378
if addr:
13791379
nworkers = info.get("n_workers", 0)
13801380
nthreads = info.get("total_threads", 0)
1381-
text = "<%s: %r processes=%d threads=%d" % (
1382-
self.__class__.__name__,
1383-
addr,
1384-
nworkers,
1385-
nthreads,
1386-
)
13871381
memory = info.get("total_memory", 0)
1388-
text += ", memory=" + format_bytes(memory)
1389-
text += ">"
1390-
return text
1391-
1382+
return f"<{self.__class__.__name__}: {addr!r} processes={nworkers} threads={nthreads}, memory={format_bytes(memory)}>"
13921383
elif self.scheduler is not None:
13931384
return f"<{self.__class__.__name__}: scheduler={self.scheduler.address!r}>"
13941385
else:
@@ -2433,7 +2424,7 @@ async def wait(k):
24332424
bad_keys.add(key)
24342425
bad_data[key] = None
24352426
else: # pragma: no cover
2436-
raise ValueError("Bad value, `errors=%s`" % errors)
2427+
raise ValueError(f"Bad value, `errors={errors}`")
24372428

24382429
keys = [k for k in keys if k not in bad_keys and k not in data]
24392430

@@ -5886,7 +5877,7 @@ def update(self, futures):
58865877
with self.lock:
58875878
for f in futures:
58885879
if not isinstance(f, (Future, BaseActorFuture)):
5889-
raise TypeError("Input must be a future, got %s" % f)
5880+
raise TypeError(f"Input must be a future, got {f}")
58905881
self.futures[f] += 1
58915882
self.loop.add_callback(self._track_future, f)
58925883

distributed/comm/addressing.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,13 +18,13 @@ def parse_address(addr: str, strict: bool = False) -> tuple[str, str]:
1818
If strict is set to true the address must have a scheme.
1919
"""
2020
if not isinstance(addr, str):
21-
raise TypeError("expected str, got %r" % addr.__class__.__name__)
21+
raise TypeError(f"expected str, got {addr.__class__.__name__!r}")
2222
scheme, sep, loc = addr.rpartition("://")
2323
if strict and not sep:
2424
msg = (
2525
"Invalid url scheme. "
2626
"Must include protocol like tcp://localhost:8000. "
27-
"Got %s" % addr
27+
f"Got {addr}"
2828
)
2929
raise ValueError(msg)
3030
if not sep:

distributed/comm/inproc.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -63,7 +63,7 @@ def get_listener_for(self, addr):
6363
return self.listeners.get(addr)
6464

6565
def new_address(self):
66-
return "%s/%d/%s" % (self.ip, os.getpid(), next(self.addr_suffixes))
66+
return f"{self.ip}/{os.getpid()}/{next(self.addr_suffixes)}"
6767

6868
def validate_address(self, addr):
6969
"""
@@ -72,8 +72,7 @@ def validate_address(self, addr):
7272
ip, pid, suffix = addr.split("/")
7373
if ip != self.ip or int(pid) != os.getpid():
7474
raise ValueError(
75-
"inproc address %r does not match host (%r) or pid (%r)"
76-
% (addr, self.ip, os.getpid())
75+
f"inproc address {addr!r} does not match host ({self.ip!r}) or pid ({os.getpid()!r})"
7776
)
7877

7978

distributed/comm/tcp.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -468,7 +468,7 @@ def _check_encryption(self, address, connection_args):
468468
# XXX Should we have a dedicated SecurityError class?
469469
raise RuntimeError(
470470
"encryption required by Dask configuration, "
471-
"refusing communication from/to %r" % (self.prefix + address,)
471+
f"refusing communication from/to {self.prefix + address!r}"
472472
)
473473

474474

distributed/config.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -209,8 +209,9 @@ def get_loop_factory() -> Callable[[], asyncio.AbstractEventLoop] | None:
209209
return asyncio.SelectorEventLoop
210210
return None
211211
raise ValueError(
212-
"Expected distributed.admin.event-loop to be in ('asyncio', 'tornado', 'uvloop'), got %s"
213-
% dask.config.get("distributed.admin.event-loop")
212+
"Expected distributed.admin.event-loop to be in ('asyncio', 'tornado', 'uvloop'), got {}".format(
213+
dask.config.get("distributed.admin.event-loop")
214+
)
214215
)
215216

216217

distributed/core.py

Lines changed: 3 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -291,7 +291,7 @@ def __init__(
291291
self.handlers.update(handlers)
292292
if blocked_handlers is None:
293293
blocked_handlers = dask.config.get(
294-
"distributed.%s.blocked-handlers" % type(self).__name__.lower(), []
294+
f"distributed.{type(self).__name__.lower()}.blocked-handlers", []
295295
)
296296
self.blocked_handlers = blocked_handlers
297297
self.stream_handlers = {}
@@ -1227,7 +1227,7 @@ def __del__(self):
12271227
comm.abort()
12281228

12291229
def __repr__(self):
1230-
return "<rpc to %r, %d comms>" % (self.address, len(self.comms))
1230+
return f"<rpc to {self.address!r}, {len(self.comms)} comms>"
12311231

12321232

12331233
class PooledRPCCall:
@@ -1378,11 +1378,7 @@ def open(self) -> int:
13781378
return self.active + sum(map(len, self.available.values()))
13791379

13801380
def __repr__(self) -> str:
1381-
return "<ConnectionPool: open=%d, active=%d, connecting=%d>" % (
1382-
self.open,
1383-
self.active,
1384-
len(self._connecting),
1385-
)
1381+
return f"<ConnectionPool: open={self.open}, active={self.active}, connecting={len(self._connecting)}>"
13861382

13871383
def __call__(
13881384
self,

distributed/dashboard/components/scheduler.py

Lines changed: 17 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -3104,15 +3104,15 @@ def update(self):
31043104
# (ones without any compute during the relevant dt)
31053105
# 3. Colors the labels appropriately.
31063106
formatter = CustomJSHover(
3107-
code="""
3108-
const colormap = %s;
3107+
code=f"""
3108+
const colormap = {dict(zip(stackers, colors))};
31093109
const divs = [];
3110-
for (let k of Object.keys(source.data)) {
3110+
for (let k of Object.keys(source.data)) {{
31113111
const val = source.data[k][value];
31123112
const color = colormap[k];
3113-
if (k === "time" || k === "nthreads" || val < 1.e-3) {
3113+
if (k === "time" || k === "nthreads" || val < 1.e-3) {{
31143114
continue;
3115-
}
3115+
}}
31163116
const label = k.length >= 20 ? k.slice(0, 20) + '…' : k;
31173117
31183118
// Unshift so that the ordering of the labels is the same as
@@ -3127,18 +3127,15 @@ def update(self):
31273127
+ '</div>'
31283128
)
31293129
3130-
}
3130+
}}
31313131
divs.unshift(
31323132
'<div>'
31333133
+ '<span style="font-weight: bold; color: darkgrey;">nthreads: </span>'
31343134
+ source.data.nthreads[value]
31353135
+ '</div>'
31363136
);
31373137
return divs.join('\\n')
3138-
"""
3139-
% dict(
3140-
zip(stackers, colors)
3141-
), # sneak the color mapping into the callback
3138+
""", # sneak the color mapping into the callback
31423139
args={"source": self.source},
31433140
)
31443141
# Add the HoverTool to the top line renderer.
@@ -3378,13 +3375,13 @@ def update(self):
33783375
)
33793376

33803377
self.root.title.text = (
3381-
"Progress -- total: %(all)s, "
3382-
"waiting: %(waiting)s, "
3383-
"queued: %(queued)s, "
3384-
"processing: %(processing)s, "
3385-
"in-memory: %(memory)s, "
3386-
"no-worker: %(no_worker)s, "
3387-
"erred: %(erred)s" % totals
3378+
"Progress -- total: {all}, "
3379+
"waiting: {waiting}, "
3380+
"queued: {queued}, "
3381+
"processing: {processing}, "
3382+
"in-memory: {memory}, "
3383+
"no-worker: {no_worker}, "
3384+
"erred: {erred}".format(**totals)
33883385
)
33893386

33903387

@@ -4537,8 +4534,9 @@ def __init__(self, scheduler, start=None):
45374534
else:
45384535
logs_html = Log(
45394536
"\n".join(
4540-
"%s - %s"
4541-
% (datetime.fromtimestamp(time).strftime("%H:%M:%S.%f"), line)
4537+
"{} - {}".format(
4538+
datetime.fromtimestamp(time).strftime("%H:%M:%S.%f"), line
4539+
)
45424540
for time, level, line in logs
45434541
)
45444542
)._repr_html_()

0 commit comments

Comments
 (0)