Skip to content

Commit 0923095

Browse files
committed
Replace remaining % and .format with f-strings (by hand)
1 parent 5f69be1 commit 0923095

File tree

12 files changed

+111
-117
lines changed

12 files changed

+111
-117
lines changed

benchmarks/basic_operations.py

Lines changed: 7 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -62,10 +62,9 @@ def set_str(conn, num, pipeline_size, data_size):
6262
if pipeline_size > 1:
6363
conn = conn.pipeline()
6464

65-
format_str = '{:0<%d}' % data_size
66-
set_data = format_str.format('a')
65+
set_data = 'a'.ljust(data_size, '0')
6766
for i in range(num):
68-
conn.set('set_str:%d' % i, set_data)
67+
conn.set(f'set_str:{i}', set_data)
6968
if pipeline_size > 1 and i % pipeline_size == 0:
7069
conn.execute()
7170

@@ -78,10 +77,9 @@ def set_int(conn, num, pipeline_size, data_size):
7877
if pipeline_size > 1:
7978
conn = conn.pipeline()
8079

81-
format_str = '{:0<%d}' % data_size
82-
set_data = int(format_str.format('1'))
80+
set_data = 10 ** (data_size - 1)
8381
for i in range(num):
84-
conn.set('set_int:%d' % i, set_data)
82+
conn.set(f'set_int:{i}', set_data)
8583
if pipeline_size > 1 and i % pipeline_size == 0:
8684
conn.execute()
8785

@@ -95,7 +93,7 @@ def get_str(conn, num, pipeline_size, data_size):
9593
conn = conn.pipeline()
9694

9795
for i in range(num):
98-
conn.get('set_str:%d' % i)
96+
conn.get(f'set_str:{i}')
9997
if pipeline_size > 1 and i % pipeline_size == 0:
10098
conn.execute()
10199

@@ -109,7 +107,7 @@ def get_int(conn, num, pipeline_size, data_size):
109107
conn = conn.pipeline()
110108

111109
for i in range(num):
112-
conn.get('set_int:%d' % i)
110+
conn.get(f'set_int:{i}')
113111
if pipeline_size > 1 and i % pipeline_size == 0:
114112
conn.execute()
115113

@@ -136,8 +134,7 @@ def lpush(conn, num, pipeline_size, data_size):
136134
if pipeline_size > 1:
137135
conn = conn.pipeline()
138136

139-
format_str = '{:0<%d}' % data_size
140-
set_data = int(format_str.format('1'))
137+
set_data = 10 ** (data_size - 1)
141138
for i in range(num):
142139
conn.lpush('lpush_key', set_data)
143140
if pipeline_size > 1 and i % pipeline_size == 0:

redis/client.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1805,8 +1805,10 @@ def raise_first_error(self, commands, response):
18051805

18061806
def annotate_exception(self, exception, number, command):
18071807
cmd = ' '.join(map(safe_str, command))
1808-
msg = 'Command # %d (%s) of pipeline caused error: %s' % (
1809-
number, cmd, exception.args[0])
1808+
msg = (
1809+
f'Command # {number} ({cmd}) of pipeline '
1810+
f'caused error: {exception.args[0]}'
1811+
)
18101812
exception.args = (msg,) + exception.args[1:]
18111813

18121814
def parse_response(self, connection, command_name, **options):

redis/cluster.py

Lines changed: 47 additions & 49 deletions
Original file line numberDiff line numberDiff line change
@@ -740,16 +740,17 @@ def determine_slot(self, *args):
740740
raise RedisClusterException(
741741
"No way to dispatch this command to Redis Cluster. "
742742
"Missing key.\nYou can execute the command by specifying "
743-
"target nodes.\nCommand: {}".format(args)
743+
f"target nodes.\nCommand: {args}"
744744
)
745745

746746
if len(keys) > 1:
747747
# multi-key command, we need to make sure all keys are mapped to
748748
# the same slot
749749
slots = {self.keyslot(key) for key in keys}
750750
if len(slots) != 1:
751-
raise RedisClusterException("{} - all keys must map to the "
752-
"same key slot".format(args[0]))
751+
raise RedisClusterException(
752+
f"{args[0]} - all keys must map to the same key slot"
753+
)
753754
return slots.pop()
754755
else:
755756
# single key command
@@ -774,12 +775,12 @@ def _parse_target_nodes(self, target_nodes):
774775
# rc.cluster_save_config(rc.get_primaries())
775776
nodes = target_nodes.values()
776777
else:
777-
raise TypeError("target_nodes type can be one of the "
778-
"followings: node_flag (PRIMARIES, "
779-
"REPLICAS, RANDOM, ALL_NODES),"
780-
"ClusterNode, list<ClusterNode>, or "
781-
"dict<any, ClusterNode>. The passed type is {0}".
782-
format(type(target_nodes)))
778+
raise TypeError(
779+
"target_nodes type can be one of the following: "
780+
"node_flag (PRIMARIES, REPLICAS, RANDOM, ALL_NODES),"
781+
"ClusterNode, list<ClusterNode>, or dict<any, ClusterNode>. "
782+
f"The passed type is {type(target_nodes)}"
783+
)
783784
return nodes
784785

