Skip to content

Commit 5f69be1

Browse files
committed
Run flynt
1 parent 5173653 commit 5f69be1

20 files changed

+48
-80
lines changed

benchmarks/base.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -35,11 +35,11 @@ def run_benchmark(self):
3535
for value_set in itertools.product(*group_values):
3636
pairs = list(zip(group_names, value_set))
3737
arg_string = ', '.join(f'{p[0]}={p[1]}' for p in pairs)
38-
sys.stdout.write('Benchmark: %s... ' % arg_string)
38+
sys.stdout.write(f'Benchmark: {arg_string}... ')
3939
sys.stdout.flush()
4040
kwargs = dict(pairs)
4141
setup = functools.partial(self.setup, **kwargs)
4242
run = functools.partial(self.run, **kwargs)
4343
t = timeit.timeit(stmt=run, setup=setup, number=1000)
44-
sys.stdout.write('%f\n' % t)
44+
sys.stdout.write(f'{t:f}\n')
4545
sys.stdout.flush()

benchmarks/command_packer_benchmark.py

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -16,8 +16,7 @@ def send_packed_command(self, command, check_health=True):
1616
_errno, errmsg = 'UNKNOWN', e.args[0]
1717
else:
1818
_errno, errmsg = e.args
19-
raise ConnectionError("Error %s while writing to socket. %s." %
20-
(_errno, errmsg))
19+
raise ConnectionError(f"Error {_errno} while writing to socket. {errmsg}.")
2120
except Exception:
2221
self.disconnect()
2322
raise
@@ -48,8 +47,7 @@ def send_packed_command(self, command, check_health=True):
4847
_errno, errmsg = 'UNKNOWN', e.args[0]
4948
else:
5049
_errno, errmsg = e.args
51-
raise ConnectionError("Error %s while writing to socket. %s." %
52-
(_errno, errmsg))
50+
raise ConnectionError(f"Error {_errno} while writing to socket. {errmsg}.")
5351
except Exception:
5452
self.disconnect()
5553
raise

redis/client.py

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1141,7 +1141,7 @@ def __enter__(self):
11411141
# check that monitor returns 'OK', but don't return it to user
11421142
response = self.connection.read_response()
11431143
if not bool_ok(response):
1144-
raise RedisError('MONITOR failed: %s' % response)
1144+
raise RedisError(f'MONITOR failed: {response}')
11451145
return self
11461146

11471147
def __exit__(self, *args):
@@ -1517,12 +1517,10 @@ def run_in_thread(self, sleep_time=0, daemon=False,
15171517
exception_handler=None):
15181518
for channel, handler in self.channels.items():
15191519
if handler is None:
1520-
raise PubSubError("Channel: '%s' has no handler registered" %
1521-
channel)
1520+
raise PubSubError(f"Channel: '{channel}' has no handler registered")
15221521
for pattern, handler in self.patterns.items():
15231522
if handler is None:
1524-
raise PubSubError("Pattern: '%s' has no handler registered" %
1525-
pattern)
1523+
raise PubSubError(f"Pattern: '{pattern}' has no handler registered")
15261524

15271525
thread = PubSubWorkerThread(
15281526
self,

redis/cluster.py

Lines changed: 3 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -678,8 +678,7 @@ def _determine_nodes(self, *args, **kwargs):
678678
# get the nodes group for this command if it was predefined
679679
command_flag = self.command_flags.get(command)
680680
if command_flag:
681-
log.debug("Target node/s for {0}: {1}".
682-
format(command, command_flag))
681+
log.debug(f"Target node/s for {command}: {command_flag}")
683682
if command_flag == self.__class__.RANDOM:
684683
# return a random node
685684
return [self.get_random_node()]
@@ -824,8 +823,7 @@ def execute_command(self, *args, **kwargs):
824823
*args, **kwargs, nodes_flag=target_nodes)
825824
if not target_nodes:
826825
raise RedisClusterException(
827-
"No targets were found to execute"
828-
" {} command on".format(args))
826+
f"No targets were found to execute {args} command on")
829827
for node in target_nodes:
830828
res[node.name] = self._execute_command(
831829
node, *args, **kwargs)
@@ -1495,8 +1493,7 @@ def _raise_on_invalid_node(self, redis_cluster, node, host, port):
14951493
"""
14961494
if node is None or redis_cluster.get_node(node_name=node.name) is None:
14971495
raise RedisClusterException(
1498-
"Node {}:{} doesn't exist in the cluster"
1499-
.format(host, port))
1496+
f"Node {host}:{port} doesn't exist in the cluster")
15001497

15011498
def execute_command(self, *args, **kwargs):
15021499
"""

