Skip to content

Commit b9db010

Browse files
authored
Set line-length to 120 on Ruff (#2679)
* Set `line-length` to 120 on Ruff * Add links to selected rules * Remove empty strings * Fix more stuff
1 parent 72c2334 commit b9db010

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

53 files changed

+402
-1149
lines changed

pyproject.toml

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -50,9 +50,19 @@ Source = "https://github.com/encode/starlette"
5050
[tool.hatch.version]
5151
path = "starlette/__init__.py"
5252

53+
[tool.ruff]
54+
line-length = 120
55+
5356
[tool.ruff.lint]
54-
select = ["E", "F", "I", "FA", "UP"]
55-
ignore = ["UP031"]
57+
select = [
58+
"E", # https://docs.astral.sh/ruff/rules/#error-e
59+
"F", # https://docs.astral.sh/ruff/rules/#pyflakes-f
60+
"I", # https://docs.astral.sh/ruff/rules/#isort-i
61+
"FA", # https://docs.astral.sh/ruff/rules/#flake8-future-annotations-fa
62+
"UP", # https://docs.astral.sh/ruff/rules/#pyupgrade-up
63+
"RUF100", # https://docs.astral.sh/ruff/rules/#ruff-specific-rules-ruf
64+
]
65+
ignore = ["UP031"] # https://docs.astral.sh/ruff/rules/printf-string-formatting/
5666

5767
[tool.ruff.lint.isort]
5868
combine-as-imports = true

starlette/_compat.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -15,9 +15,7 @@
1515
# that reject usedforsecurity=True
1616
hashlib.md5(b"data", usedforsecurity=False) # type: ignore[call-arg]
1717

18-
def md5_hexdigest(
19-
data: bytes, *, usedforsecurity: bool = True
20-
) -> str: # pragma: no cover
18+
def md5_hexdigest(data: bytes, *, usedforsecurity: bool = True) -> str: # pragma: no cover
2119
return hashlib.md5( # type: ignore[call-arg]
2220
data, usedforsecurity=usedforsecurity
2321
).hexdigest()

starlette/_exception_handler.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -22,9 +22,7 @@
2222
StatusHandlers = typing.Dict[int, ExceptionHandler]
2323

2424

25-
def _lookup_exception_handler(
26-
exc_handlers: ExceptionHandlers, exc: Exception
27-
) -> ExceptionHandler | None:
25+
def _lookup_exception_handler(exc_handlers: ExceptionHandlers, exc: Exception) -> ExceptionHandler | None:
2826
for cls in type(exc).__mro__:
2927
if cls in exc_handlers:
3028
return exc_handlers[cls]

starlette/_utils.py

Lines changed: 3 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -37,26 +37,20 @@ def is_async_callable(obj: typing.Any) -> typing.Any:
3737
while isinstance(obj, functools.partial):
3838
obj = obj.func
3939

40-
return asyncio.iscoroutinefunction(obj) or (
41-
callable(obj) and asyncio.iscoroutinefunction(obj.__call__)
42-
)
40+
return asyncio.iscoroutinefunction(obj) or (callable(obj) and asyncio.iscoroutinefunction(obj.__call__))
4341

4442

4543
T_co = typing.TypeVar("T_co", covariant=True)
4644

4745

48-
class AwaitableOrContextManager(
49-
typing.Awaitable[T_co], typing.AsyncContextManager[T_co], typing.Protocol[T_co]
50-
): ...
46+
class AwaitableOrContextManager(typing.Awaitable[T_co], typing.AsyncContextManager[T_co], typing.Protocol[T_co]): ...
5147

5248

5349
class SupportsAsyncClose(typing.Protocol):
5450
async def close(self) -> None: ... # pragma: no cover
5551

5652

57-
SupportsAsyncCloseType = typing.TypeVar(
58-
"SupportsAsyncCloseType", bound=SupportsAsyncClose, covariant=False
59-
)
53+
SupportsAsyncCloseType = typing.TypeVar("SupportsAsyncCloseType", bound=SupportsAsyncClose, covariant=False)
6054

6155

6256
class AwaitableOrContextManagerWrapper(typing.Generic[SupportsAsyncCloseType]):

starlette/applications.py

Lines changed: 20 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -72,21 +72,15 @@ def __init__(
7272

7373
self.debug = debug
7474
self.state = State()
75-
self.router = Router(
76-
routes, on_startup=on_startup, on_shutdown=on_shutdown, lifespan=lifespan
77-
)
78-
self.exception_handlers = (
79-
{} if exception_handlers is None else dict(exception_handlers)
80-
)
75+
self.router = Router(routes, on_startup=on_startup, on_shutdown=on_shutdown, lifespan=lifespan)
76+
self.exception_handlers = {} if exception_handlers is None else dict(exception_handlers)
8177
self.user_middleware = [] if middleware is None else list(middleware)
8278
self.middleware_stack: ASGIApp | None = None
8379

8480
def build_middleware_stack(self) -> ASGIApp:
8581
debug = self.debug
8682
error_handler = None
87-
exception_handlers: dict[
88-
typing.Any, typing.Callable[[Request, Exception], Response]
89-
] = {}
83+
exception_handlers: dict[typing.Any, typing.Callable[[Request, Exception], Response]] = {}
9084

9185
for key, value in self.exception_handlers.items():
9286
if key in (500, Exception):
@@ -97,11 +91,7 @@ def build_middleware_stack(self) -> ASGIApp:
9791
middleware = (
9892
[Middleware(ServerErrorMiddleware, handler=error_handler, debug=debug)]
9993
+ self.user_middleware
100-
+ [
101-
Middleware(
102-
ExceptionMiddleware, handlers=exception_handlers, debug=debug
103-
)
104-
]
94+
+ [Middleware(ExceptionMiddleware, handlers=exception_handlers, debug=debug)]
10595
)
10696

10797
app = self.router
@@ -163,9 +153,7 @@ def add_route(
163153
name: str | None = None,
164154
include_in_schema: bool = True,
165155
) -> None: # pragma: no cover
166-
self.router.add_route(
167-
path, route, methods=methods, name=name, include_in_schema=include_in_schema
168-
)
156+
self.router.add_route(path, route, methods=methods, name=name, include_in_schema=include_in_schema)
169157

170158
def add_websocket_route(
171159
self,
@@ -175,16 +163,14 @@ def add_websocket_route(
175163
) -> None: # pragma: no cover
176164
self.router.add_websocket_route(path, route, name=name)
177165

178-
def exception_handler(
179-
self, exc_class_or_status_code: int | type[Exception]
180-
) -> typing.Callable: # type: ignore[type-arg]
166+
def exception_handler(self, exc_class_or_status_code: int | type[Exception]) -> typing.Callable: # type: ignore[type-arg]
181167
warnings.warn(
182-
"The `exception_handler` decorator is deprecated, and will be removed in version 1.0.0. " # noqa: E501
183-
"Refer to https://www.starlette.io/exceptions/ for the recommended approach.", # noqa: E501
168+
"The `exception_handler` decorator is deprecated, and will be removed in version 1.0.0. "
169+
"Refer to https://www.starlette.io/exceptions/ for the recommended approach.",
184170
DeprecationWarning,
185171
)
186172

187-
def decorator(func: typing.Callable) -> typing.Callable: # type: ignore[type-arg] # noqa: E501
173+
def decorator(func: typing.Callable) -> typing.Callable: # type: ignore[type-arg]
188174
self.add_exception_handler(exc_class_or_status_code, func)
189175
return func
190176

@@ -205,12 +191,12 @@ def route(
205191
>>> app = Starlette(routes=routes)
206192
"""
207193
warnings.warn(
208-
"The `route` decorator is deprecated, and will be removed in version 1.0.0. " # noqa: E501
209-
"Refer to https://www.starlette.io/routing/ for the recommended approach.", # noqa: E501
194+
"The `route` decorator is deprecated, and will be removed in version 1.0.0. "
195+
"Refer to https://www.starlette.io/routing/ for the recommended approach.",
210196
DeprecationWarning,
211197
)
212198

213-
def decorator(func: typing.Callable) -> typing.Callable: # type: ignore[type-arg] # noqa: E501
199+
def decorator(func: typing.Callable) -> typing.Callable: # type: ignore[type-arg]
214200
self.router.add_route(
215201
path,
216202
func,
@@ -231,18 +217,18 @@ def websocket_route(self, path: str, name: str | None = None) -> typing.Callable
231217
>>> app = Starlette(routes=routes)
232218
"""
233219
warnings.warn(
234-
"The `websocket_route` decorator is deprecated, and will be removed in version 1.0.0. " # noqa: E501
235-
"Refer to https://www.starlette.io/routing/#websocket-routing for the recommended approach.", # noqa: E501
220+
"The `websocket_route` decorator is deprecated, and will be removed in version 1.0.0. "
221+
"Refer to https://www.starlette.io/routing/#websocket-routing for the recommended approach.",
236222
DeprecationWarning,
237223
)
238224

239-
def decorator(func: typing.Callable) -> typing.Callable: # type: ignore[type-arg] # noqa: E501
225+
def decorator(func: typing.Callable) -> typing.Callable: # type: ignore[type-arg]
240226
self.router.add_websocket_route(path, func, name=name)
241227
return func
242228

243229
return decorator
244230

245-
def middleware(self, middleware_type: str) -> typing.Callable: # type: ignore[type-arg] # noqa: E501
231+
def middleware(self, middleware_type: str) -> typing.Callable: # type: ignore[type-arg]
246232
"""
247233
We no longer document this decorator style API, and its usage is discouraged.
248234
Instead you should use the following approach:
@@ -251,15 +237,13 @@ def middleware(self, middleware_type: str) -> typing.Callable: # type: ignore[t
251237
>>> app = Starlette(middleware=middleware)
252238
"""
253239
warnings.warn(
254-
"The `middleware` decorator is deprecated, and will be removed in version 1.0.0. " # noqa: E501
255-
"Refer to https://www.starlette.io/middleware/#using-middleware for recommended approach.", # noqa: E501
240+
"The `middleware` decorator is deprecated, and will be removed in version 1.0.0. "
241+
"Refer to https://www.starlette.io/middleware/#using-middleware for recommended approach.",
256242
DeprecationWarning,
257243
)
258-
assert (
259-
middleware_type == "http"
260-
), 'Currently only middleware("http") is supported.'
244+
assert middleware_type == "http", 'Currently only middleware("http") is supported.'
261245

262-
def decorator(func: typing.Callable) -> typing.Callable: # type: ignore[type-arg] # noqa: E501
246+
def decorator(func: typing.Callable) -> typing.Callable: # type: ignore[type-arg]
263247
self.add_middleware(BaseHTTPMiddleware, dispatch=func)
264248
return func
265249

starlette/authentication.py

Lines changed: 4 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -31,9 +31,7 @@ def requires(
3131
scopes: str | typing.Sequence[str],
3232
status_code: int = 403,
3333
redirect: str | None = None,
34-
) -> typing.Callable[
35-
[typing.Callable[_P, typing.Any]], typing.Callable[_P, typing.Any]
36-
]:
34+
) -> typing.Callable[[typing.Callable[_P, typing.Any]], typing.Callable[_P, typing.Any]]:
3735
scopes_list = [scopes] if isinstance(scopes, str) else list(scopes)
3836

3937
def decorator(
@@ -45,17 +43,13 @@ def decorator(
4543
type_ = parameter.name
4644
break
4745
else:
48-
raise Exception(
49-
f'No "request" or "websocket" argument on function "{func}"'
50-
)
46+
raise Exception(f'No "request" or "websocket" argument on function "{func}"')
5147

5248
if type_ == "websocket":
5349
# Handle websocket functions. (Always async)
5450
@functools.wraps(func)
5551
async def websocket_wrapper(*args: _P.args, **kwargs: _P.kwargs) -> None:
56-
websocket = kwargs.get(
57-
"websocket", args[idx] if idx < len(args) else None
58-
)
52+
websocket = kwargs.get("websocket", args[idx] if idx < len(args) else None)
5953
assert isinstance(websocket, WebSocket)
6054

6155
if not has_required_scope(websocket, scopes_list):
@@ -107,9 +101,7 @@ class AuthenticationError(Exception):
107101

108102

109103
class AuthenticationBackend:
110-
async def authenticate(
111-
self, conn: HTTPConnection
112-
) -> tuple[AuthCredentials, BaseUser] | None:
104+
async def authenticate(self, conn: HTTPConnection) -> tuple[AuthCredentials, BaseUser] | None:
113105
raise NotImplementedError() # pragma: no cover
114106

115107

starlette/background.py

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -15,9 +15,7 @@
1515

1616

1717
class BackgroundTask:
18-
def __init__(
19-
self, func: typing.Callable[P, typing.Any], *args: P.args, **kwargs: P.kwargs
20-
) -> None:
18+
def __init__(self, func: typing.Callable[P, typing.Any], *args: P.args, **kwargs: P.kwargs) -> None:
2119
self.func = func
2220
self.args = args
2321
self.kwargs = kwargs
@@ -34,9 +32,7 @@ class BackgroundTasks(BackgroundTask):
3432
def __init__(self, tasks: typing.Sequence[BackgroundTask] | None = None):
3533
self.tasks = list(tasks) if tasks else []
3634

37-
def add_task(
38-
self, func: typing.Callable[P, typing.Any], *args: P.args, **kwargs: P.kwargs
39-
) -> None:
35+
def add_task(self, func: typing.Callable[P, typing.Any], *args: P.args, **kwargs: P.kwargs) -> None:
4036
task = BackgroundTask(func, *args, **kwargs)
4137
self.tasks.append(task)
4238

starlette/concurrency.py

Lines changed: 4 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -16,26 +16,23 @@
1616
T = typing.TypeVar("T")
1717

1818

19-
async def run_until_first_complete(*args: tuple[typing.Callable, dict]) -> None: # type: ignore[type-arg] # noqa: E501
19+
async def run_until_first_complete(*args: tuple[typing.Callable, dict]) -> None: # type: ignore[type-arg]
2020
warnings.warn(
21-
"run_until_first_complete is deprecated "
22-
"and will be removed in a future version.",
21+
"run_until_first_complete is deprecated and will be removed in a future version.",
2322
DeprecationWarning,
2423
)
2524

2625
async with anyio.create_task_group() as task_group:
2726

28-
async def run(func: typing.Callable[[], typing.Coroutine]) -> None: # type: ignore[type-arg] # noqa: E501
27+
async def run(func: typing.Callable[[], typing.Coroutine]) -> None: # type: ignore[type-arg]
2928
await func()
3029
task_group.cancel_scope.cancel()
3130

3231
for func, kwargs in args:
3332
task_group.start_soon(run, functools.partial(func, **kwargs))
3433

3534

36-
async def run_in_threadpool(
37-
func: typing.Callable[P, T], *args: P.args, **kwargs: P.kwargs
38-
) -> T:
35+
async def run_in_threadpool(func: typing.Callable[P, T], *args: P.args, **kwargs: P.kwargs) -> T:
3936
if kwargs: # pragma: no cover
4037
# run_sync doesn't accept 'kwargs', so bind them in here
4138
func = functools.partial(func, **kwargs)

starlette/config.py

Lines changed: 5 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -25,18 +25,12 @@ def __getitem__(self, key: str) -> str:
2525

2626
def __setitem__(self, key: str, value: str) -> None:
2727
if key in self._has_been_read:
28-
raise EnvironError(
29-
f"Attempting to set environ['{key}'], but the value has already been "
30-
"read."
31-
)
28+
raise EnvironError(f"Attempting to set environ['{key}'], but the value has already been read.")
3229
self._environ.__setitem__(key, value)
3330

3431
def __delitem__(self, key: str) -> None:
3532
if key in self._has_been_read:
36-
raise EnvironError(
37-
f"Attempting to delete environ['{key}'], but the value has already "
38-
"been read."
39-
)
33+
raise EnvironError(f"Attempting to delete environ['{key}'], but the value has already been read.")
4034
self._environ.__delitem__(key)
4135

4236
def __iter__(self) -> typing.Iterator[str]:
@@ -85,9 +79,7 @@ def __call__(
8579
) -> T: ...
8680

8781
@typing.overload
88-
def __call__(
89-
self, key: str, cast: type[str] = ..., default: T = ...
90-
) -> T | str: ...
82+
def __call__(self, key: str, cast: type[str] = ..., default: T = ...) -> T | str: ...
9183

9284
def __call__(
9385
self,
@@ -138,13 +130,9 @@ def _perform_cast(
138130
mapping = {"true": True, "1": True, "false": False, "0": False}
139131
value = value.lower()
140132
if value not in mapping:
141-
raise ValueError(
142-
f"Config '{key}' has value '{value}'. Not a valid bool."
143-
)
133+
raise ValueError(f"Config '{key}' has value '{value}'. Not a valid bool.")
144134
return mapping[value]
145135
try:
146136
return cast(value)
147137
except (TypeError, ValueError):
148-
raise ValueError(
149-
f"Config '{key}' has value '{value}'. Not a valid {cast.__name__}."
150-
)
138+
raise ValueError(f"Config '{key}' has value '{value}'. Not a valid {cast.__name__}.")

0 commit comments

Comments
 (0)