785786
def execute_command(self, *args, **kwargs):
@@ -866,9 +867,10 @@ def _execute_command(self, target_node, *args, **kwargs):
866867
command in READ_COMMANDS)
867868
moved = False
868869

869-
log.debug("Executing command {0} on target node: {1} {2}".
870-
format(command, target_node.server_type,
871-
target_node.name))
870+
log.debug(
871+
f"Executing command {command} on target node: "
872+
f"{target_node.server_type} {target_node.name}"
873+
)
872874
redis_node = self.get_redis_connection(target_node)
873875
connection = get_connection(redis_node, *args, **kwargs)
874876
if asking:
@@ -1005,13 +1007,13 @@ def __init__(self, host, port, server_type=None, redis_connection=None):
10051007
self.redis_connection = redis_connection
10061008

10071009
def __repr__(self):
1008-
return '[host={},port={},' \
1009-
'name={},server_type={},redis_connection={}]' \
1010-
.format(self.host,
1011-
self.port,
1012-
self.name,
1013-
self.server_type,
1014-
self.redis_connection)
1010+
return (
1011+
f'[host={self.host},'
1012+
f'port={self.port},'
1013+
f'name={self.name},'
1014+
f'server_type={self.server_type},'
1015+
f'redis_connection={self.redis_connection}]'
1016+
)
10151017

10161018
def __eq__(self, obj):
10171019
return isinstance(obj, ClusterNode) and obj.name == self.name
@@ -1133,9 +1135,8 @@ def get_node_from_slot(self, slot, read_from_replicas=False,
11331135
if self.slots_cache.get(slot) is None or \
11341136
len(self.slots_cache[slot]) == 0:
11351137
raise SlotNotCoveredError(
1136-
'Slot "{}" not covered by the cluster. '
1137-
'"require_full_coverage={}"'.format(
1138-
slot, self._require_full_coverage)
1138+
f'Slot "{slot}" not covered by the cluster. '
1139+
f'"require_full_coverage={self._require_full_coverage}"'
11391140
)
11401141

11411142
if read_from_replicas is True:
@@ -1194,7 +1195,7 @@ def node_require_full_coverage(node):
11941195
except Exception as e:
11951196
raise RedisClusterException(
11961197
'ERROR sending "config get cluster-require-full-coverage"'
1197-
' command to redis server: {}, {}'.format(node.name, e)
1198+
f' command to redis server: {node.name}, {e}'
11981199
)
11991200

12001201
# at least one node should have cluster-require-full-coverage yes
@@ -1267,7 +1268,7 @@ def initialize(self):
12671268
msg = e.__str__
12681269
log.exception('An exception occurred while trying to'
12691270
' initialize the cluster using the seed node'
1270-
' {}:\n{}'.format(startup_node.name, msg))
1271+
f' {startup_node.name}:\n{msg}')
12711272
continue
12721273
except ResponseError as e:
12731274
log.exception(
@@ -1281,15 +1282,13 @@ def initialize(self):
12811282
else:
12821283
raise RedisClusterException(
12831284
'ERROR sending "cluster slots" command to redis '
1284-
'server: {}. error: {}'.format(
1285-
startup_node, message)
1285+
f'server: {startup_node}. error: {message}'
12861286
)
12871287
except Exception as e:
12881288
message = e.__str__()
12891289
raise RedisClusterException(
12901290
'ERROR sending "cluster slots" command to redis '
1291-
'server: {}. error: {}'.format(
1292-
startup_node, message)
1291+
f'server: {startup_node}. error: {message}'
12931292
)
12941293

12951294
# CLUSTER SLOTS command results in the following output:
@@ -1340,17 +1339,16 @@ def initialize(self):
13401339
else:
13411340
# Validate that 2 nodes want to use the same slot cache
13421341
# setup
1343-
if tmp_slots[i][0].name != target_node.name:
1342+
tmp_slot = tmp_slots[i][0]
1343+
if tmp_slot.name != target_node.name:
13441344
disagreements.append(
1345-
'{} vs {} on slot: {}'.format(
1346-
tmp_slots[i][0].name, target_node.name, i)
1345+
f'{tmp_slot.name} vs {target_node.name} on slot: {i}'
13471346
)
13481347

13491348
if len(disagreements) > 5:
13501349
raise RedisClusterException(
1351-
'startup_nodes could not agree on a valid'
1352-
' slots cache: {}'.format(
1353-
", ".join(disagreements))
1350+
f'startup_nodes could not agree on a valid '
1351+
f'slots cache: {", ".join(disagreements)}'
13541352
)
13551353

13561354
if not startup_nodes_reachable:
@@ -1368,9 +1366,8 @@ def initialize(self):
13681366
# Despite the requirement that the slots be covered, there
13691367
# isn't a full coverage
13701368
raise RedisClusterException(
1371-
'All slots are not covered after query all startup_nodes.'
1372-
' {} of {} covered...'.format(
1373-
len(self.slots_cache), REDIS_CLUSTER_HASH_SLOTS)
1369+
f'All slots are not covered after query all startup_nodes. '
1370+
f'{len(self.slots_cache)} of {REDIS_CLUSTER_HASH_SLOTS} covered...'
13741371
)
13751372
elif not fully_covered and not self._require_full_coverage:
13761373
# The user set require_full_coverage to False.
@@ -1387,8 +1384,7 @@ def initialize(self):
13871384
'cluster-require-full-coverage configuration to no on '
13881385
'all of the cluster nodes if you wish the cluster to '
13891386
'be able to serve without being fully covered.'
1390-
' {} of {} covered...'.format(
1391-
len(self.slots_cache), REDIS_CLUSTER_HASH_SLOTS)
1387+
f'{len(self.slots_cache)} of {REDIS_CLUSTER_HASH_SLOTS} covered...'
13921388
)
13931389

