Skip to content

Commit 4122f7c

Browse files
authored
Replace flake8+isort+black with ruff (#3147)
* Replace flake8 + isort + flynt with ruff * Replace black with `ruff format`; run it
1 parent 5891109 commit 4122f7c

36 files changed

+123
-120
lines changed

.flake8

-28
This file was deleted.

.isort.cfg

-5
This file was deleted.

benchmarks/basic_operations.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,7 @@ def wrapper(*args, **kwargs):
5454
count = args[1]
5555
print(f"{func.__name__} - {count} Requests")
5656
print(f"Duration = {duration}")
57-
print(f"Rate = {count/duration}")
57+
print(f"Rate = {count / duration}")
5858
print()
5959
return ret
6060

benchmarks/command_packer_benchmark.py

-1
Original file line numberDiff line numberDiff line change
@@ -78,7 +78,6 @@ def pack_command(self, *args):
7878

7979

8080
class CommandPackerBenchmark(Benchmark):
81-
8281
ARGUMENTS = (
8382
{
8483
"name": "connection_class",

benchmarks/socket_read_size.py

-1
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,6 @@
44

55

66
class SocketReadBenchmark(Benchmark):
7-
87
ARGUMENTS = (
98
{"name": "parser", "values": [PythonParser, _HiredisParser]},
109
{

dev_requirements.txt

+1-4
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,5 @@
11
build
2-
black==24.3.0
32
click==8.0.4
4-
flake8-isort
5-
flake8
6-
flynt~=0.69.0
73
invoke==2.2.0
84
mock
95
packaging>=20.4
@@ -12,6 +8,7 @@ pytest-asyncio>=0.23.0,<0.24.0
128
pytest-cov
139
pytest-profiling==1.8.1
1410
pytest-timeout
11+
ruff==0.9.6
1512
ujson>=4.2.0
1613
uvloop
1714
vulture>=2.3.0

doctests/README.md

+2-2
Original file line numberDiff line numberDiff line change
@@ -21,8 +21,8 @@ pip uninstall -y redis # uninstall Redis package installed via redis-entraid
2121
pip install -r doctests/requirements.txt
2222
```
2323

24-
Note - the CI process, runs the basic ```black``` and ```isort``` linters against the examples. Assuming
25-
the requirements above have been installed you can run ```black yourfile.py``` and ```isort yourfile.py```
24+
Note - the CI process, runs linters against the examples. Assuming
25+
the requirements above have been installed you can run ```ruff check yourfile.py``` and ```ruff format yourfile.py```
2626
locally to validate the linting, prior to CI.
2727

2828
Just include necessary assertions in the example file and run

pyproject.toml

+50
Original file line numberDiff line numberDiff line change
@@ -96,3 +96,53 @@ filterwarnings = [
9696
# Ignore a coverage warning when COVERAGE_CORE=sysmon for Pythons < 3.12.
9797
"ignore:sys.monitoring isn't available:coverage.exceptions.CoverageWarning",
9898
]
99+
100+
[tool.ruff]
101+
target-version = "py38"
102+
line-length = 88
103+
exclude = [
104+
"*.egg-info",
105+
"*.pyc",
106+
".git",
107+
".venv*",
108+
"build",
109+
"dist",
110+
"docker",
111+
"docs/*",
112+
"doctests/*",
113+
"tasks.py",
114+
"venv*",
115+
"whitelist.py",
116+
]
117+
118+
[tool.ruff.lint]
119+
ignore = [
120+
"E501", # line too long (taken care of with ruff format)
121+
"E741", # ambiguous variable name
122+
"N818", # Errors should have Error suffix
123+
]
124+
125+
select = [
126+
"E",
127+
"F",
128+
"FLY",
129+
"I",
130+
"N",
131+
"W",
132+
]
133+
134+
[tool.ruff.lint.per-file-ignores]
135+
"redis/commands/bf/*" = [
136+
# the `bf` module uses star imports, so this is required there.
137+
"F405", # name may be undefined, or defined from star imports
138+
]
139+
"redis/commands/{bf,timeseries,json,search}/*" = [
140+
"N",
141+
]
142+
"tests/*" = [
143+
"I", # TODO: could be enabled, plenty of changes
144+
"N801", # class name should use CapWords convention
145+
"N803", # argument name should be lowercase
146+
"N802", # function name should be lowercase
147+
"N806", # variable name should be lowercase
148+
]

redis/_parsers/base.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -32,9 +32,9 @@
3232
from .encoders import Encoder
3333
from .socket import SERVER_CLOSED_CONNECTION_ERROR, SocketBuffer
3434

35-
MODULE_LOAD_ERROR = "Error loading the extension. " "Please check the server logs."
35+
MODULE_LOAD_ERROR = "Error loading the extension. Please check the server logs."
3636
NO_SUCH_MODULE_ERROR = "Error unloading module: no such module with that name"
37-
MODULE_UNLOAD_NOT_POSSIBLE_ERROR = "Error unloading module: operation not " "possible."
37+
MODULE_UNLOAD_NOT_POSSIBLE_ERROR = "Error unloading module: operation not possible."
3838
MODULE_EXPORTS_DATA_TYPES_ERROR = (
3939
"Error unloading module: the module "
4040
"exports one or more module-side data "

redis/asyncio/cluster.py

+2-4
Original file line numberDiff line numberDiff line change
@@ -1154,9 +1154,7 @@ def get_node(
11541154
return self.nodes_cache.get(node_name)
11551155
else:
11561156
raise DataError(
1157-
"get_node requires one of the following: "
1158-
"1. node name "
1159-
"2. host and port"
1157+
"get_node requires one of the following: 1. node name 2. host and port"
11601158
)
11611159

11621160
def set_nodes(
@@ -1338,7 +1336,7 @@ async def initialize(self) -> None:
13381336
if len(disagreements) > 5:
13391337
raise RedisClusterException(
13401338
f"startup_nodes could not agree on a valid "
1341-
f'slots cache: {", ".join(disagreements)}'
1339+
f"slots cache: {', '.join(disagreements)}"
13421340
)
13431341

13441342
# Validate if all slots are covered or if we should try next startup node

redis/asyncio/connection.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -842,7 +842,7 @@ def __init__(
842842
if cert_reqs is None:
843843
self.cert_reqs = ssl.CERT_NONE
844844
elif isinstance(cert_reqs, str):
845-
CERT_REQS = {
845+
CERT_REQS = { # noqa: N806
846846
"none": ssl.CERT_NONE,
847847
"optional": ssl.CERT_OPTIONAL,
848848
"required": ssl.CERT_REQUIRED,

redis/asyncio/utils.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ def from_url(url, **kwargs):
1616
return Redis.from_url(url, **kwargs)
1717

1818

19-
class pipeline:
19+
class pipeline: # noqa: N801
2020
def __init__(self, redis_obj: "Redis"):
2121
self.p: "Pipeline" = redis_obj.pipeline()
2222

redis/auth/token.py

-1
Original file line numberDiff line numberDiff line change
@@ -76,7 +76,6 @@ def get_received_at_ms(self) -> float:
7676

7777

7878
class JWToken(TokenInterface):
79-
8079
REQUIRED_FIELDS = {"exp"}
8180

8281
def __init__(self, token: str):

redis/client.py

+1-2
Original file line numberDiff line numberDiff line change
@@ -1514,8 +1514,7 @@ def raise_first_error(self, commands, response):
15141514
def annotate_exception(self, exception, number, command):
15151515
cmd = " ".join(map(safe_str, command))
15161516
msg = (
1517-
f"Command # {number} ({cmd}) of pipeline "
1518-
f"caused error: {exception.args[0]}"
1517+
f"Command # {number} ({cmd}) of pipeline caused error: {exception.args[0]}"
15191518
)
15201519
exception.args = (msg,) + exception.args[1:]
15211520

redis/cluster.py

+2-3
Original file line numberDiff line numberDiff line change
@@ -1628,7 +1628,7 @@ def initialize(self):
16281628
if len(disagreements) > 5:
16291629
raise RedisClusterException(
16301630
f"startup_nodes could not agree on a valid "
1631-
f'slots cache: {", ".join(disagreements)}'
1631+
f"slots cache: {', '.join(disagreements)}"
16321632
)
16331633

16341634
fully_covered = self.check_slots_coverage(tmp_slots)
@@ -2047,8 +2047,7 @@ def annotate_exception(self, exception, number, command):
20472047
"""
20482048
cmd = " ".join(map(safe_str, command))
20492049
msg = (
2050-
f"Command # {number} ({cmd}) of pipeline "
2051-
f"caused error: {exception.args[0]}"
2050+
f"Command # {number} ({cmd}) of pipeline caused error: {exception.args[0]}"
20522051
)
20532052
exception.args = (msg,) + exception.args[1:]
20542053

redis/commands/cluster.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -595,7 +595,7 @@ def cluster_setslot(
595595
"CLUSTER SETSLOT", slot_id, state, node_id, target_nodes=target_node
596596
)
597597
elif state.upper() == "STABLE":
598-
raise RedisError('For "stable" state please use ' "cluster_setslot_stable")
598+
raise RedisError('For "stable" state please use cluster_setslot_stable')
599599
else:
600600
raise RedisError(f"Invalid slot state: {state}")
601601

redis/commands/core.py

+4-3
Original file line numberDiff line numberDiff line change
@@ -3415,7 +3415,9 @@ def smembers(self, name: str) -> Union[Awaitable[Set], Set]:
34153415
"""
34163416
return self.execute_command("SMEMBERS", name, keys=[name])
34173417

3418-
def smismember(self, name: str, values: List, *args: List) -> Union[
3418+
def smismember(
3419+
self, name: str, values: List, *args: List
3420+
) -> Union[
34193421
Awaitable[List[Union[Literal[0], Literal[1]]]],
34203422
List[Union[Literal[0], Literal[1]]],
34213423
]:
@@ -4162,8 +4164,7 @@ def zadd(
41624164
raise DataError("ZADD allows either 'gt' or 'lt', not both")
41634165
if incr and len(mapping) != 1:
41644166
raise DataError(
4165-
"ZADD option 'incr' only works when passing a "
4166-
"single element/score pair"
4167+
"ZADD option 'incr' only works when passing a single element/score pair"
41674168
)
41684169
if nx and (gt or lt):
41694170
raise DataError("Only one of 'nx', 'lt', or 'gr' may be defined.")

redis/commands/graph/commands.py

+1-3
Original file line numberDiff line numberDiff line change
@@ -171,9 +171,7 @@ def config(self, name, value=None, set=False):
171171
if set:
172172
params.append(value)
173173
else:
174-
raise DataError(
175-
"``value`` can be provided only when ``set`` is True"
176-
) # noqa
174+
raise DataError("``value`` can be provided only when ``set`` is True") # noqa
177175
return self.execute_command(CONFIG_CMD, *params)
178176

179177
def list_keys(self):

redis/commands/helpers.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -138,9 +138,9 @@ def stringify_param_value(value):
138138
elif value is None:
139139
return "null"
140140
elif isinstance(value, (list, tuple)):
141-
return f'[{",".join(map(stringify_param_value, value))}]'
141+
return f"[{','.join(map(stringify_param_value, value))}]"
142142
elif isinstance(value, dict):
143-
return f'{{{",".join(f"{k}:{stringify_param_value(v)}" for k, v in value.items())}}}' # noqa
143+
return f"{{{','.join(f'{k}:{stringify_param_value(v)}' for k, v in value.items())}}}" # noqa
144144
else:
145145
return str(value)
146146

redis/connection.py

+2-4
Original file line numberDiff line numberDiff line change
@@ -622,9 +622,7 @@ def read_response(
622622
except OSError as e:
623623
if disconnect_on_error:
624624
self.disconnect()
625-
raise ConnectionError(
626-
f"Error while reading from {host_error}" f" : {e.args}"
627-
)
625+
raise ConnectionError(f"Error while reading from {host_error} : {e.args}")
628626
except BaseException:
629627
# Also by default close in case of BaseException. A lot of code
630628
# relies on this behaviour when doing Command/Response pairs.
@@ -1040,7 +1038,7 @@ def __init__(
10401038
if ssl_cert_reqs is None:
10411039
ssl_cert_reqs = ssl.CERT_NONE
10421040
elif isinstance(ssl_cert_reqs, str):
1043-
CERT_REQS = {
1041+
CERT_REQS = { # noqa: N806
10441042
"none": ssl.CERT_NONE,
10451043
"optional": ssl.CERT_OPTIONAL,
10461044
"required": ssl.CERT_REQUIRED,

redis/exceptions.py

+3
Original file line numberDiff line numberDiff line change
@@ -79,6 +79,7 @@ class ModuleError(ResponseError):
7979

8080
class LockError(RedisError, ValueError):
8181
"Errors acquiring or releasing a lock"
82+
8283
# NOTE: For backwards compatibility, this class derives from ValueError.
8384
# This was originally chosen to behave like threading.Lock.
8485

@@ -89,11 +90,13 @@ def __init__(self, message=None, lock_name=None):
8990

9091
class LockNotOwnedError(LockError):
9192
"Error trying to extend or release a lock that is (no longer) owned"
93+
9294
pass
9395

9496

9597
class ChildDeadlockedError(Exception):
9698
"Error indicating that a child process is deadlocked after a fork()"
99+
97100
pass
98101

99102

redis/ocsp.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
from cryptography.hazmat.primitives.hashes import SHA1, Hash
1616
from cryptography.hazmat.primitives.serialization import Encoding, PublicFormat
1717
from cryptography.x509 import ocsp
18+
1819
from redis.exceptions import AuthorizationError, ConnectionError
1920

2021

@@ -56,7 +57,7 @@ def _check_certificate(issuer_cert, ocsp_bytes, validate=True):
5657
if ocsp_response.response_status == ocsp.OCSPResponseStatus.SUCCESSFUL:
5758
if ocsp_response.certificate_status != ocsp.OCSPCertStatus.GOOD:
5859
raise ConnectionError(
59-
f'Received an {str(ocsp_response.certificate_status).split(".")[1]} '
60+
f"Received an {str(ocsp_response.certificate_status).split('.')[1]} "
6061
"ocsp certificate status"
6162
)
6263
else:

redis/sentinel.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -273,7 +273,7 @@ def __repr__(self):
273273
)
274274
return (
275275
f"<{type(self).__module__}.{type(self).__name__}"
276-
f'(sentinels=[{",".join(sentinel_addresses)}])>'
276+
f"(sentinels=[{','.join(sentinel_addresses)}])>"
277277
)
278278

279279
def check_master_state(self, state, service_name):

tasks.py

+2-4
Original file line numberDiff line numberDiff line change
@@ -27,11 +27,9 @@ def build_docs(c):
2727
@task
2828
def linters(c):
2929
"""Run code linters"""
30-
run("flake8 tests redis")
31-
run("black --target-version py37 --check --diff tests redis")
32-
run("isort --check-only --diff tests redis")
30+
run("ruff check tests redis")
31+
run("ruff format --check --diff tests redis")
3332
run("vulture redis whitelist.py --min-confidence 80")
34-
run("flynt --fail-on-change --dry-run tests redis")
3533

3634

3735
@task

tests/conftest.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -646,7 +646,7 @@ def wait_for_command(client, monitor, command, key=None):
646646
if Version(redis_version) >= Version("5.0.0"):
647647
id_str = str(client.client_id())
648648
else:
649-
id_str = f"{random.randrange(2 ** 32):08x}"
649+
id_str = f"{random.randrange(2**32):08x}"
650650
key = f"__REDIS-PY-{id_str}__"
651651
client.get(key)
652652
while True:

tests/test_asyncio/conftest.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -242,7 +242,7 @@ async def wait_for_command(
242242
if Version(redis_version) >= Version("5.0.0"):
243243
id_str = str(await client.client_id())
244244
else:
245-
id_str = f"{random.randrange(2 ** 32):08x}"
245+
id_str = f"{random.randrange(2**32):08x}"
246246
key = f"__REDIS-PY-{id_str}__"
247247
await client.get(key)
248248
while True:

0 commit comments

Comments
 (0)