Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use __future__.annotations #2433

Merged
merged 3 commits into from
Jan 20, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 4 additions & 4 deletions starlette/_exception_handler.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from __future__ import annotations

import typing

from starlette._utils import is_async_callable
Expand All @@ -22,16 +24,14 @@

def _lookup_exception_handler(
exc_handlers: ExceptionHandlers, exc: Exception
) -> typing.Optional[ExceptionHandler]:
) -> ExceptionHandler | None:
for cls in type(exc).__mro__:
if cls in exc_handlers:
return exc_handlers[cls]
return None


def wrap_app_handling_exceptions(
app: ASGIApp, conn: typing.Union[Request, WebSocket]
) -> ASGIApp:
def wrap_app_handling_exceptions(app: ASGIApp, conn: Request | WebSocket) -> ASGIApp:
exception_handlers: ExceptionHandlers
status_handlers: StatusHandlers
try:
Expand Down
4 changes: 3 additions & 1 deletion starlette/_utils.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from __future__ import annotations

import asyncio
import functools
import re
Expand Down Expand Up @@ -74,7 +76,7 @@ async def __aenter__(self) -> SupportsAsyncCloseType:
self.entered = await self.aw
return self.entered

async def __aexit__(self, *args: typing.Any) -> typing.Union[None, bool]:
async def __aexit__(self, *args: typing.Any) -> None | bool:
await self.entered.close()
return None

