Skip to content
Merged
Show file tree
Hide file tree
Changes from 16 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
10 changes: 2 additions & 8 deletions aiohttp/abc.py
Original file line number Diff line number Diff line change
Expand Up @@ -147,16 +147,10 @@ async def close(self) -> None:
"""Release resolver"""


if TYPE_CHECKING:
IterableBase = Iterable[Morsel[str]]
else:
IterableBase = Iterable


ClearCookiePredicate = Callable[["Morsel[str]"], bool]
ClearCookiePredicate = Callable[[Morsel[str]], bool]


class AbstractCookieJar(Sized, IterableBase):
class AbstractCookieJar(Sized, Iterable[Morsel[str]]):
"""Abstract Cookie Jar."""

@property
Expand Down
4 changes: 2 additions & 2 deletions aiohttp/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
from typing import TYPE_CHECKING, Any, Final, Generic, TypedDict, TypeVar, final

from multidict import CIMultiDict, MultiDict, MultiDictProxy, istr
from yarl import URL
from yarl import URL, Query

from . import hdrs, http, payload
from ._websocket.reader import WebSocketDataQueue
Expand Down Expand Up @@ -96,7 +96,7 @@
from .http import WS_KEY, HttpVersion, WebSocketReader, WebSocketWriter
from .http_websocket import WSHandshakeError, ws_ext_gen, ws_ext_parse
from .tracing import Trace, TraceConfig
from .typedefs import JSONEncoder, LooseCookies, LooseHeaders, Query, StrOrURL
from .typedefs import JSONEncoder, LooseCookies, LooseHeaders, StrOrURL