redis/commands/cluster.py

Lines changed: 4 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -228,8 +228,7 @@ def client_kill_filter(self, _id=None, _type=None, addr=None,
228228
if _type is not None:
229229
client_types = ('normal', 'master', 'slave', 'pubsub')
230230
if str(_type).lower() not in client_types:
231-
raise DataError("CLIENT KILL type must be one of {!r}".format(
232-
client_types))
231+
raise DataError(f"CLIENT KILL type must be one of {client_types!r}")
233232
args.extend((b'TYPE', _type))
234233
if skipme is not None:
235234
if not isinstance(skipme, bool):
@@ -267,8 +266,7 @@ def client_list(self, _type=None, target_nodes=None):
267266
if _type is not None:
268267
client_types = ('normal', 'master', 'replica', 'pubsub')
269268
if str(_type).lower() not in client_types:
270-
raise DataError("CLIENT LIST _type must be one of {!r}".format(
271-
client_types))
269+
raise DataError(f"CLIENT LIST _type must be one of {client_types!r}")
272270
return self.execute_command('CLIENT LIST',
273271
b'TYPE',
274272
_type,
@@ -302,7 +300,7 @@ def client_reply(self, reply, target_nodes=None):
302300
"""
303301
replies = ['ON', 'OFF', 'SKIP']
304302
if reply not in replies:
305-
raise DataError('CLIENT REPLY must be one of %r' % replies)
303+
raise DataError(f'CLIENT REPLY must be one of {replies!r}')
306304
return self.execute_command("CLIENT REPLY", reply,
307305
target_nodes=target_nodes)
308306

@@ -788,8 +786,7 @@ def cluster_failover(self, target_node, option=None):
788786
if option:
789787
if option.upper() not in ['FORCE', 'TAKEOVER']:
790788
raise RedisError(
791-
'Invalid option for CLUSTER FAILOVER command: {}'.format(
792-
option))
789+
f'Invalid option for CLUSTER FAILOVER command: {option}')
793790
else:
794791
return self.execute_command('CLUSTER FAILOVER', option,
795792
target_nodes=target_node)

redis/commands/core.py

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -342,8 +342,7 @@ def client_kill_filter(self, _id=None, _type=None, addr=None,
342342
if _type is not None:
343343
client_types = ('normal', 'master', 'slave', 'pubsub')
344344
if str(_type).lower() not in client_types:
345-
raise DataError("CLIENT KILL type must be one of {!r}".format(
346-
client_types))
345+
raise DataError(f"CLIENT KILL type must be one of {client_types!r}")
347346
args.extend((b'TYPE', _type))
348347
if skipme is not None:
349348
if not isinstance(skipme, bool):
@@ -388,8 +387,7 @@ def client_list(self, _type=None, client_id=[]):
388387
if _type is not None:
389388
client_types = ('normal', 'master', 'replica', 'pubsub')
390389
if str(_type).lower() not in client_types:
391-
raise DataError("CLIENT LIST _type must be one of {!r}".format(
392-
client_types))
390+
raise DataError(f"CLIENT LIST _type must be one of {client_types!r}")
393391
args.append(b'TYPE')
394392
args.append(_type)
395393
if not isinstance(client_id, list):
@@ -434,7 +432,7 @@ def client_reply(self, reply):
434432
"""
435433
replies = ['ON', 'OFF', 'SKIP']
436434
if reply not in replies:
437-
raise DataError('CLIENT REPLY must be one of %r' % replies)
435+
raise DataError(f'CLIENT REPLY must be one of {replies!r}')
438436
return self.execute_command("CLIENT REPLY", reply)
439437

440438
def client_id(self):
@@ -551,7 +549,7 @@ def config_rewrite(self):
551549
return self.execute_command('CONFIG REWRITE')
552550

553551
def cluster(self, cluster_arg, *args):
554-
return self.execute_command('CLUSTER %s' % cluster_arg.upper(), *args)
552+
return self.execute_command(f'CLUSTER {cluster_arg.upper()}', *args)
555553

556554
def dbsize(self):
557555
"""

redis/commands/search/commands.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -348,7 +348,7 @@ def _mk_query_args(self, query):
348348
# convert the query from a text to a query object
349349
query = Query(query)
350350
if not isinstance(query, Query):
351-
raise ValueError("Bad query type %s" % type(query))
351+
raise ValueError(f"Bad query type {type(query)}")
352352

353353
args += query.get_args()
354354
return args, query

redis/commands/search/document.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,4 +10,4 @@ def __init__(self, id, payload=None, **fields):
1010
setattr(self, k, v)
1111

1212
def __repr__(self):
13-
return "Document %s" % self.__dict__
13+
return f"Document {self.__dict__}"

redis/commands/search/indexDefinition.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -38,8 +38,7 @@ def _appendIndexType(self, index_type):
3838
elif index_type is IndexType.JSON:
3939
self.args.extend(["ON", "JSON"])
4040
elif index_type is not None:
41-
raise RuntimeError("index_type must be one of {}".
42-
format(list(IndexType)))
41+
raise RuntimeError(f"index_type must be one of {list(IndexType)}")
4342

4443
def _appendPrefix(self, prefix):
4544
"""Append PREFIX."""

redis/commands/search/querystring.py

Lines changed: 3 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -199,11 +199,9 @@ def join_fields(self, key, vals):
199199
if len(vals) == 1:
200200
return [BaseNode(f"@{key}:{vals[0].to_string()}")]
201201
if not vals[0].combinable:
202-
return [BaseNode("@{}:{}".format(key,
203-
v.to_string())) for v in vals]
202+
return [BaseNode(f"@{key}:{v.to_string()}") for v in vals]
204203
s = BaseNode(
205-
"@{}:({})".format(key,
206-
self.JOINSTR.join(v.to_string() for v in vals))
204+
f"@{key}:({self.JOINSTR.join(v.to_string() for v in vals)})"
207205
)
208206
return [s]
209207

@@ -220,9 +218,7 @@ def JOINSTR(self):
220218
def to_string(self, with_parens=None):
221219
with_parens = self._should_use_paren(with_parens)
222220
pre, post = ("(", ")") if with_parens else ("", "")
223-
return "{}{}{}".format(
224-
pre, self.JOINSTR.join(n.to_string() for n in self.params), post
225-
)
221+
return f"{pre}{self.JOINSTR.join(n.to_string() for n in self.params)}{post}"
226222

227223
def _should_use_paren(self, optval):
228224
if optval is not None:

redis/connection.py

Lines changed: 9 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -214,8 +214,7 @@ def _read_from_socket(self, length=None, timeout=SENTINEL,
214214
allowed = NONBLOCKING_EXCEPTION_ERROR_NUMBERS.get(ex.__class__, -1)
215215
if not raise_on_timeout and ex.errno == allowed:
216216
return False
217-
raise ConnectionError("Error while reading from socket: %s" %
218-
(ex.args,))
217+
raise ConnectionError(f"Error while reading from socket: {ex.args}")
219218
finally:
220219
if custom_timeout:
221220
sock.settimeout(self.socket_timeout)
@@ -323,7 +322,7 @@ def read_response(self, disable_decoding=False):
323322
byte, response = raw[:1], raw[1:]
324323

325324
if byte not in (b'-', b'+', b':', b'$', b'*'):
326-
raise InvalidResponse("Protocol Error: %r" % raw)
325+
raise InvalidResponse(f"Protocol Error: {raw!r}")
327326

328327
# server returned an error
329328
if byte == b'-':
@@ -445,8 +444,7 @@ def read_from_socket(self, timeout=SENTINEL, raise_on_timeout=True):
445444
allowed = NONBLOCKING_EXCEPTION_ERROR_NUMBERS.get(ex.__class__, -1)
446445
if not raise_on_timeout and ex.errno == allowed:
447446
return False
448-
raise ConnectionError("Error while reading from socket: %s" %
449-
(ex.args,))
447+
raise ConnectionError(f"Error while reading from socket: {ex.args}")
450448
finally:
451449
if custom_timeout:
452450
sock.settimeout(self._socket_timeout)
@@ -646,8 +644,7 @@ def _error_message(self, exception):
646644
# args for socket.error can either be (errno, "message")
647645
# or just "message"
648646
if len(exception.args) == 1:
649-
return "Error connecting to %s:%s. %s." % \
650-
(self.host, self.port, exception.args[0])
647+
return f"Error connecting to {self.host}:{self.port}. {exception.args[0]}."
651648
else:
652649
return "Error %s connecting to %s:%s. %s." % \
653650
(exception.args[0], self.host, self.port, exception.args[1])
@@ -741,8 +738,7 @@ def send_packed_command(self, command, check_health=True):
741738
else:
742739
errno = e.args[0]
743740
errmsg = e.args[1]
744-
raise ConnectionError("Error %s while writing to socket. %s." %
745-
(errno, errmsg))
741+
raise ConnectionError(f"Error {errno} while writing to socket. {errmsg}.")
746742
except BaseException:
747743
self.disconnect()
748744
raise
@@ -767,8 +763,7 @@ def read_response(self, disable_decoding=False):
767763
)
768764
except socket.timeout:
769765
self.disconnect()
770-
raise TimeoutError("Timeout reading from %s:%s" %
771-
(self.host, self.port))
766+
raise TimeoutError(f"Timeout reading from {self.host}:{self.port}")
772767
except OSError as e:
773768
self.disconnect()
774769
raise ConnectionError("Error while reading from %s:%s : %s" %
@@ -867,8 +862,7 @@ def __init__(self, ssl_keyfile=None, ssl_certfile=None,
867862
}
868863
if ssl_cert_reqs not in CERT_REQS:
869864
raise RedisError(
870-
"Invalid SSL Certificate Requirements Flag: %s" %
871-
ssl_cert_reqs)
865+
f"Invalid SSL Certificate Requirements Flag: {ssl_cert_reqs}")
872866
ssl_cert_reqs = CERT_REQS[ssl_cert_reqs]
873867
self.cert_reqs = ssl_cert_reqs
874868
self.ca_certs = ssl_ca_certs
@@ -947,8 +941,7 @@ def _error_message(self, exception):
947941
# args for socket.error can either be (errno, "message")
948942
# or just "message"
949943
if len(exception.args) == 1:
950-
return "Error connecting to unix socket: %s. %s." % \
951-
(self.path, exception.args[0])
944+
return f"Error connecting to unix socket: {self.path}. {exception.args[0]}."
952945
else:
953946
return "Error %s connecting to unix socket: %s. %s." % \
954947
(exception.args[0], self.path, exception.args[1])
@@ -990,7 +983,7 @@ def parse_url(url):
990983
kwargs[name] = parser(value)
991984
except (TypeError, ValueError):
992985
raise ValueError(
993-
"Invalid value for `%s` in connection URL." % name
986+
f"Invalid value for `{name}` in connection URL."
994987
)
995988
else:
996989
kwargs[name] = value

redis/sentinel.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -136,7 +136,7 @@ def rotate_slaves(self):
136136
yield self.get_master_address()
137137
except MasterNotFoundError:
138138
pass
139-
raise SlaveNotFoundError('No slave found for %r' % (self.service_name))
139+
raise SlaveNotFoundError(f'No slave found for {self.service_name!r}')
140140

141141

142142
class Sentinel(SentinelCommands):

tasks.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -73,7 +73,7 @@ def clean(c):
7373
shutil.rmtree("build")
7474
if os.path.isdir("dist"):
7575
shutil.rmtree("dist")
76-
run("docker rm -f {}".format(' '.join(dockers)))
76+
run(f"docker rm -f {' '.join(dockers)}")
7777

7878

7979
@task

tests/conftest.py

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -87,8 +87,7 @@ def wait_for_cluster_creation(redis_url, cluster_nodes, timeout=20):
8787
now = time.time()
8888
end_time = now + timeout
8989
client = None
90-
print("Waiting for {0} cluster nodes to become available".
91-
format(cluster_nodes))
90+
print(f"Waiting for {cluster_nodes} cluster nodes to become available")
9291
while now < end_time:
9392
try:
9493
client = redis.RedisCluster.from_url(redis_url)
@@ -320,8 +319,8 @@ def wait_for_command(client, monitor, command):
320319
if LooseVersion(redis_version) >= LooseVersion('5.0.0'):
321320
id_str = str(client.client_id())
322321
else:
323-
id_str = '%08x' % random.randrange(2**32)
324-
key = '__REDIS-PY-%s__' % id_str
322+
id_str = f'{random.randrange(2 ** 32):08x}'
323+
key = f'__REDIS-PY-{id_str}__'
325324
client.get(key)
326325
while True:
327326
monitor_response = monitor.next_command()

tests/test_cluster.py

Lines changed: 3 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -333,8 +333,7 @@ def ok_response(connection, *args, **options):
333333
return "MOCK_OK"
334334

335335
parse_response.side_effect = ok_response
336-
raise AskError("12182 {}:{}".format(redirect_node.host,
337-
redirect_node.port))
336+
raise AskError(f"12182 {redirect_node.host}:{redirect_node.port}")
338337

339338
parse_response.side_effect = ask_redirect_effect
340339

@@ -2373,8 +2372,7 @@ def test_asking_error(self, r):
23732372
warnings.warn("skipping this test since the cluster has only one "
23742373
"node")
23752374
return
2376-
ask_msg = "{} {}:{}".format(r.keyslot(key), ask_node.host,
2377-
ask_node.port)
2375+
ask_msg = f"{r.keyslot(key)} {ask_node.host}:{ask_node.port}"
23782376

23792377
def raise_ask_error():
23802378
raise AskError(ask_msg)
@@ -2434,9 +2432,7 @@ def test_moved_redirection_on_slave_with_default(self, r):
24342432
with r.pipeline() as readwrite_pipe:
24352433
mock_node_resp(primary, "MOCK_FOO")
24362434
if replica is not None:
2437-
moved_error = "{} {}:{}".format(r.keyslot(key),
2438-
primary.host,
2439-
primary.port)
2435+
moved_error = f"{r.keyslot(key)} {primary.host}:{primary.port}"
24402436

24412437
def raise_moved_error():
24422438
raise MovedError(moved_error)

tests/test_commands.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1805,11 +1805,11 @@ def test_zadd_incr_with_xx(self, r):
18051805
def test_zadd_gt_lt(self, r):
18061806

18071807
for i in range(1, 20):
1808-
r.zadd('a', {'a%s' % i: i})
1808+
r.zadd('a', {f'a{i}': i})
18091809
assert r.zadd('a', {'a20': 5}, gt=3) == 1
18101810

18111811
for i in range(1, 20):
1812-
r.zadd('a', {'a%s' % i: i})
1812+
r.zadd('a', {f'a{i}': i})
18131813
assert r.zadd('a', {'a2': 5}, lt=1) == 0
18141814

18151815
# cannot use both nx and xx options

tests/test_connection.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ def test_invalid_response(r):
1515
with mock.patch.object(parser._buffer, 'readline', return_value=raw):
1616
with pytest.raises(InvalidResponse) as cm:
1717
parser.read_response()
18-
assert str(cm.value) == 'Protocol Error: %r' % raw
18+
assert str(cm.value) == f'Protocol Error: {raw!r}'
1919

2020

2121
@skip_if_server_version_lt('4.0.0')

0 commit comments

Comments
 (0)