13941390
# Set the tmp variables to the real variables
@@ -1642,8 +1638,10 @@ def annotate_exception(self, exception, number, command):
16421638
Provides extra context to the exception prior to it being handled
16431639
"""
16441640
cmd = ' '.join(map(safe_str, command))
1645-
msg = 'Command # %d (%s) of pipeline caused error: %s' % (
1646-
number, cmd, exception.args[0])
1641+
msg = (
1642+
f'Command # {number} ({cmd}) of pipeline '
1643+
f'caused error: {exception.args[0]}'
1644+
)
16471645
exception.args = (msg,) + exception.args[1:]
16481646

16491647
def execute(self, raise_on_error=True):
@@ -1832,12 +1830,12 @@ def _send_cluster_commands(self, stack,
18321830
# If a lot of commands have failed, we'll be setting the
18331831
# flag to rebuild the slots table from scratch.
18341832
# So MOVED errors should correct themselves fairly quickly.
1835-
msg = 'An exception occurred during pipeline execution. ' \
1836-
'args: {0}, error: {1} {2}'.\
1837-
format(attempt[-1].args,
1838-
type(attempt[-1].result).__name__,
1839-
str(attempt[-1].result))
1840-
log.exception(msg)
1833+
log.exception(
1834+
f'An exception occurred during pipeline execution. '
1835+
f'args: {attempt[-1].args}, '
1836+
f'error: {type(attempt[-1].result).__name__} '
1837+
f'{str(attempt[-1].result)}'
1838+
)
18411839
self.reinitialize_counter += 1
18421840
if self._should_reinitialized():
18431841
self.nodes_manager.initialize()
@@ -1929,8 +1927,8 @@ def block_pipeline_command(func):
19291927

19301928
def inner(*args, **kwargs):
19311929
raise RedisClusterException(
1932-
"ERROR: Calling pipelined function {} is blocked when "
1933-
"running redis in cluster mode...".format(func.__name__))
1930+
f"ERROR: Calling pipelined function {func.__name__} is blocked when "
1931+
f"running redis in cluster mode...")
19341932

19351933
return inner
19361934

redis/commands/cluster.py

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -638,11 +638,10 @@ def stralgo(self, algo, value1, value2, specific_argument='strings',
638638
# check validity
639639
supported_algo = ['LCS']
640640
if algo not in supported_algo:
641-
raise DataError("The supported algorithms are: %s"
642-
% (', '.join(supported_algo)))
641+
supported_algos_str = ', '.join(supported_algo)
642+
raise DataError(f"The supported algorithms are: {supported_algos_str}")
643643
if specific_argument not in ['keys', 'strings']:
644-
raise DataError("specific_argument can be only"
645-
" keys or strings")
644+
raise DataError("specific_argument can be only keys or strings")
646645
if len and idx:
647646
raise DataError("len and idx cannot be provided together.")
648647

redis/commands/core.py

Lines changed: 17 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -227,8 +227,8 @@ def acl_setuser(self, username, enabled=False, nopass=False,
227227
elif password.startswith(b'-'):
228228
pieces.append(b'<%s' % password[1:])
229229
else:
230-
raise DataError('Password %d must be prefixeed with a '
231-
'"+" to add or a "-" to remove' % i)
230+
raise DataError(f'Password {i} must be prefixed with a '
231+
f'"+" to add or a "-" to remove')
232232

233233
if hashed_passwords:
234234
# as most users will have only one password, allow remove_passwords
@@ -241,8 +241,8 @@ def acl_setuser(self, username, enabled=False, nopass=False,
241241
elif hashed_password.startswith(b'-'):
242242
pieces.append(b'!%s' % hashed_password[1:])
243243
else:
244-
raise DataError('Hashed %d password must be prefixeed '
245-
'with a "+" to add or a "-" to remove' % i)
244+
raise DataError(f'Hashed password {i} must be prefixed with a '
245+
f'"+" to add or a "-" to remove')
246246

247247
if nopass:
248248
pieces.append(b'nopass')
@@ -260,16 +260,18 @@ def acl_setuser(self, username, enabled=False, nopass=False,
260260
elif category.startswith(b'-'):
261261
pieces.append(b'-@%s' % category[1:])
262262
else:
263-
raise DataError('Category "%s" must be prefixed with '
264-
'"+" or "-"'
265-
% encoder.decode(category, force=True))
263+
raise DataError(
264+
f'Category "{encoder.decode(category, force=True)}" '
265+
'must be prefixed with "+" or "-"'
266+
)
266267
if commands:
267268
for cmd in commands:
268269
cmd = encoder.encode(cmd)
269270
if not cmd.startswith(b'+') and not cmd.startswith(b'-'):
270-
raise DataError('Command "%s" must be prefixed with '
271-
'"+" or "-"'
272-
% encoder.decode(cmd, force=True))
271+
raise DataError(
272+
f'Command "{encoder.decode(cmd, force=True)}" '
273+
'must be prefixed with "+" or "-"'
274+
)
273275
pieces.append(cmd)
274276

275277
if keys:
@@ -1552,11 +1554,10 @@ def stralgo(self, algo, value1, value2, specific_argument='strings',
15521554
# check validity
15531555
supported_algo = ['LCS']
15541556
if algo not in supported_algo:
1555-
raise DataError("The supported algorithms are: %s"
1556-
% (', '.join(supported_algo)))
1557+
supported_algos_str = ', '.join(supported_algo)
1558+
raise DataError(f"The supported algorithms are: {supported_algos_str}")
15571559
if specific_argument not in ['keys', 'strings']:
1558-
raise DataError("specific_argument can be only"
1559-
" keys or strings")
1560+
raise DataError("specific_argument can be only keys or strings")
15601561
if len and idx:
15611562
raise DataError("len and idx cannot be provided together.")
15621563

@@ -3464,8 +3465,8 @@ def hmset(self, name, mapping):
34643465
For more information check https://redis.io/commands/hmset
34653466
"""
34663467
warnings.warn(
3467-
'%s.hmset() is deprecated. Use %s.hset() instead.'
3468-
% (self.__class__.__name__, self.__class__.__name__),
3468+
f'{self.__class__.__name__}.hmset() is deprecated. '
3469+
f'Use {self.__class__.__name__}.hset() instead.',
34693470
DeprecationWarning,
34703471
stacklevel=2,
34713472
)