__all__ = (
# client_exceptions
Expand Down
11 changes: 3 additions & 8 deletions aiohttp/client_exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,17 +7,12 @@

from .typedefs import StrOrURL

if TYPE_CHECKING:
try:
import ssl

SSLContext = ssl.SSLContext
else:
try:
import ssl

SSLContext = ssl.SSLContext
except ImportError: # pragma: no cover
ssl = SSLContext = None # type: ignore[assignment]
except ImportError: # pragma: no cover
ssl = SSLContext = None # type: ignore[assignment]

if TYPE_CHECKING:
from .client_reqrep import ClientResponse, ConnectionKey, Fingerprint, RequestInfo
Expand Down
16 changes: 6 additions & 10 deletions aiohttp/client_reqrep.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
from typing import TYPE_CHECKING, Any, NamedTuple, TypedDict

from multidict import CIMultiDict, CIMultiDictProxy, MultiDict, MultiDictProxy
from yarl import URL
from yarl import URL, Query

from . import hdrs, multipart, payload
from ._cookie_helpers import (
Expand Down Expand Up @@ -57,18 +57,14 @@
StreamWriter,
)
from .streams import StreamReader
from .typedefs import DEFAULT_JSON_DECODER, JSONDecoder, Query, RawHeaders
from .typedefs import DEFAULT_JSON_DECODER, JSONDecoder, RawHeaders

if TYPE_CHECKING:
try:
import ssl
from ssl import SSLContext
else:
try:
import ssl
from ssl import SSLContext
except ImportError: # pragma: no cover
ssl = None # type: ignore[assignment]
SSLContext = object # type: ignore[misc,assignment]
except ImportError: # pragma: no cover
ssl = None # type: ignore[assignment]
SSLContext = object # type: ignore[misc,assignment]


__all__ = ("ClientRequest", "ClientResponse", "RequestInfo", "Fingerprint")
Expand Down
13 changes: 4 additions & 9 deletions aiohttp/connector.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,18 +56,13 @@
else:
Buffer = "bytes | bytearray | memoryview[int] | memoryview[bytes]"

if TYPE_CHECKING:
try:
import ssl

SSLContext = ssl.SSLContext
else:
try:
import ssl

SSLContext = ssl.SSLContext
except ImportError: # pragma: no cover
ssl = None # type: ignore[assignment]
SSLContext = object # type: ignore[misc,assignment]
except ImportError: # pragma: no cover
ssl = None # type: ignore[assignment]
SSLContext = object # type: ignore[misc,assignment]

EMPTY_SCHEMA_SET = frozenset({""})
HTTP_SCHEMA_SET = frozenset({"http", "https"})
Expand Down
22 changes: 5 additions & 17 deletions aiohttp/payload.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,9 @@
import sys
import warnings
from abc import ABC, abstractmethod
from collections.abc import Iterable
from collections.abc import AsyncIterable, AsyncIterator, Iterable
from itertools import chain
from typing import IO, TYPE_CHECKING, Any, Final, TextIO
from typing import IO, Any, Final, TextIO

from multidict import CIMultiDict

Expand Down Expand Up @@ -939,26 +939,14 @@ def __init__(
)


if TYPE_CHECKING:
from collections.abc import AsyncIterable, AsyncIterator

_AsyncIterator = AsyncIterator[bytes]
_AsyncIterable = AsyncIterable[bytes]
else:
from collections.abc import AsyncIterable, AsyncIterator

_AsyncIterator = AsyncIterator
_AsyncIterable = AsyncIterable


class AsyncIterablePayload(Payload):
_iter: _AsyncIterator | None = None
_value: _AsyncIterable
_iter: AsyncIterator[bytes] | None = None
_value: AsyncIterable[bytes]
_cached_chunks: list[bytes] | None = None
# _consumed stays False to allow reuse with cached content
_autoclose = True # Iterator doesn't need explicit closing

def __init__(self, value: _AsyncIterable, *args: Any, **kwargs: Any) -> None:
def __init__(self, value: AsyncIterable[bytes], *args: Any, **kwargs: Any) -> None:
if not isinstance(value, AsyncIterable):
raise TypeError(
"value argument must support "
Expand Down
52 changes: 17 additions & 35 deletions aiohttp/typedefs.py
Original file line number Diff line number Diff line change
@@ -1,52 +1,34 @@
import json
import os
from collections.abc import Awaitable, Callable, Iterable, Mapping
from typing import TYPE_CHECKING, Any, Protocol, Union
from http.cookies import BaseCookie, Morsel
from typing import TYPE_CHECKING, Any, Protocol

from multidict import CIMultiDict, CIMultiDictProxy, MultiDict, MultiDictProxy, istr
from yarl import URL, Query as _Query

Query = _Query
from yarl import URL

DEFAULT_JSON_ENCODER = json.dumps
DEFAULT_JSON_DECODER = json.loads

if TYPE_CHECKING:
_CIMultiDict = CIMultiDict[str]
_CIMultiDictProxy = CIMultiDictProxy[str]
_MultiDict = MultiDict[str]
_MultiDictProxy = MultiDictProxy[str]
from http.cookies import BaseCookie, Morsel

from .web import Request, StreamResponse
else:
_CIMultiDict = CIMultiDict
_CIMultiDictProxy = CIMultiDictProxy
_MultiDict = MultiDict
_MultiDictProxy = MultiDictProxy

Byteish = Union[bytes, bytearray, memoryview]
Byteish = bytes | bytearray | memoryview
JSONEncoder = Callable[[Any], str]
JSONDecoder = Callable[[str], Any]
LooseHeaders = Union[
Mapping[str, str],
Mapping[istr, str],
_CIMultiDict,
_CIMultiDictProxy,
Iterable[tuple[str | istr, str]],
]
LooseHeaders = (
Mapping[str, str]
| Mapping[istr, str]
| CIMultiDict[str]
| CIMultiDictProxy[str]
| Iterable[tuple[str | istr, str]]
)
RawHeaders = tuple[tuple[bytes, bytes], ...]
StrOrURL = Union[str, URL]

LooseCookiesMappings = Mapping[str, Union[str, "BaseCookie[str]", "Morsel[Any]"]]
LooseCookiesIterables = Iterable[
tuple[str, Union[str, "BaseCookie[str]", "Morsel[Any]"]]
]
LooseCookies = Union[
LooseCookiesMappings,
LooseCookiesIterables,
"BaseCookie[str]",
]
StrOrURL = str | URL

LooseCookiesMappings = Mapping[str, str | BaseCookie[str] | Morsel[Any]]
LooseCookiesIterables = Iterable[tuple[str, str | BaseCookie[str] | Morsel[Any]]]
LooseCookies = LooseCookiesMappings | LooseCookiesIterables | BaseCookie[str]

Handler = Callable[["Request"], Awaitable["StreamResponse"]]

Expand All @@ -57,4 +39,4 @@ def __call__(
) -> Awaitable["StreamResponse"]: ...


PathLike = Union[str, "os.PathLike[str]"]
PathLike = str | os.PathLike[str]
11 changes: 4 additions & 7 deletions aiohttp/web.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
from collections.abc import Awaitable, Callable, Iterable, Iterable as TypingIterable
from contextlib import suppress
from importlib import import_module
from typing import TYPE_CHECKING, Any, cast
from typing import Any, cast

from .abc import AbstractAccessLogger
from .helpers import AppKey
Expand Down Expand Up @@ -256,13 +256,10 @@
)


if TYPE_CHECKING:
try:
from ssl import SSLContext
else:
try:
from ssl import SSLContext
except ImportError: # pragma: no cover
SSLContext = object # type: ignore[misc,assignment]
except ImportError: # pragma: no cover
SSLContext = object # type: ignore[misc,assignment]

# Only display warning when using -Wdefault, -We, -X dev or similar.
warnings.filterwarnings("ignore", category=NotAppKeyWarning, append=True)
Expand Down
27 changes: 7 additions & 20 deletions aiohttp/web_app.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
Sequence,
)
from functools import lru_cache, partial, update_wrapper
from typing import TYPE_CHECKING, Any, TypeVar, cast, final, overload
from typing import Any, TypeVar, cast, final, overload

