Skip to content

Commit

Permalink
one-time run ruff with --unsafe-fixes for UP031
Browse files Browse the repository at this point in the history
  • Loading branch information
minrk committed Oct 28, 2024
1 parent b098c82 commit bae8d7f
Show file tree
Hide file tree
Showing 30 changed files with 146 additions and 150 deletions.
2 changes: 1 addition & 1 deletion docs/source/examples/Futures.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -564,7 +564,7 @@
" print(executor.__class__.__name__)\n",
" result = executor.map(task, sizes)\n",
" rlist = list(result)\n",
" assert rlist == ref, \"%s != %s\" % (rlist, ref)\n",
" assert rlist == ref, f\"{rlist} != {ref}\"\n",
" # time the task assignment\n",
" %timeit list(executor.map(task, sizes))"
]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -400,7 +400,7 @@
" plt.close('all')\n",
" display(fig)\n",
" print(msg)\n",
" print('Monitored for: %s.' % tmon)"
" print(f'Monitored for: {tmon}.')"
]
},
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -341,7 +341,7 @@
" plt.close('all')\n",
" display(fig)\n",
" print(msg)\n",
" print('Monitored for: %s.' % tmon)"
" print(f'Monitored for: {tmon}.')"
]
},
{
Expand Down
6 changes: 3 additions & 3 deletions docs/source/examples/interengine/interengine.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,10 +20,10 @@
def broadcast(client, sender, msg_name, dest_name=None, block=None):
"""broadcast a message from one engine to all others."""
dest_name = msg_name if dest_name is None else dest_name
client[sender].execute('com.publish(%s)' % msg_name, block=None)
client[sender].execute(f'com.publish({msg_name})', block=None)
targets = client.ids
targets.remove(sender)
return client[targets].execute('%s=com.consume()' % dest_name, block=None)
return client[targets].execute(f'{dest_name}=com.consume()', block=None)


def send(client, sender, targets, msg_name, dest_name=None, block=None):
Expand All @@ -36,4 +36,4 @@ def _send(targets, m_name):

client[sender].apply_async(_send, targets, msg_name)

return client[targets].execute('%s=com.recv()' % dest_name, block=None)
return client[targets].execute(f'{dest_name}=com.recv()', block=None)
2 changes: 1 addition & 1 deletion docs/source/examples/iopubwatcher.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,5 +83,5 @@ def main(connection_file):
# This gets the security file for the default profile:
pattern = 'ipcontroller-client.json'
cf = find_connection_file(pattern)
print("Using connection file %s" % cf)
print(f"Using connection file {cf}")
main(cf)
4 changes: 2 additions & 2 deletions ipyparallel/apps/baseapp.py
Original file line number Diff line number Diff line change
Expand Up @@ -176,7 +176,7 @@ def to_work_dir(self):
wd = self.work_dir
if wd != os.getcwd():
os.chdir(wd)
self.log.info("Changing to working dir: %s" % wd)
self.log.info(f"Changing to working dir: {wd}")
# This is the working dir by now.
sys.path.insert(0, '')

Expand All @@ -185,7 +185,7 @@ def reinit_logging(self):
log_dir = self.profile_dir.log_dir
if self.clean_logs:
for f in os.listdir(log_dir):
if re.match(r'%s-\d+\.(log|err|out)' % self.name, f):
if re.match(rf'{self.name}-\d+\.(log|err|out)', f):
try:
os.remove(os.path.join(log_dir, f))
except OSError:
Expand Down
2 changes: 1 addition & 1 deletion ipyparallel/apps/iploggerapp.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ def init_watcher(self):
except BaseException:
self.log.error("Couldn't start the LogWatcher", exc_info=True)
self.exit(1)
self.log.info("Listening for log messages on %r" % self.watcher.url)
self.log.info(f"Listening for log messages on {self.watcher.url!r}")

def start(self):
self.watcher.start()
Expand Down
6 changes: 3 additions & 3 deletions ipyparallel/apps/logwatcher.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ class LogWatcher(LoggingConfigurable):
url = Unicode(config=True, help="ZMQ url on which to listen for log messages")

def _url_default(self):
return 'tcp://%s:20202' % localhost()
return f'tcp://{localhost()}:20202'

# internals
stream = Instance('zmq.eventloop.zmqstream.ZMQStream', allow_none=True)
Expand Down Expand Up @@ -65,7 +65,7 @@ def subscribe(self):
self.stream.setsockopt(zmq.SUBSCRIBE, '')
else:
for topic in self.topics:
self.log.debug("Subscribing to: %r" % (topic))
self.log.debug(f"Subscribing to: {topic!r}")
self.stream.setsockopt(zmq.SUBSCRIBE, topic)

def _extract_level(self, topic_str):
Expand All @@ -86,7 +86,7 @@ def _extract_level(self, topic_str):
def log_message(self, raw):
"""receive and parse a message, then log it."""
if len(raw) != 2 or '.' not in raw[0]:
self.log.error("Invalid log message: %s" % raw)
self.log.error(f"Invalid log message: {raw}")
return
else:
topic, msg = raw
Expand Down
6 changes: 3 additions & 3 deletions ipyparallel/client/asyncresult.py
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,7 @@ def _init_futures(self):
future.set_result(result)
future.output.set_result(None)
if not future:
raise KeyError("No Future or result for msg_id: %s" % msg_id)
raise KeyError(f"No Future or result for msg_id: {msg_id}")
self._children.append(future)

self._result_future = multi_future(self._children)
Expand Down Expand Up @@ -703,7 +703,7 @@ def __getitem__(self, key):
return values
else:
raise TypeError(
"Invalid key type %r, must be 'int','slice', or 'str'" % type(key)
f"Invalid key type {type(key)!r}, must be 'int','slice', or 'str'"
)

def __getattr__(self, key):
Expand Down Expand Up @@ -1048,7 +1048,7 @@ def display_outputs(self, groupby="type", result_only=False):

else:
raise ValueError(
"groupby must be one of 'type', 'engine', 'collate', not %r" % groupby
f"groupby must be one of 'type', 'engine', 'collate', not {groupby!r}"
)


Expand Down
59 changes: 28 additions & 31 deletions ipyparallel/client/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -529,11 +529,10 @@ def __init__(
# This is only a warning, because the most likely cause
# is a local Controller on a laptop whose IP is dynamic
warnings.warn(
"""
f"""
Controller appears to be listening on localhost, but not on this machine.
If this is true, you should specify Client(...,sshserver='you@%s')
or instruct your controller to listen on an external IP."""
% location,
If this is true, you should specify Client(...,sshserver='you@{location}')
or instruct your controller to listen on an external IP.""",
RuntimeWarning,
)
elif not sshserver:
Expand All @@ -552,7 +551,7 @@ def __init__(
if tunnel.try_passwordless_ssh(sshserver, sshkey, paramiko):
password = False
else:
password = getpass("SSH Password for %s: " % sshserver)
password = getpass(f"SSH Password for {sshserver}: ")
ssh_kwargs = dict(keyfile=sshkey, password=password, paramiko=paramiko)

# configure and construct the session
Expand Down Expand Up @@ -706,7 +705,7 @@ def _build_targets(self, targets):
if targets.lower() == 'all':
targets = self._ids
else:
raise TypeError("%r not valid str target, must be 'all'" % (targets))
raise TypeError(f"{targets!r} not valid str target, must be 'all'")
elif isinstance(targets, int):
if targets < 0:
targets = self.ids[targets]
Expand All @@ -721,7 +720,7 @@ def _build_targets(self, targets):

if not isinstance(targets, (tuple, list, range)):
raise TypeError(
"targets by int/slice/collection of ints only, not %s" % (type(targets))
f"targets by int/slice/collection of ints only, not {type(targets)}"
)

return [self._engines[t].encode("utf8") for t in targets], list(targets)
Expand Down Expand Up @@ -790,7 +789,7 @@ def connect_socket(s, url):
else:
self._connected = False
tb = '\n'.join(content.get('traceback', []))
raise Exception("Failed to connect! %s" % tb)
raise Exception(f"Failed to connect! {tb}")

self._start_io_thread()

Expand Down Expand Up @@ -910,9 +909,9 @@ def _handle_execute_reply(self, msg):
future = self._futures.get(msg_id, None)
if msg_id not in self.outstanding:
if msg_id in self.history:
print("got stale result: %s" % msg_id)
print(f"got stale result: {msg_id}")
else:
print("got unknown result: %s" % msg_id)
print(f"got unknown result: {msg_id}")
else:
self.outstanding.remove(msg_id)

Expand Down Expand Up @@ -971,11 +970,11 @@ def _handle_apply_reply(self, msg):
future = self._futures.get(msg_id, None)
if msg_id not in self.outstanding:
if msg_id in self.history:
print("got stale result: %s" % msg_id)
print(f"got stale result: {msg_id}")
print(self.results[msg_id])
print(msg)
else:
print("got unknown result: %s" % msg_id)
print(f"got unknown result: {msg_id}")
else:
self.outstanding.remove(msg_id)
content = msg['content']
Expand Down Expand Up @@ -1102,7 +1101,7 @@ def _dispatch_notification(self, msg):
msg_type = msg['header']['msg_type']
handler = self._notification_handlers.get(msg_type, None)
if handler is None:
raise KeyError("Unhandled notification message type: %s" % msg_type)
raise KeyError(f"Unhandled notification message type: {msg_type}")
else:
handler(msg)

Expand All @@ -1112,7 +1111,7 @@ def _dispatch_reply(self, msg):
msg_type = msg['header']['msg_type']
handler = self._queue_handlers.get(msg_type, None)
if handler is None:
raise KeyError("Unhandled reply message type: %s" % msg_type)
raise KeyError(f"Unhandled reply message type: {msg_type}")
else:
handler(msg)

Expand Down Expand Up @@ -1331,9 +1330,7 @@ def __getitem__(self, key):
Must be int, slice, or list/tuple/range of ints"""
if not isinstance(key, (int, slice, tuple, list, range)):
raise TypeError(
"key by int/slice/iterable of ints only, not %s" % (type(key))
)
raise TypeError(f"key by int/slice/iterable of ints only, not {type(key)}")
else:
return self.direct_view(key)

Expand Down Expand Up @@ -1744,7 +1741,7 @@ def abort(self, jobs=None, targets=None, block=None):
bad_ids = [obj for obj in jobs if not isinstance(obj, (str, AsyncResult))]
if bad_ids:
raise TypeError(
"Invalid msg_id type %r, expected str or AsyncResult" % bad_ids[0]
f"Invalid msg_id type {bad_ids[0]!r}, expected str or AsyncResult"
)
for j in jobs:
if isinstance(j, AsyncResult):
Expand Down Expand Up @@ -1945,13 +1942,13 @@ def send_apply_request(

# validate arguments
if not callable(f) and not isinstance(f, (Reference, PrePickled)):
raise TypeError("f must be callable, not %s" % type(f))
raise TypeError(f"f must be callable, not {type(f)}")
if not isinstance(args, (tuple, list)):
raise TypeError("args must be tuple or list, not %s" % type(args))
raise TypeError(f"args must be tuple or list, not {type(args)}")
if not isinstance(kwargs, dict):
raise TypeError("kwargs must be dict, not %s" % type(kwargs))
raise TypeError(f"kwargs must be dict, not {type(kwargs)}")
if not isinstance(metadata, dict):
raise TypeError("metadata must be dict, not %s" % type(metadata))
raise TypeError(f"metadata must be dict, not {type(metadata)}")

bufs = serialize.pack_apply_message(
f,
Expand Down Expand Up @@ -1996,9 +1993,9 @@ def send_execute_request(

# validate arguments
if not isinstance(code, str):
raise TypeError("code must be text, not %s" % type(code))
raise TypeError(f"code must be text, not {type(code)}")
if not isinstance(metadata, dict):
raise TypeError("metadata must be dict, not %s" % type(metadata))
raise TypeError(f"metadata must be dict, not {type(metadata)}")

content = dict(code=code, silent=bool(silent), user_expressions={})

Expand Down Expand Up @@ -2281,7 +2278,9 @@ def result_status(self, msg_ids, status_only=True):
elif header['msg_type'] == 'execute_reply':
res = ExecuteReply(msg_id, rcontent, md)
else:
raise KeyError("unhandled msg type: %r" % header['msg_type'])
raise KeyError(
"unhandled msg type: {!r}".format(header['msg_type'])
)
else:
res = self._unwrap_exception(rcontent)
failures.append(res)
Expand Down Expand Up @@ -2354,7 +2353,7 @@ def _msg_ids_from_jobs(self, jobs=None):
elif isinstance(job, AsyncResult):
msg_ids.extend(job.msg_ids)
else:
raise TypeError("Expected msg_id, int, or AsyncResult, got %r" % job)
raise TypeError(f"Expected msg_id, int, or AsyncResult, got {job!r}")
return msg_ids

def _asyncresult_from_jobs(self, jobs=None, owner=False):
Expand Down Expand Up @@ -2387,7 +2386,7 @@ def _asyncresult_from_jobs(self, jobs=None, owner=False):
else:
msg_ids.extend(job.msg_ids)
else:
raise TypeError("Expected msg_id, int, or AsyncResult, got %r" % job)
raise TypeError(f"Expected msg_id, int, or AsyncResult, got {job!r}")
if msg_ids:
if single:
msg_ids = msg_ids[0]
Expand Down Expand Up @@ -2430,9 +2429,7 @@ def purge_local_results(self, jobs=[], targets=[]):

if jobs == 'all':
if self.outstanding:
raise RuntimeError(
"Can't purge outstanding tasks: %s" % self.outstanding
)
raise RuntimeError(f"Can't purge outstanding tasks: {self.outstanding}")
self.results.clear()
self.metadata.clear()
self._futures.clear()
Expand All @@ -2444,7 +2441,7 @@ def purge_local_results(self, jobs=[], targets=[]):
still_outstanding = self.outstanding.intersection(msg_ids)
if still_outstanding:
raise RuntimeError(
"Can't purge outstanding tasks: %s" % still_outstanding
f"Can't purge outstanding tasks: {still_outstanding}"
)
for mid in msg_ids:
self.results.pop(mid, None)
Expand Down
4 changes: 2 additions & 2 deletions ipyparallel/client/magics.py
Original file line number Diff line number Diff line change
Expand Up @@ -263,7 +263,7 @@ def __init__(self, shell, view, suffix=''):

def _eval_target_str(self, ts):
if ':' in ts:
targets = eval("self.view.client.ids[%s]" % ts)
targets = eval(f"self.view.client.ids[{ts}]")
elif 'all' in ts:
targets = 'all'
else:
Expand Down Expand Up @@ -375,7 +375,7 @@ def parallel_execute(
else:
str_targets = str(targets)
if self.verbose:
print(base + " execution on engine(s): %s" % str_targets)
print(base + f" execution on engine(s): {str_targets}")

result = self.view.execute(cell, silent=False, block=False)
result._fname = "%px"
Expand Down
4 changes: 2 additions & 2 deletions ipyparallel/client/remotefunction.py
Original file line number Diff line number Diff line change
Expand Up @@ -213,7 +213,7 @@ def __call__(self, *sequences, **kwargs):
client = self.view.client
_mapping = kwargs.pop('__ipp_mapping', False)
if kwargs:
raise TypeError("Unexpected keyword arguments: %s" % kwargs)
raise TypeError(f"Unexpected keyword arguments: {kwargs}")

lens = []
maxlen = minlen = -1
Expand All @@ -239,7 +239,7 @@ def __call__(self, *sequences, **kwargs):

# check that the length of sequences match
if not _mapping and minlen != maxlen:
msg = 'all sequences must have equal length, but have %s' % lens
msg = f'all sequences must have equal length, but have {lens}'
raise ValueError(msg)

balanced = 'Balanced' in self.view.__class__.__name__
Expand Down
Loading

0 comments on commit bae8d7f

Please sign in to comment.