Skip to content

Commit 2c8add6

Browse files
chore(internal): enable more lint rules (#945)
1 parent 5290639 commit 2c8add6

14 files changed

+61
-32
lines changed

pyproject.toml

+20-11
Original file line numberDiff line numberDiff line change
@@ -47,17 +47,18 @@ openai = "openai.cli:main"
4747

4848
[tool.rye]
4949
managed = true
50+
# version pins are in requirements-dev.lock
5051
dev-dependencies = [
51-
"pyright==1.1.332",
52-
"mypy==1.7.1",
53-
"black==23.3.0",
54-
"respx==0.20.2",
55-
"pytest==7.1.1",
56-
"pytest-asyncio==0.21.1",
57-
"ruff==0.0.282",
58-
"isort==5.10.1",
59-
"time-machine==2.9.0",
60-
"nox==2023.4.22",
52+
"pyright",
53+
"mypy",
54+
"black",
55+
"respx",
56+
"pytest",
57+
"pytest-asyncio",
58+
"ruff",
59+
"isort",
60+
"time-machine",
61+
"nox",
6162
"dirty-equals>=0.6.0",
6263
"azure-identity >=1.14.1",
6364
"types-tqdm > 4"
@@ -135,9 +136,11 @@ extra_standard_library = ["typing_extensions"]
135136

136137
[tool.ruff]
137138
line-length = 120
138-
format = "grouped"
139+
output-format = "grouped"
139140
target-version = "py37"
140141
select = [
142+
# bugbear rules
143+
"B",
141144
# remove unused imports
142145
"F401",
143146
# bare except statements
@@ -148,6 +151,12 @@ select = [
148151
"T201",
149152
"T203",
150153
]
154+
ignore = [
155+
# lru_cache in methods, will be fixed separately
156+
"B019",
157+
# mutable defaults
158+
"B006",
159+
]
151160
unfixable = [
152161
# disable auto fix for print statements
153162
"T201",

requirements-dev.lock

+17-1
Original file line numberDiff line numberDiff line change
@@ -11,11 +11,15 @@ annotated-types==0.6.0
1111
anyio==4.1.0
1212
argcomplete==3.1.2
1313
attrs==23.1.0
14+
azure-core==1.29.5
1415
azure-identity==1.15.0
1516
black==23.3.0
1617
certifi==2023.7.22
18+
cffi==1.16.0
19+
charset-normalizer==3.3.2
1720
click==8.1.7
1821
colorlog==6.7.0
22+
cryptography==41.0.7
1923
dirty-equals==0.6.0
2024
distlib==0.3.7
2125
distro==1.8.0
@@ -27,31 +31,43 @@ httpx==0.25.2
2731
idna==3.4
2832
iniconfig==2.0.0
2933
isort==5.10.1
34+
msal==1.26.0
35+
msal-extensions==1.0.0
3036
mypy==1.7.1
3137
mypy-extensions==1.0.0
3238
nodeenv==1.8.0
3339
nox==2023.4.22
40+
numpy==1.26.2
3441
packaging==23.2
42+
pandas==2.1.3
43+
pandas-stubs==2.1.1.230928
3544
pathspec==0.11.2
3645
platformdirs==3.11.0
3746
pluggy==1.3.0
47+
portalocker==2.8.2
3848
py==1.11.0
49+
pycparser==2.21
3950
pydantic==2.4.2
4051
pydantic-core==2.10.1
52+
pyjwt==2.8.0
4153
pyright==1.1.332
4254
pytest==7.1.1
4355
pytest-asyncio==0.21.1
4456
python-dateutil==2.8.2
4557
pytz==2023.3.post1
58+
requests==2.31.0
4659
respx==0.20.2
47-
ruff==0.0.282
60+
ruff==0.1.7
4861
six==1.16.0
4962
sniffio==1.3.0
5063
time-machine==2.9.0
5164
tomli==2.0.1
5265
tqdm==4.66.1
66+
types-pytz==2023.3.1.1
5367
types-tqdm==4.66.0.2
5468
typing-extensions==4.8.0
69+
tzdata==2023.3
70+
urllib3==2.1.0
5571
virtualenv==20.24.5
5672
# The following packages are considered to be unsafe in a requirements file:
5773
setuptools==68.2.2

src/openai/__init__.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -86,7 +86,7 @@
8686
for __name in __all__:
8787
if not __name.startswith("__"):
8888
try:
89-
setattr(__locals[__name], "__module__", "openai")
89+
__locals[__name].__module__ = "openai"
9090
except (TypeError, AttributeError):
9191
# Some of our exported symbols are builtins which we can't set attributes for.
9292
pass

src/openai/_extras/numpy_proxy.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -20,8 +20,8 @@ class NumpyProxy(LazyProxy[Any]):
2020
def __load__(self) -> Any:
2121
try:
2222
import numpy
23-
except ImportError:
24-
raise MissingDependencyError(NUMPY_INSTRUCTIONS)
23+
except ImportError as err:
24+
raise MissingDependencyError(NUMPY_INSTRUCTIONS) from err
2525

2626
return numpy
2727

src/openai/_extras/pandas_proxy.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -20,8 +20,8 @@ class PandasProxy(LazyProxy[Any]):
2020
def __load__(self) -> Any:
2121
try:
2222
import pandas
23-
except ImportError:
24-
raise MissingDependencyError(PANDAS_INSTRUCTIONS)
23+
except ImportError as err:
24+
raise MissingDependencyError(PANDAS_INSTRUCTIONS) from err
2525

2626
return pandas
2727

src/openai/_streaming.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -65,7 +65,7 @@ def __stream__(self) -> Iterator[ResponseT]:
6565
yield process_data(data=data, cast_to=cast_to, response=response)
6666

6767
# Ensure the entire stream is consumed
68-
for sse in iterator:
68+
for _sse in iterator:
6969
...
7070

7171

@@ -120,7 +120,7 @@ async def __stream__(self) -> AsyncIterator[ResponseT]:
120120
yield process_data(data=data, cast_to=cast_to, response=response)
121121

122122
# Ensure the entire stream is consumed
123-
async for sse in iterator:
123+
async for _sse in iterator:
124124
...
125125

126126

src/openai/_types.py

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

4545

4646
class BinaryResponseContent(ABC):
47+
@abstractmethod
4748
def __init__(
4849
self,
4950
response: Any,

src/openai/_utils/_utils.py

+5-3
Original file line numberDiff line numberDiff line change
@@ -194,8 +194,8 @@ def extract_type_arg(typ: type, index: int) -> type:
194194
args = get_args(typ)
195195
try:
196196
return cast(type, args[index])
197-
except IndexError:
198-
raise RuntimeError(f"Expected type {typ} to have a type argument at index {index} but it did not")
197+
except IndexError as err:
198+
raise RuntimeError(f"Expected type {typ} to have a type argument at index {index} but it did not") from err
199199

200200

201201
def deepcopy_minimal(item: _T) -> _T:
@@ -275,7 +275,9 @@ def wrapper(*args: object, **kwargs: object) -> object:
275275
try:
276276
given_params.add(positional[i])
277277
except IndexError:
278-
raise TypeError(f"{func.__name__}() takes {len(positional)} argument(s) but {len(args)} were given")
278+
raise TypeError(
279+
f"{func.__name__}() takes {len(positional)} argument(s) but {len(args)} were given"
280+
) from None
279281

280282
for key in kwargs.keys():
281283
given_params.add(key)

src/openai/cli/_progress.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@ def read(self, n: int | None = -1) -> bytes:
3535
try:
3636
self._callback(self._progress)
3737
except Exception as e: # catches exception from the callback
38-
raise CancelledError("The upload was cancelled: {}".format(e))
38+
raise CancelledError("The upload was cancelled: {}".format(e)) from e
3939

4040
return chunk
4141

src/openai/cli/_tools/migrate.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,7 @@ def grit(args: GritArgs) -> None:
4141
except subprocess.CalledProcessError:
4242
# stdout and stderr are forwarded by subprocess so an error will already
4343
# have been displayed
44-
raise SilentCLIError()
44+
raise SilentCLIError() from None
4545

4646

4747
class MigrateArgs(BaseModel):
@@ -57,7 +57,7 @@ def migrate(args: MigrateArgs) -> None:
5757
except subprocess.CalledProcessError:
5858
# stdout and stderr are forwarded by subprocess so an error will already
5959
# have been displayed
60-
raise SilentCLIError()
60+
raise SilentCLIError() from None
6161

6262

6363
# handles downloading the Grit CLI until they provide their own PyPi package

tests/test_client.py

+3-2
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@
1919
from openai._models import BaseModel, FinalRequestOptions
2020
from openai._streaming import Stream, AsyncStream
2121
from openai._exceptions import (
22+
OpenAIError,
2223
APIStatusError,
2324
APITimeoutError,
2425
APIConnectionError,
@@ -269,7 +270,7 @@ def test_validate_headers(self) -> None:
269270
request = client._build_request(FinalRequestOptions(method="get", url="/foo"))
270271
assert request.headers.get("Authorization") == f"Bearer {api_key}"
271272

272-
with pytest.raises(Exception):
273+
with pytest.raises(OpenAIError):
273274
client2 = OpenAI(base_url=base_url, api_key=None, _strict_response_validation=True)
274275
_ = client2
275276

@@ -934,7 +935,7 @@ def test_validate_headers(self) -> None:
934935
request = client._build_request(FinalRequestOptions(method="get", url="/foo"))
935936
assert request.headers.get("Authorization") == f"Bearer {api_key}"
936937

937-
with pytest.raises(Exception):
938+
with pytest.raises(OpenAIError):
938939
client2 = AsyncOpenAI(base_url=base_url, api_key=None, _strict_response_validation=True)
939940
_ = client2
940941

tests/test_module_client.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -129,7 +129,7 @@ def test_azure_api_key_env_without_api_version() -> None:
129129
ValueError,
130130
match=r"Must provide either the `api_version` argument or the `OPENAI_API_VERSION` environment variable",
131131
):
132-
openai.completions._client
132+
openai.completions._client # noqa: B018
133133

134134

135135
def test_azure_api_key_and_version_env() -> None:
@@ -142,7 +142,7 @@ def test_azure_api_key_and_version_env() -> None:
142142
ValueError,
143143
match=r"Must provide one of the `base_url` or `azure_endpoint` arguments, or the `AZURE_OPENAI_ENDPOINT` environment variable",
144144
):
145-
openai.completions._client
145+
openai.completions._client # noqa: B018
146146

147147

148148
def test_azure_api_key_version_and_endpoint_env() -> None:
@@ -152,7 +152,7 @@ def test_azure_api_key_version_and_endpoint_env() -> None:
152152
_os.environ["OPENAI_API_VERSION"] = "example-version"
153153
_os.environ["AZURE_OPENAI_ENDPOINT"] = "https://www.example"
154154

155-
openai.completions._client
155+
openai.completions._client # noqa: B018
156156

157157
assert openai.api_type == "azure"
158158

tests/test_utils/test_proxy.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -19,5 +19,5 @@ def test_recursive_proxy() -> None:
1919
assert repr(proxy) == "RecursiveLazyProxy"
2020
assert str(proxy) == "RecursiveLazyProxy"
2121
assert dir(proxy) == []
22-
assert getattr(type(proxy), "__name__") == "RecursiveLazyProxy"
22+
assert type(proxy).__name__ == "RecursiveLazyProxy"
2323
assert type(operator.attrgetter("name.foo.bar.baz")(proxy)).__name__ == "RecursiveLazyProxy"

tests/utils.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -91,7 +91,7 @@ def assert_matches_type(
9191
traceback.print_exc()
9292
continue
9393

94-
assert False, "Did not match any variants"
94+
raise AssertionError("Did not match any variants")
9595
elif issubclass(origin, BaseModel):
9696
assert isinstance(value, type_)
9797
assert assert_matches_model(type_, cast(Any, value), path=path)

0 commit comments

Comments
 (0)