redis/commands/parser.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -46,8 +46,9 @@ def get_keys(self, redis_conn, *args):
4646
# version has changed, the commands may not be current
4747
self.initialize(redis_conn)
4848
if cmd_name not in self.commands:
49-
raise RedisError("{} command doesn't exist in Redis "
50-
"commands".format(cmd_name.upper()))
49+
raise RedisError(
50+
f"{cmd_name.upper()} command doesn't exist in Redis commands"
51+
)
5152

5253
command = self.commands.get(cmd_name)
5354
if 'movablekeys' in command['flags']:

redis/commands/search/aggregation.py

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -392,9 +392,8 @@ def __init__(self, rows, cursor, schema):
392392
self.schema = schema
393393

394394
def __repr__(self):
395-
return "<{} at 0x{:x} Rows={}, Cursor={}>".format(
396-
self.__class__.__name__,
397-
id(self),
398-
len(self.rows),
399-
self.cursor.cid if self.cursor else -1,
395+
cid = self.cursor.cid if self.cursor else -1
396+
return (
397+
f"<{self.__class__.__name__} at 0x{id(self):x} "
398+
f"Rows={len(self.rows)}, Cursor={cid}>"
400399
)

redis/commands/search/result.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -70,4 +70,4 @@ def __init__(
7070
self.docs.append(doc)
7171

7272
def __repr__(self):
73-
return "Result{%d total, docs: %s}" % (self.total, self.docs)
73+
return f"Result{{{self.total} total, docs: {self.docs}}}"

0 commit comments

Comments
 (0)