from aiosignal import Signal
from frozenlist import FrozenList
Expand All @@ -39,21 +39,11 @@

__all__ = ("Application", "CleanupError")


if TYPE_CHECKING:
_AppSignal = Signal["Application"]
_RespPrepareSignal = Signal[Request, StreamResponse]
_Middlewares = FrozenList[Middleware]
_MiddlewaresHandlers = Sequence[Middleware]
_Subapps = list["Application"]
else:
# No type checker mode, skip types
_AppSignal = Signal
_RespPrepareSignal = Signal
_Handler = Callable
_Middlewares = FrozenList
_MiddlewaresHandlers = Sequence
_Subapps = list
_AppSignal = Signal["Application"]
_RespPrepareSignal = Signal[Request, StreamResponse]
_Middlewares = FrozenList[Middleware]
_MiddlewaresHandlers = Sequence[Middleware]
_Subapps = list["Application"]

_T = TypeVar("_T")
_U = TypeVar("_U")
Expand Down Expand Up @@ -415,10 +405,7 @@ def exceptions(self) -> list[BaseException]:
return cast(list[BaseException], self.args[1])


if TYPE_CHECKING:
_CleanupContextBase = FrozenList[Callable[[Application], AsyncIterator[None]]]
else:
_CleanupContextBase = FrozenList
_CleanupContextBase = FrozenList[Callable[[Application], AsyncIterator[None]]]


class CleanupContext(_CleanupContextBase):
Expand Down
7 changes: 1 addition & 6 deletions aiohttp/web_response.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import asyncio
import collections.abc
import datetime
import enum
import json
Expand Down Expand Up @@ -43,10 +42,6 @@
if TYPE_CHECKING:
from .web_request import BaseRequest

BaseClass = MutableMapping[str, Any]
else:
BaseClass = collections.abc.MutableMapping


# TODO(py311): Convert to StrEnum for wider use
class ContentCoding(enum.Enum):
Expand All @@ -66,7 +61,7 @@ class ContentCoding(enum.Enum):
############################################################


class StreamResponse(BaseClass, HeadersMixin, CookieMixin):
class StreamResponse(MutableMapping[str, Any], HeadersMixin, CookieMixin):

_body: None | bytes | bytearray | Payload
_length_check = True
Expand Down
11 changes: 4 additions & 7 deletions aiohttp/web_runner.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
import signal
import socket
from abc import ABC, abstractmethod
from typing import TYPE_CHECKING, Any, Generic, TypeVar
from typing import Any, Generic, TypeVar

from yarl import URL

Expand All @@ -16,13 +16,10 @@
from .web_request import BaseRequest, Request
from .web_server import Server

if TYPE_CHECKING:
try:
from ssl import SSLContext
else:
try:
from ssl import SSLContext
except ImportError: # pragma: no cover
SSLContext = object # type: ignore[misc,assignment]
except ImportError: # pragma: no cover
SSLContext = object # type: ignore[misc,assignment]

__all__ = (
"BaseSite",
Expand Down
6 changes: 1 addition & 5 deletions aiohttp/web_urldispatcher.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,10 +60,6 @@
if TYPE_CHECKING:
from .web_app import Application

BaseDict = dict[str, str]
else:
BaseDict = dict

CIRCULAR_SYMLINK_ERROR = (RuntimeError,) if sys.version_info < (3, 13) else ()

HTTP_METHOD_RE: Final[Pattern[str]] = re.compile(
Expand Down Expand Up @@ -212,7 +208,7 @@ async def handle_expect_header(self, request: Request) -> StreamResponse | None:
return await self._expect_handler(request)


class UrlMappingMatchInfo(BaseDict, AbstractMatchInfo):
class UrlMappingMatchInfo(dict[str, str], AbstractMatchInfo):

__slots__ = ("_route", "_apps", "_current_app", "_frozen")

Expand Down
Loading