Expand Down
10 changes: 5 additions & 5 deletions starlette/applications.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,14 +55,14 @@ class Starlette:
"""

def __init__(
self: "AppType",
self: AppType,
debug: bool = False,
routes: typing.Sequence[BaseRoute] | None = None,
middleware: typing.Sequence[Middleware] | None = None,
exception_handlers: typing.Mapping[typing.Any, ExceptionHandler] | None = None,
on_startup: typing.Sequence[typing.Callable[[], typing.Any]] | None = None,
on_shutdown: typing.Sequence[typing.Callable[[], typing.Any]] | None = None,
lifespan: typing.Optional[Lifespan["AppType"]] = None,
lifespan: Lifespan[AppType] | None = None,
) -> None:
# The lifespan context function is a newer style that replaces
# on_startup / on_shutdown handlers. Use one or the other, not both.
Expand All @@ -84,7 +84,7 @@ def __init__(
def build_middleware_stack(self) -> ASGIApp:
debug = self.debug
error_handler = None
exception_handlers: typing.Dict[
exception_handlers: dict[
typing.Any, typing.Callable[[Request, Exception], Response]
] = {}

Expand All @@ -110,7 +110,7 @@ def build_middleware_stack(self) -> ASGIApp:
return app

@property
def routes(self) -> typing.List[BaseRoute]:
def routes(self) -> list[BaseRoute]:
return self.router.routes

def url_path_for(self, name: str, /, **path_params: typing.Any) -> URLPath:
Expand Down Expand Up @@ -193,7 +193,7 @@ def decorator(func: typing.Callable) -> typing.Callable: # type: ignore[type-ar
def route(
self,
path: str,
methods: typing.List[str] | None = None,
methods: list[str] | None = None,
name: str | None = None,
include_in_schema: bool = True,
) -> typing.Callable: # type: ignore[type-arg]
Expand Down
10 changes: 6 additions & 4 deletions starlette/authentication.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from __future__ import annotations

import functools
import inspect
import sys
Expand Down Expand Up @@ -26,9 +28,9 @@ def has_required_scope(conn: HTTPConnection, scopes: typing.Sequence[str]) -> bo


def requires(
scopes: typing.Union[str, typing.Sequence[str]],
scopes: str | typing.Sequence[str],
status_code: int = 403,
redirect: typing.Optional[str] = None,
redirect: str | None = None,
) -> typing.Callable[
[typing.Callable[_P, typing.Any]], typing.Callable[_P, typing.Any]
]:
Expand Down Expand Up @@ -113,12 +115,12 @@ class AuthenticationError(Exception):
class AuthenticationBackend:
async def authenticate(
self, conn: HTTPConnection
) -> typing.Optional[typing.Tuple["AuthCredentials", "BaseUser"]]:
) -> tuple[AuthCredentials, BaseUser] | None:
raise NotImplementedError() # pragma: no cover


class AuthCredentials:
def __init__(self, scopes: typing.Optional[typing.Sequence[str]] = None):
def __init__(self, scopes: typing.Sequence[str] | None = None):
self.scopes = [] if scopes is None else list(scopes)


Expand Down
4 changes: 3 additions & 1 deletion starlette/background.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from __future__ import annotations

import sys
import typing

Expand Down Expand Up @@ -29,7 +31,7 @@ async def __call__(self) -> None:


class BackgroundTasks(BackgroundTask):
def __init__(self, tasks: typing.Optional[typing.Sequence[BackgroundTask]] = None):
def __init__(self, tasks: typing.Sequence[BackgroundTask] | None = None):
self.tasks = list(tasks) if tasks else []

def add_task(
Expand Down
4 changes: 3 additions & 1 deletion starlette/concurrency.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from __future__ import annotations

import functools
import sys
import typing
Expand All @@ -14,7 +16,7 @@
T = typing.TypeVar("T")


async def run_until_first_complete(*args: typing.Tuple[typing.Callable, dict]) -> None: # type: ignore[type-arg] # noqa: E501
async def run_until_first_complete(*args: tuple[typing.Callable, dict]) -> None: # type: ignore[type-arg] # noqa: E501
warnings.warn(
"run_until_first_complete is deprecated "
"and will be removed in a future version.",
Expand Down
24 changes: 11 additions & 13 deletions starlette/config.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from __future__ import annotations

import os
import typing
from pathlib import Path
Expand Down Expand Up @@ -51,7 +53,7 @@ def __len__(self) -> int:
class Config:
def __init__(
self,
env_file: typing.Optional[typing.Union[str, Path]] = None,
env_file: str | Path | None = None,
environ: typing.Mapping[str, str] = environ,
env_prefix: str = "",
) -> None:
Expand All @@ -64,17 +66,15 @@ def __init__(
self.file_values = self._read_file(env_file)

@typing.overload
def __call__(self, key: str, *, default: None) -> typing.Optional[str]:
def __call__(self, key: str, *, default: None) -> str | None:
...

@typing.overload
def __call__(self, key: str, cast: typing.Type[T], default: T = ...) -> T:
def __call__(self, key: str, cast: type[T], default: T = ...) -> T:
...

@typing.overload
def __call__(
self, key: str, cast: typing.Type[str] = ..., default: str = ...
) -> str:
def __call__(self, key: str, cast: type[str] = ..., default: str = ...) -> str:
...

@typing.overload
Expand All @@ -87,23 +87,21 @@ def __call__(
...

@typing.overload
def __call__(
self, key: str, cast: typing.Type[str] = ..., default: T = ...
) -> typing.Union[T, str]:
def __call__(self, key: str, cast: type[str] = ..., default: T = ...) -> T | str:
...

def __call__(
self,
key: str,
cast: typing.Optional[typing.Callable[[typing.Any], typing.Any]] = None,
cast: typing.Callable[[typing.Any], typing.Any] | None = None,
default: typing.Any = undefined,
) -> typing.Any:
return self.get(key, cast, default)

def get(
self,
key: str,
cast: typing.Optional[typing.Callable[[typing.Any], typing.Any]] = None,
cast: typing.Callable[[typing.Any], typing.Any] | None = None,
default: typing.Any = undefined,
) -> typing.Any:
key = self.env_prefix + key
Expand All @@ -117,7 +115,7 @@ def get(
return self._perform_cast(key, default, cast)
raise KeyError(f"Config '{key}' is missing, and has no default.")

def _read_file(self, file_name: typing.Union[str, Path]) -> typing.Dict[str, str]:
def _read_file(self, file_name: str | Path) -> dict[str, str]:
file_values: typing.Dict[str, str] = {}
with open(file_name) as input_file:
for line in input_file.readlines():
Expand All @@ -133,7 +131,7 @@ def _perform_cast(
self,
key: str,
value: typing.Any,
cast: typing.Optional[typing.Callable[[typing.Any], typing.Any]] = None,
cast: typing.Callable[[typing.Any], typing.Any] | None = None,
) -> typing.Any:
if cast is None or value is None:
return value
Expand Down
Loading