Skip to content

Commit fbe87ac

Browse files
authored
Pyupgrade + flynt + f-strings (#1759)
@akx Thank you so much for this! Thanks again for introducing me to a new tool that I'm sliding into my workflow as well.
1 parent 4db85ef commit fbe87ac

36 files changed

+263
-306
lines changed

benchmarks/base.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -34,12 +34,12 @@ def run_benchmark(self):
3434
group_values = [group['values'] for group in self.ARGUMENTS]
3535
for value_set in itertools.product(*group_values):
3636
pairs = list(zip(group_names, value_set))
37-
arg_string = ', '.join(['%s=%s' % (p[0], p[1]) for p in pairs])
38-
sys.stdout.write('Benchmark: %s... ' % arg_string)
37+
arg_string = ', '.join(f'{p[0]}={p[1]}' for p in pairs)
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/basic_operations.py

+10-13
Original file line numberDiff line numberDiff line change
@@ -49,9 +49,9 @@ def wrapper(*args, **kwargs):
4949
count = kwargs['num']
5050
else:
5151
count = args[1]
52-
print('{} - {} Requests'.format(func.__name__, count))
53-
print('Duration = {}'.format(duration))
54-
print('Rate = {}'.format(count/duration))
52+
print(f'{func.__name__} - {count} Requests')
53+
print(f'Duration = {duration}')
54+
print(f'Rate = {count/duration}')
5555
print()
5656
return ret
5757
return wrapper
@@ -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:

benchmarks/command_packer_benchmark.py

+4-7
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
import socket
21
from redis.connection import (Connection, SYM_STAR, SYM_DOLLAR, SYM_EMPTY,
32
SYM_CRLF)
43
from base import Benchmark
@@ -11,14 +10,13 @@ def send_packed_command(self, command, check_health=True):
1110
self.connect()
1211
try:
1312
self._sock.sendall(command)
14-
except socket.error as e:
13+
except OSError as e:
1514
self.disconnect()
1615
if len(e.args) == 1:
1716
_errno, errmsg = 'UNKNOWN', e.args[0]
1817
else:
1918
_errno, errmsg = e.args
20-
raise ConnectionError("Error %s while writing to socket. %s." %
21-
(_errno, errmsg))
19+
raise ConnectionError(f"Error {_errno} while writing to socket. {errmsg}.")
2220
except Exception:
2321
self.disconnect()
2422
raise
@@ -43,14 +41,13 @@ def send_packed_command(self, command, check_health=True):
4341
command = [command]
4442
for item in command:
4543
self._sock.sendall(item)
46-
except socket.error as e:
44+
except OSError as e:
4745
self.disconnect()
4846
if len(e.args) == 1:
4947
_errno, errmsg = 'UNKNOWN', e.args[0]
5048
else:
5149
_errno, errmsg = e.args
52-
raise ConnectionError("Error %s while writing to socket. %s." %
53-
(_errno, errmsg))
50+
raise ConnectionError(f"Error {_errno} while writing to socket. {errmsg}.")
5451
except Exception:
5552
self.disconnect()
5653
raise

dev_requirements.txt

+1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
flake8>=3.9.2
2+
flynt~=0.69.0
23
pytest==6.2.5
34
pytest-timeout==2.0.1
45
tox==3.24.4

redis/client.py

+9-9
Original file line numberDiff line numberDiff line change
@@ -629,7 +629,7 @@ def parse_set_result(response, **options):
629629
return response and str_if_bytes(response) == 'OK'
630630

631631

632-
class Redis(RedisModuleCommands, CoreCommands, SentinelCommands, object):
632+
class Redis(RedisModuleCommands, CoreCommands, SentinelCommands):
633633
"""
634634
Implementation of the Redis protocol.
635635
@@ -918,7 +918,7 @@ def __init__(self, host='localhost', port=6379,
918918
self.__class__.RESPONSE_CALLBACKS)
919919

920920
def __repr__(self):
921-
return "%s<%s>" % (type(self).__name__, repr(self.connection_pool))
921+
return f"{type(self).__name__}<{repr(self.connection_pool)}>"
922922

923923
def set_response_callback(self, command, callback):
924924
"Set a custom Response Callback"
@@ -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,
@@ -1807,8 +1805,10 @@ def raise_first_error(self, commands, response):
18071805

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

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

0 commit comments

Comments
 (0)