From 4e0a17c9af50ff180d57a0edfdc5ceab24611b3b Mon Sep 17 00:00:00 2001 From: 4shen0ne <33086594+zrquan@users.noreply.github.com> Date: Wed, 16 Oct 2024 16:59:26 +0800 Subject: [PATCH] Consistent import style (#970) --- httpcore/_api.py | 12 ++--- httpcore/_async/connection.py | 10 ++-- httpcore/_async/connection_pool.py | 14 ++--- httpcore/_async/http11.py | 18 ++++--- httpcore/_async/http2.py | 8 +-- httpcore/_async/http_proxy.py | 23 +++++---- httpcore/_async/interfaces.py | 12 ++--- httpcore/_async/socks_proxy.py | 26 +++++----- httpcore/_backends/anyio.py | 8 +-- httpcore/_backends/auto.py | 6 +-- httpcore/_backends/mock.py | 14 ++--- httpcore/_backends/sync.py | 6 +-- httpcore/_backends/trio.py | 8 +-- httpcore/_exceptions.py | 6 +-- httpcore/_models.py | 82 +++++++++++++++--------------- httpcore/_sync/connection.py | 10 ++-- httpcore/_sync/connection_pool.py | 14 ++--- httpcore/_sync/http11.py | 18 ++++--- httpcore/_sync/http2.py | 8 +-- httpcore/_sync/http_proxy.py | 23 +++++---- httpcore/_sync/interfaces.py | 12 ++--- httpcore/_sync/socks_proxy.py | 26 +++++----- httpcore/_synchronization.py | 14 ++--- httpcore/_trace.py | 16 +++--- 24 files changed, 199 insertions(+), 195 deletions(-) diff --git a/httpcore/_api.py b/httpcore/_api.py index e84a88fb..38b961d1 100644 --- a/httpcore/_api.py +++ b/httpcore/_api.py @@ -1,7 +1,7 @@ from __future__ import annotations -from contextlib import contextmanager -from typing import Iterator +import contextlib +import typing from ._models import URL, Extensions, HeaderTypes, Response from ._sync.connection_pool import ConnectionPool @@ -12,7 +12,7 @@ def request( url: URL | bytes | str, *, headers: HeaderTypes = None, - content: bytes | Iterator[bytes] | None = None, + content: bytes | typing.Iterator[bytes] | None = None, extensions: Extensions | None = None, ) -> Response: """ @@ -47,15 +47,15 @@ def request( ) -@contextmanager +@contextlib.contextmanager def stream( method: bytes | str, url: URL | bytes | str, *, headers: HeaderTypes = None, - content: bytes | Iterator[bytes] | None = None, + content: bytes | typing.Iterator[bytes] | None = None, extensions: Extensions | None = None, -) -> Iterator[Response]: +) -> typing.Iterator[Response]: """ Sends an HTTP request, returning the response within a content manager. diff --git a/httpcore/_async/connection.py b/httpcore/_async/connection.py index 2eb53c8e..b42581df 100644 --- a/httpcore/_async/connection.py +++ b/httpcore/_async/connection.py @@ -3,8 +3,8 @@ import itertools import logging import ssl -from types import TracebackType -from typing import Iterable, Iterator +import types +import typing from .._backends.auto import AutoBackend from .._backends.base import SOCKET_OPTION, AsyncNetworkBackend, AsyncNetworkStream @@ -22,7 +22,7 @@ logger = logging.getLogger("httpcore.connection") -def exponential_backoff(factor: float) -> Iterator[float]: +def exponential_backoff(factor: float) -> typing.Iterator[float]: """ Generate a geometric sequence that has a ratio of 2 and starts with 0. @@ -47,7 +47,7 @@ def __init__( local_address: str | None = None, uds: str | None = None, network_backend: AsyncNetworkBackend | None = None, - socket_options: Iterable[SOCKET_OPTION] | None = None, + socket_options: typing.Iterable[SOCKET_OPTION] | None = None, ) -> None: self._origin = origin self._ssl_context = ssl_context @@ -217,6 +217,6 @@ async def __aexit__( self, exc_type: type[BaseException] | None = None, exc_value: BaseException | None = None, - traceback: TracebackType | None = None, + traceback: types.TracebackType | None = None, ) -> None: await self.aclose() diff --git a/httpcore/_async/connection_pool.py b/httpcore/_async/connection_pool.py index 314eb2c7..0795b9cc 100644 --- a/httpcore/_async/connection_pool.py +++ b/httpcore/_async/connection_pool.py @@ -2,8 +2,8 @@ import ssl import sys -from types import TracebackType -from typing import AsyncIterable, AsyncIterator, Iterable +import types +import typing from .._backends.auto import AutoBackend from .._backends.base import SOCKET_OPTION, AsyncNetworkBackend @@ -57,7 +57,7 @@ def __init__( local_address: str | None = None, uds: str | None = None, network_backend: AsyncNetworkBackend | None = None, - socket_options: Iterable[SOCKET_OPTION] | None = None, + socket_options: typing.Iterable[SOCKET_OPTION] | None = None, ) -> None: """ A connection pool for making HTTP requests. @@ -217,7 +217,7 @@ async def handle_async_request(self, request: Request) -> Response: # Return the response. Note that in this case we still have to manage # the point at which the response is closed. - assert isinstance(response.stream, AsyncIterable) + assert isinstance(response.stream, typing.AsyncIterable) return Response( status=response.status, headers=response.headers, @@ -319,7 +319,7 @@ async def __aexit__( self, exc_type: type[BaseException] | None = None, exc_value: BaseException | None = None, - traceback: TracebackType | None = None, + traceback: types.TracebackType | None = None, ) -> None: await self.aclose() @@ -349,7 +349,7 @@ def __repr__(self) -> str: class PoolByteStream: def __init__( self, - stream: AsyncIterable[bytes], + stream: typing.AsyncIterable[bytes], pool_request: AsyncPoolRequest, pool: AsyncConnectionPool, ) -> None: @@ -358,7 +358,7 @@ def __init__( self._pool = pool self._closed = False - async def __aiter__(self) -> AsyncIterator[bytes]: + async def __aiter__(self) -> typing.AsyncIterator[bytes]: try: async for part in self._stream: yield part diff --git a/httpcore/_async/http11.py b/httpcore/_async/http11.py index b5c3cd5d..e6d6d709 100644 --- a/httpcore/_async/http11.py +++ b/httpcore/_async/http11.py @@ -4,8 +4,8 @@ import logging import ssl import time -from types import TracebackType -from typing import Any, AsyncIterable, AsyncIterator, Union +import types +import typing import h11 @@ -26,7 +26,7 @@ # A subset of `h11.Event` types supported by `_send_event` -H11SendEvent = Union[ +H11SendEvent = typing.Union[ h11.Request, h11.Data, h11.EndOfMessage, @@ -153,7 +153,7 @@ async def _send_request_body(self, request: Request) -> None: timeouts = request.extensions.get("timeout", {}) timeout = timeouts.get("write", None) - assert isinstance(request.stream, AsyncIterable) + assert isinstance(request.stream, typing.AsyncIterable) async for chunk in request.stream: event = h11.Data(data=chunk) await self._send_event(event, timeout=timeout) @@ -193,7 +193,9 @@ async def _receive_response_headers( return http_version, event.status_code, event.reason, headers, trailing_data - async def _receive_response_body(self, request: Request) -> AsyncIterator[bytes]: + async def _receive_response_body( + self, request: Request + ) -> typing.AsyncIterator[bytes]: timeouts = request.extensions.get("timeout", {}) timeout = timeouts.get("read", None) @@ -314,7 +316,7 @@ async def __aexit__( self, exc_type: type[BaseException] | None = None, exc_value: BaseException | None = None, - traceback: TracebackType | None = None, + traceback: types.TracebackType | None = None, ) -> None: await self.aclose() @@ -325,7 +327,7 @@ def __init__(self, connection: AsyncHTTP11Connection, request: Request) -> None: self._request = request self._closed = False - async def __aiter__(self) -> AsyncIterator[bytes]: + async def __aiter__(self) -> typing.AsyncIterator[bytes]: kwargs = {"request": self._request} try: async with Trace("receive_response_body", logger, self._request, kwargs): @@ -373,5 +375,5 @@ async def start_tls( ) -> AsyncNetworkStream: return await self._stream.start_tls(ssl_context, server_hostname, timeout) - def get_extra_info(self, info: str) -> Any: + def get_extra_info(self, info: str) -> typing.Any: return self._stream.get_extra_info(info) diff --git a/httpcore/_async/http2.py b/httpcore/_async/http2.py index c10e1bb9..c6434a04 100644 --- a/httpcore/_async/http2.py +++ b/httpcore/_async/http2.py @@ -4,7 +4,7 @@ import logging import time import types -from typing import AsyncIterable, AsyncIterator +import typing import h2.config import h2.connection @@ -253,7 +253,7 @@ async def _send_request_body(self, request: Request, stream_id: int) -> None: if not has_body_headers(request): return - assert isinstance(request.stream, AsyncIterable) + assert isinstance(request.stream, typing.AsyncIterable) async for data in request.stream: await self._send_stream_data(request, stream_id, data) await self._send_end_stream(request, stream_id) @@ -303,7 +303,7 @@ async def _receive_response( async def _receive_response_body( self, request: Request, stream_id: int - ) -> AsyncIterator[bytes]: + ) -> typing.AsyncIterator[bytes]: """ Iterator that returns the bytes of the response body for a given stream ID. """ @@ -559,7 +559,7 @@ def __init__( self._stream_id = stream_id self._closed = False - async def __aiter__(self) -> AsyncIterator[bytes]: + async def __aiter__(self) -> typing.AsyncIterator[bytes]: kwargs = {"request": self._request, "stream_id": self._stream_id} try: async with Trace("receive_response_body", logger, self._request, kwargs): diff --git a/httpcore/_async/http_proxy.py b/httpcore/_async/http_proxy.py index 896d28cb..4cbfe518 100644 --- a/httpcore/_async/http_proxy.py +++ b/httpcore/_async/http_proxy.py @@ -1,9 +1,9 @@ from __future__ import annotations +import base64 import logging import ssl -from base64 import b64encode -from typing import Iterable, Mapping, Sequence, Tuple, Union +import typing from .._backends.base import SOCKET_OPTION, AsyncNetworkBackend from .._exceptions import ProxyError @@ -24,16 +24,17 @@ from .http11 import AsyncHTTP11Connection from .interfaces import AsyncConnectionInterface -HeadersAsSequence = Sequence[Tuple[Union[bytes, str], Union[bytes, str]]] -HeadersAsMapping = Mapping[Union[bytes, str], Union[bytes, str]] +ByteOrStr = typing.Union[bytes, str] +HeadersAsSequence = typing.Sequence[typing.Tuple[ByteOrStr, ByteOrStr]] +HeadersAsMapping = typing.Mapping[ByteOrStr, ByteOrStr] logger = logging.getLogger("httpcore.proxy") def merge_headers( - default_headers: Sequence[tuple[bytes, bytes]] | None = None, - override_headers: Sequence[tuple[bytes, bytes]] | None = None, + default_headers: typing.Sequence[tuple[bytes, bytes]] | None = None, + override_headers: typing.Sequence[tuple[bytes, bytes]] | None = None, ) -> list[tuple[bytes, bytes]]: """ Append default_headers and override_headers, de-duplicating if a key exists @@ -52,7 +53,7 @@ def merge_headers( def build_auth_header(username: bytes, password: bytes) -> bytes: userpass = username + b":" + password - return b"Basic " + b64encode(userpass) + return b"Basic " + base64.b64encode(userpass) class AsyncHTTPProxy(AsyncConnectionPool): @@ -76,7 +77,7 @@ def __init__( local_address: str | None = None, uds: str | None = None, network_backend: AsyncNetworkBackend | None = None, - socket_options: Iterable[SOCKET_OPTION] | None = None, + socket_options: typing.Iterable[SOCKET_OPTION] | None = None, ) -> None: """ A connection pool for making HTTP requests. @@ -177,7 +178,7 @@ def __init__( proxy_headers: HeadersAsMapping | HeadersAsSequence | None = None, keepalive_expiry: float | None = None, network_backend: AsyncNetworkBackend | None = None, - socket_options: Iterable[SOCKET_OPTION] | None = None, + socket_options: typing.Iterable[SOCKET_OPTION] | None = None, proxy_ssl_context: ssl.SSLContext | None = None, ) -> None: self._connection = AsyncHTTPConnection( @@ -240,12 +241,12 @@ def __init__( remote_origin: Origin, ssl_context: ssl.SSLContext | None = None, proxy_ssl_context: ssl.SSLContext | None = None, - proxy_headers: Sequence[tuple[bytes, bytes]] | None = None, + proxy_headers: typing.Sequence[tuple[bytes, bytes]] | None = None, keepalive_expiry: float | None = None, http1: bool = True, http2: bool = False, network_backend: AsyncNetworkBackend | None = None, - socket_options: Iterable[SOCKET_OPTION] | None = None, + socket_options: typing.Iterable[SOCKET_OPTION] | None = None, ) -> None: self._connection: AsyncConnectionInterface = AsyncHTTPConnection( origin=proxy_origin, diff --git a/httpcore/_async/interfaces.py b/httpcore/_async/interfaces.py index bff92014..361583be 100644 --- a/httpcore/_async/interfaces.py +++ b/httpcore/_async/interfaces.py @@ -1,7 +1,7 @@ from __future__ import annotations -from contextlib import asynccontextmanager -from typing import AsyncIterator +import contextlib +import typing from .._models import ( URL, @@ -24,7 +24,7 @@ async def request( url: URL | bytes | str, *, headers: HeaderTypes = None, - content: bytes | AsyncIterator[bytes] | None = None, + content: bytes | typing.AsyncIterator[bytes] | None = None, extensions: Extensions | None = None, ) -> Response: # Strict type checking on our parameters. @@ -49,16 +49,16 @@ async def request( await response.aclose() return response - @asynccontextmanager + @contextlib.asynccontextmanager async def stream( self, method: bytes | str, url: URL | bytes | str, *, headers: HeaderTypes = None, - content: bytes | AsyncIterator[bytes] | None = None, + content: bytes | typing.AsyncIterator[bytes] | None = None, extensions: Extensions | None = None, - ) -> AsyncIterator[Response]: + ) -> typing.AsyncIterator[Response]: # Strict type checking on our parameters. method = enforce_bytes(method, name="method") url = enforce_url(url, name="url") diff --git a/httpcore/_async/socks_proxy.py b/httpcore/_async/socks_proxy.py index 5052f4a8..ef96a8c1 100644 --- a/httpcore/_async/socks_proxy.py +++ b/httpcore/_async/socks_proxy.py @@ -3,7 +3,7 @@ import logging import ssl -from socksio import socks5 +import socksio from .._backends.auto import AutoBackend from .._backends.base import AsyncNetworkBackend, AsyncNetworkStream @@ -46,22 +46,22 @@ async def _init_socks5_connection( port: int, auth: tuple[bytes, bytes] | None = None, ) -> None: - conn = socks5.SOCKS5Connection() + conn = socksio.socks5.SOCKS5Connection() # Auth method request auth_method = ( - socks5.SOCKS5AuthMethod.NO_AUTH_REQUIRED + socksio.socks5.SOCKS5AuthMethod.NO_AUTH_REQUIRED if auth is None - else socks5.SOCKS5AuthMethod.USERNAME_PASSWORD + else socksio.socks5.SOCKS5AuthMethod.USERNAME_PASSWORD ) - conn.send(socks5.SOCKS5AuthMethodsRequest([auth_method])) + conn.send(socksio.socks5.SOCKS5AuthMethodsRequest([auth_method])) outgoing_bytes = conn.data_to_send() await stream.write(outgoing_bytes) # Auth method response incoming_bytes = await stream.read(max_bytes=4096) response = conn.receive_data(incoming_bytes) - assert isinstance(response, socks5.SOCKS5AuthReply) + assert isinstance(response, socksio.socks5.SOCKS5AuthReply) if response.method != auth_method: requested = AUTH_METHODS.get(auth_method, "UNKNOWN") responded = AUTH_METHODS.get(response.method, "UNKNOWN") @@ -69,25 +69,25 @@ async def _init_socks5_connection( f"Requested {requested} from proxy server, but got {responded}." ) - if response.method == socks5.SOCKS5AuthMethod.USERNAME_PASSWORD: + if response.method == socksio.socks5.SOCKS5AuthMethod.USERNAME_PASSWORD: # Username/password request assert auth is not None username, password = auth - conn.send(socks5.SOCKS5UsernamePasswordRequest(username, password)) + conn.send(socksio.socks5.SOCKS5UsernamePasswordRequest(username, password)) outgoing_bytes = conn.data_to_send() await stream.write(outgoing_bytes) # Username/password response incoming_bytes = await stream.read(max_bytes=4096) response = conn.receive_data(incoming_bytes) - assert isinstance(response, socks5.SOCKS5UsernamePasswordReply) + assert isinstance(response, socksio.socks5.SOCKS5UsernamePasswordReply) if not response.success: raise ProxyError("Invalid username/password") # Connect request conn.send( - socks5.SOCKS5CommandRequest.from_address( - socks5.SOCKS5Command.CONNECT, (host, port) + socksio.socks5.SOCKS5CommandRequest.from_address( + socksio.socks5.SOCKS5Command.CONNECT, (host, port) ) ) outgoing_bytes = conn.data_to_send() @@ -96,8 +96,8 @@ async def _init_socks5_connection( # Connect response incoming_bytes = await stream.read(max_bytes=4096) response = conn.receive_data(incoming_bytes) - assert isinstance(response, socks5.SOCKS5Reply) - if response.reply_code != socks5.SOCKS5ReplyCode.SUCCEEDED: + assert isinstance(response, socksio.socks5.SOCKS5Reply) + if response.reply_code != socksio.socks5.SOCKS5ReplyCode.SUCCEEDED: reply_code = REPLY_CODES.get(response.reply_code, "UNKOWN") raise ProxyError(f"Proxy Server could not connect: {reply_code}.") diff --git a/httpcore/_backends/anyio.py b/httpcore/_backends/anyio.py index 451ffb37..a140095e 100644 --- a/httpcore/_backends/anyio.py +++ b/httpcore/_backends/anyio.py @@ -1,7 +1,7 @@ from __future__ import annotations import ssl -from typing import Any, Iterable +import typing import anyio @@ -79,7 +79,7 @@ async def start_tls( raise exc return AnyIOStream(ssl_stream) - def get_extra_info(self, info: str) -> Any: + def get_extra_info(self, info: str) -> typing.Any: if info == "ssl_object": return self._stream.extra(anyio.streams.tls.TLSAttribute.ssl_object, None) if info == "client_addr": @@ -101,7 +101,7 @@ async def connect_tcp( port: int, timeout: float | None = None, local_address: str | None = None, - socket_options: Iterable[SOCKET_OPTION] | None = None, + socket_options: typing.Iterable[SOCKET_OPTION] | None = None, ) -> AsyncNetworkStream: # pragma: nocover if socket_options is None: socket_options = [] @@ -126,7 +126,7 @@ async def connect_unix_socket( self, path: str, timeout: float | None = None, - socket_options: Iterable[SOCKET_OPTION] | None = None, + socket_options: typing.Iterable[SOCKET_OPTION] | None = None, ) -> AsyncNetworkStream: # pragma: nocover if socket_options is None: socket_options = [] diff --git a/httpcore/_backends/auto.py b/httpcore/_backends/auto.py index e8086acb..49f0e698 100644 --- a/httpcore/_backends/auto.py +++ b/httpcore/_backends/auto.py @@ -1,6 +1,6 @@ from __future__ import annotations -from typing import Iterable +import typing from .._synchronization import current_async_library from .base import SOCKET_OPTION, AsyncNetworkBackend, AsyncNetworkStream @@ -25,7 +25,7 @@ async def connect_tcp( port: int, timeout: float | None = None, local_address: str | None = None, - socket_options: Iterable[SOCKET_OPTION] | None = None, + socket_options: typing.Iterable[SOCKET_OPTION] | None = None, ) -> AsyncNetworkStream: await self._init_backend() return await self._backend.connect_tcp( @@ -40,7 +40,7 @@ async def connect_unix_socket( self, path: str, timeout: float | None = None, - socket_options: Iterable[SOCKET_OPTION] | None = None, + socket_options: typing.Iterable[SOCKET_OPTION] | None = None, ) -> AsyncNetworkStream: # pragma: nocover await self._init_backend() return await self._backend.connect_unix_socket( diff --git a/httpcore/_backends/mock.py b/httpcore/_backends/mock.py index be33ec86..9b6edca0 100644 --- a/httpcore/_backends/mock.py +++ b/httpcore/_backends/mock.py @@ -1,7 +1,7 @@ from __future__ import annotations import ssl -from typing import Any, Iterable +import typing from .._exceptions import ReadError from .base import ( @@ -48,7 +48,7 @@ def start_tls( ) -> NetworkStream: return self - def get_extra_info(self, info: str) -> Any: + def get_extra_info(self, info: str) -> typing.Any: return MockSSLObject(http2=self._http2) if info == "ssl_object" else None def __repr__(self) -> str: @@ -66,7 +66,7 @@ def connect_tcp( port: int, timeout: float | None = None, local_address: str | None = None, - socket_options: Iterable[SOCKET_OPTION] | None = None, + socket_options: typing.Iterable[SOCKET_OPTION] | None = None, ) -> NetworkStream: return MockStream(list(self._buffer), http2=self._http2) @@ -74,7 +74,7 @@ def connect_unix_socket( self, path: str, timeout: float | None = None, - socket_options: Iterable[SOCKET_OPTION] | None = None, + socket_options: typing.Iterable[SOCKET_OPTION] | None = None, ) -> NetworkStream: return MockStream(list(self._buffer), http2=self._http2) @@ -109,7 +109,7 @@ async def start_tls( ) -> AsyncNetworkStream: return self - def get_extra_info(self, info: str) -> Any: + def get_extra_info(self, info: str) -> typing.Any: return MockSSLObject(http2=self._http2) if info == "ssl_object" else None def __repr__(self) -> str: @@ -127,7 +127,7 @@ async def connect_tcp( port: int, timeout: float | None = None, local_address: str | None = None, - socket_options: Iterable[SOCKET_OPTION] | None = None, + socket_options: typing.Iterable[SOCKET_OPTION] | None = None, ) -> AsyncNetworkStream: return AsyncMockStream(list(self._buffer), http2=self._http2) @@ -135,7 +135,7 @@ async def connect_unix_socket( self, path: str, timeout: float | None = None, - socket_options: Iterable[SOCKET_OPTION] | None = None, + socket_options: typing.Iterable[SOCKET_OPTION] | None = None, ) -> AsyncNetworkStream: return AsyncMockStream(list(self._buffer), http2=self._http2) diff --git a/httpcore/_backends/sync.py b/httpcore/_backends/sync.py index e9833171..4018a09c 100644 --- a/httpcore/_backends/sync.py +++ b/httpcore/_backends/sync.py @@ -1,10 +1,10 @@ from __future__ import annotations +import functools import socket import ssl import sys import typing -from functools import partial from .._exceptions import ( ConnectError, @@ -81,7 +81,7 @@ def read(self, max_bytes: int, timeout: float | None = None) -> bytes: with map_exceptions(exc_map): self._sock.settimeout(timeout) return typing.cast( - bytes, self._perform_io(partial(self.ssl_obj.read, max_bytes)) + bytes, self._perform_io(functools.partial(self.ssl_obj.read, max_bytes)) ) def write(self, buffer: bytes, timeout: float | None = None) -> None: @@ -89,7 +89,7 @@ def write(self, buffer: bytes, timeout: float | None = None) -> None: with map_exceptions(exc_map): self._sock.settimeout(timeout) while buffer: - nsent = self._perform_io(partial(self.ssl_obj.write, buffer)) + nsent = self._perform_io(functools.partial(self.ssl_obj.write, buffer)) buffer = buffer[nsent:] def close(self) -> None: diff --git a/httpcore/_backends/trio.py b/httpcore/_backends/trio.py index a6b6ab80..6f53f5f2 100644 --- a/httpcore/_backends/trio.py +++ b/httpcore/_backends/trio.py @@ -1,7 +1,7 @@ from __future__ import annotations import ssl -from typing import Any, Iterable +import typing import trio @@ -78,7 +78,7 @@ async def start_tls( raise exc return TrioStream(ssl_stream) - def get_extra_info(self, info: str) -> Any: + def get_extra_info(self, info: str) -> typing.Any: if info == "ssl_object" and isinstance(self._stream, trio.SSLStream): # Type checkers cannot see `_ssl_object` attribute because trio._ssl.SSLStream uses __getattr__/__setattr__. # Tracked at https://github.com/python-trio/trio/issues/542 @@ -113,7 +113,7 @@ async def connect_tcp( port: int, timeout: float | None = None, local_address: str | None = None, - socket_options: Iterable[SOCKET_OPTION] | None = None, + socket_options: typing.Iterable[SOCKET_OPTION] | None = None, ) -> AsyncNetworkStream: # By default for TCP sockets, trio enables TCP_NODELAY. # https://trio.readthedocs.io/en/stable/reference-io.html#trio.SocketStream @@ -138,7 +138,7 @@ async def connect_unix_socket( self, path: str, timeout: float | None = None, - socket_options: Iterable[SOCKET_OPTION] | None = None, + socket_options: typing.Iterable[SOCKET_OPTION] | None = None, ) -> AsyncNetworkStream: # pragma: nocover if socket_options is None: socket_options = [] diff --git a/httpcore/_exceptions.py b/httpcore/_exceptions.py index 81e7fc61..bc28d44f 100644 --- a/httpcore/_exceptions.py +++ b/httpcore/_exceptions.py @@ -1,11 +1,11 @@ import contextlib -from typing import Iterator, Mapping, Type +import typing -ExceptionMapping = Mapping[Type[Exception], Type[Exception]] +ExceptionMapping = typing.Mapping[typing.Type[Exception], typing.Type[Exception]] @contextlib.contextmanager -def map_exceptions(map: ExceptionMapping) -> Iterator[None]: +def map_exceptions(map: ExceptionMapping) -> typing.Iterator[None]: try: yield except Exception as exc: # noqa: PIE786 diff --git a/httpcore/_models.py b/httpcore/_models.py index 0ffd2cd8..48e10317 100644 --- a/httpcore/_models.py +++ b/httpcore/_models.py @@ -1,27 +1,17 @@ from __future__ import annotations -from typing import ( - Any, - AsyncIterable, - AsyncIterator, - Iterable, - Iterator, - Mapping, - MutableMapping, - Sequence, - Tuple, - Union, -) -from urllib.parse import urlparse +import typing +import urllib.parse # Functions for typechecking... -HeadersAsSequence = Sequence[Tuple[Union[bytes, str], Union[bytes, str]]] -HeadersAsMapping = Mapping[Union[bytes, str], Union[bytes, str]] -HeaderTypes = Union[HeadersAsSequence, HeadersAsMapping, None] +ByteOrStr = typing.Union[bytes, str] +HeadersAsSequence = typing.Sequence[typing.Tuple[ByteOrStr, ByteOrStr]] +HeadersAsMapping = typing.Mapping[ByteOrStr, ByteOrStr] +HeaderTypes = typing.Union[HeadersAsSequence, HeadersAsMapping, None] -Extensions = MutableMapping[str, Any] +Extensions = typing.MutableMapping[str, typing.Any] def enforce_bytes(value: bytes | str, *, name: str) -> bytes: @@ -67,7 +57,7 @@ def enforce_headers( """ if value is None: return [] - elif isinstance(value, Mapping): + elif isinstance(value, typing.Mapping): return [ ( enforce_bytes(k, name="header name"), @@ -75,7 +65,7 @@ def enforce_headers( ) for k, v in value.items() ] - elif isinstance(value, Sequence): + elif isinstance(value, typing.Sequence): return [ ( enforce_bytes(k, name="header name"), @@ -91,8 +81,10 @@ def enforce_headers( def enforce_stream( - value: bytes | Iterable[bytes] | AsyncIterable[bytes] | None, *, name: str -) -> Iterable[bytes] | AsyncIterable[bytes]: + value: bytes | typing.Iterable[bytes] | typing.AsyncIterable[bytes] | None, + *, + name: str, +) -> typing.Iterable[bytes] | typing.AsyncIterable[bytes]: if value is None: return ByteStream(b"") elif isinstance(value, bytes): @@ -116,7 +108,7 @@ def include_request_headers( headers: list[tuple[bytes, bytes]], *, url: "URL", - content: None | bytes | Iterable[bytes] | AsyncIterable[bytes], + content: None | bytes | typing.Iterable[bytes] | typing.AsyncIterable[bytes], ) -> list[tuple[bytes, bytes]]: headers_set = set(k.lower() for k, v in headers) @@ -154,10 +146,10 @@ class ByteStream: def __init__(self, content: bytes) -> None: self._content = content - def __iter__(self) -> Iterator[bytes]: + def __iter__(self) -> typing.Iterator[bytes]: yield self._content - async def __aiter__(self) -> AsyncIterator[bytes]: + async def __aiter__(self) -> typing.AsyncIterator[bytes]: yield self._content def __repr__(self) -> str: @@ -170,7 +162,7 @@ def __init__(self, scheme: bytes, host: bytes, port: int) -> None: self.host = host self.port = port - def __eq__(self, other: Any) -> bool: + def __eq__(self, other: typing.Any) -> bool: return ( isinstance(other, Origin) and self.scheme == other.scheme @@ -271,7 +263,7 @@ def __init__( target: The target of the HTTP request. Such as `"/items?search=red"`. """ if url: - parsed = urlparse(enforce_bytes(url, name="url")) + parsed = urllib.parse.urlparse(enforce_bytes(url, name="url")) self.scheme = parsed.scheme self.host = parsed.hostname or b"" self.port = parsed.port @@ -297,7 +289,7 @@ def origin(self) -> Origin: scheme=self.scheme, host=self.host, port=self.port or default_port ) - def __eq__(self, other: Any) -> bool: + def __eq__(self, other: typing.Any) -> bool: return ( isinstance(other, URL) and other.scheme == self.scheme @@ -329,7 +321,10 @@ def __init__( url: URL | bytes | str, *, headers: HeaderTypes = None, - content: bytes | Iterable[bytes] | AsyncIterable[bytes] | None = None, + content: bytes + | typing.Iterable[bytes] + | typing.AsyncIterable[bytes] + | None = None, extensions: Extensions | None = None, ) -> None: """ @@ -348,8 +343,8 @@ def __init__( self.headers: list[tuple[bytes, bytes]] = enforce_headers( headers, name="headers" ) - self.stream: Iterable[bytes] | AsyncIterable[bytes] = enforce_stream( - content, name="content" + self.stream: typing.Iterable[bytes] | typing.AsyncIterable[bytes] = ( + enforce_stream(content, name="content") ) self.extensions = {} if extensions is None else extensions @@ -375,7 +370,10 @@ def __init__( status: int, *, headers: HeaderTypes = None, - content: bytes | Iterable[bytes] | AsyncIterable[bytes] | None = None, + content: bytes + | typing.Iterable[bytes] + | typing.AsyncIterable[bytes] + | None = None, extensions: Extensions | None = None, ) -> None: """ @@ -391,8 +389,8 @@ def __init__( self.headers: list[tuple[bytes, bytes]] = enforce_headers( headers, name="headers" ) - self.stream: Iterable[bytes] | AsyncIterable[bytes] = enforce_stream( - content, name="content" + self.stream: typing.Iterable[bytes] | typing.AsyncIterable[bytes] = ( + enforce_stream(content, name="content") ) self.extensions = {} if extensions is None else extensions @@ -401,7 +399,7 @@ def __init__( @property def content(self) -> bytes: if not hasattr(self, "_content"): - if isinstance(self.stream, Iterable): + if isinstance(self.stream, typing.Iterable): raise RuntimeError( "Attempted to access 'response.content' on a streaming response. " "Call 'response.read()' first." @@ -419,7 +417,7 @@ def __repr__(self) -> str: # Sync interface... def read(self) -> bytes: - if not isinstance(self.stream, Iterable): # pragma: nocover + if not isinstance(self.stream, typing.Iterable): # pragma: nocover raise RuntimeError( "Attempted to read an asynchronous response using 'response.read()'. " "You should use 'await response.aread()' instead." @@ -428,8 +426,8 @@ def read(self) -> bytes: self._content = b"".join([part for part in self.iter_stream()]) return self._content - def iter_stream(self) -> Iterator[bytes]: - if not isinstance(self.stream, Iterable): # pragma: nocover + def iter_stream(self) -> typing.Iterator[bytes]: + if not isinstance(self.stream, typing.Iterable): # pragma: nocover raise RuntimeError( "Attempted to stream an asynchronous response using 'for ... in " "response.iter_stream()'. " @@ -444,7 +442,7 @@ def iter_stream(self) -> Iterator[bytes]: yield chunk def close(self) -> None: - if not isinstance(self.stream, Iterable): # pragma: nocover + if not isinstance(self.stream, typing.Iterable): # pragma: nocover raise RuntimeError( "Attempted to close an asynchronous response using 'response.close()'. " "You should use 'await response.aclose()' instead." @@ -455,7 +453,7 @@ def close(self) -> None: # Async interface... async def aread(self) -> bytes: - if not isinstance(self.stream, AsyncIterable): # pragma: nocover + if not isinstance(self.stream, typing.AsyncIterable): # pragma: nocover raise RuntimeError( "Attempted to read an synchronous response using " "'await response.aread()'. " @@ -465,8 +463,8 @@ async def aread(self) -> bytes: self._content = b"".join([part async for part in self.aiter_stream()]) return self._content - async def aiter_stream(self) -> AsyncIterator[bytes]: - if not isinstance(self.stream, AsyncIterable): # pragma: nocover + async def aiter_stream(self) -> typing.AsyncIterator[bytes]: + if not isinstance(self.stream, typing.AsyncIterable): # pragma: nocover raise RuntimeError( "Attempted to stream an synchronous response using 'async for ... in " "response.aiter_stream()'. " @@ -482,7 +480,7 @@ async def aiter_stream(self) -> AsyncIterator[bytes]: yield chunk async def aclose(self) -> None: - if not isinstance(self.stream, AsyncIterable): # pragma: nocover + if not isinstance(self.stream, typing.AsyncIterable): # pragma: nocover raise RuntimeError( "Attempted to close a synchronous response using " "'await response.aclose()'. " diff --git a/httpcore/_sync/connection.py b/httpcore/_sync/connection.py index 117dfe44..363f8be8 100644 --- a/httpcore/_sync/connection.py +++ b/httpcore/_sync/connection.py @@ -3,8 +3,8 @@ import itertools import logging import ssl -from types import TracebackType -from typing import Iterable, Iterator +import types +import typing from .._backends.sync import SyncBackend from .._backends.base import SOCKET_OPTION, NetworkBackend, NetworkStream @@ -22,7 +22,7 @@ logger = logging.getLogger("httpcore.connection") -def exponential_backoff(factor: float) -> Iterator[float]: +def exponential_backoff(factor: float) -> typing.Iterator[float]: """ Generate a geometric sequence that has a ratio of 2 and starts with 0. @@ -47,7 +47,7 @@ def __init__( local_address: str | None = None, uds: str | None = None, network_backend: NetworkBackend | None = None, - socket_options: Iterable[SOCKET_OPTION] | None = None, + socket_options: typing.Iterable[SOCKET_OPTION] | None = None, ) -> None: self._origin = origin self._ssl_context = ssl_context @@ -217,6 +217,6 @@ def __exit__( self, exc_type: type[BaseException] | None = None, exc_value: BaseException | None = None, - traceback: TracebackType | None = None, + traceback: types.TracebackType | None = None, ) -> None: self.close() diff --git a/httpcore/_sync/connection_pool.py b/httpcore/_sync/connection_pool.py index cf9dda68..00c3983d 100644 --- a/httpcore/_sync/connection_pool.py +++ b/httpcore/_sync/connection_pool.py @@ -2,8 +2,8 @@ import ssl import sys -from types import TracebackType -from typing import Iterable, Iterator, Iterable +import types +import typing from .._backends.sync import SyncBackend from .._backends.base import SOCKET_OPTION, NetworkBackend @@ -57,7 +57,7 @@ def __init__( local_address: str | None = None, uds: str | None = None, network_backend: NetworkBackend | None = None, - socket_options: Iterable[SOCKET_OPTION] | None = None, + socket_options: typing.Iterable[SOCKET_OPTION] | None = None, ) -> None: """ A connection pool for making HTTP requests. @@ -217,7 +217,7 @@ def handle_request(self, request: Request) -> Response: # Return the response. Note that in this case we still have to manage # the point at which the response is closed. - assert isinstance(response.stream, Iterable) + assert isinstance(response.stream, typing.Iterable) return Response( status=response.status, headers=response.headers, @@ -319,7 +319,7 @@ def __exit__( self, exc_type: type[BaseException] | None = None, exc_value: BaseException | None = None, - traceback: TracebackType | None = None, + traceback: types.TracebackType | None = None, ) -> None: self.close() @@ -349,7 +349,7 @@ def __repr__(self) -> str: class PoolByteStream: def __init__( self, - stream: Iterable[bytes], + stream: typing.Iterable[bytes], pool_request: PoolRequest, pool: ConnectionPool, ) -> None: @@ -358,7 +358,7 @@ def __init__( self._pool = pool self._closed = False - def __iter__(self) -> Iterator[bytes]: + def __iter__(self) -> typing.Iterator[bytes]: try: for part in self._stream: yield part diff --git a/httpcore/_sync/http11.py b/httpcore/_sync/http11.py index 5f02f92e..ebd3a974 100644 --- a/httpcore/_sync/http11.py +++ b/httpcore/_sync/http11.py @@ -4,8 +4,8 @@ import logging import ssl import time -from types import TracebackType -from typing import Any, Iterable, Iterator, Union +import types +import typing import h11 @@ -26,7 +26,7 @@ # A subset of `h11.Event` types supported by `_send_event` -H11SendEvent = Union[ +H11SendEvent = typing.Union[ h11.Request, h11.Data, h11.EndOfMessage, @@ -153,7 +153,7 @@ def _send_request_body(self, request: Request) -> None: timeouts = request.extensions.get("timeout", {}) timeout = timeouts.get("write", None) - assert isinstance(request.stream, Iterable) + assert isinstance(request.stream, typing.Iterable) for chunk in request.stream: event = h11.Data(data=chunk) self._send_event(event, timeout=timeout) @@ -193,7 +193,9 @@ def _receive_response_headers( return http_version, event.status_code, event.reason, headers, trailing_data - def _receive_response_body(self, request: Request) -> Iterator[bytes]: + def _receive_response_body( + self, request: Request + ) -> typing.Iterator[bytes]: timeouts = request.extensions.get("timeout", {}) timeout = timeouts.get("read", None) @@ -314,7 +316,7 @@ def __exit__( self, exc_type: type[BaseException] | None = None, exc_value: BaseException | None = None, - traceback: TracebackType | None = None, + traceback: types.TracebackType | None = None, ) -> None: self.close() @@ -325,7 +327,7 @@ def __init__(self, connection: HTTP11Connection, request: Request) -> None: self._request = request self._closed = False - def __iter__(self) -> Iterator[bytes]: + def __iter__(self) -> typing.Iterator[bytes]: kwargs = {"request": self._request} try: with Trace("receive_response_body", logger, self._request, kwargs): @@ -373,5 +375,5 @@ def start_tls( ) -> NetworkStream: return self._stream.start_tls(ssl_context, server_hostname, timeout) - def get_extra_info(self, info: str) -> Any: + def get_extra_info(self, info: str) -> typing.Any: return self._stream.get_extra_info(info) diff --git a/httpcore/_sync/http2.py b/httpcore/_sync/http2.py index c7bbdc89..ca4dd724 100644 --- a/httpcore/_sync/http2.py +++ b/httpcore/_sync/http2.py @@ -4,7 +4,7 @@ import logging import time import types -from typing import Iterable, Iterator +import typing import h2.config import h2.connection @@ -253,7 +253,7 @@ def _send_request_body(self, request: Request, stream_id: int) -> None: if not has_body_headers(request): return - assert isinstance(request.stream, Iterable) + assert isinstance(request.stream, typing.Iterable) for data in request.stream: self._send_stream_data(request, stream_id, data) self._send_end_stream(request, stream_id) @@ -303,7 +303,7 @@ def _receive_response( def _receive_response_body( self, request: Request, stream_id: int - ) -> Iterator[bytes]: + ) -> typing.Iterator[bytes]: """ Iterator that returns the bytes of the response body for a given stream ID. """ @@ -559,7 +559,7 @@ def __init__( self._stream_id = stream_id self._closed = False - def __iter__(self) -> Iterator[bytes]: + def __iter__(self) -> typing.Iterator[bytes]: kwargs = {"request": self._request, "stream_id": self._stream_id} try: with Trace("receive_response_body", logger, self._request, kwargs): diff --git a/httpcore/_sync/http_proxy.py b/httpcore/_sync/http_proxy.py index 390e19ee..e58693ec 100644 --- a/httpcore/_sync/http_proxy.py +++ b/httpcore/_sync/http_proxy.py @@ -1,9 +1,9 @@ from __future__ import annotations +import base64 import logging import ssl -from base64 import b64encode -from typing import Iterable, Mapping, Sequence, Tuple, Union +import typing from .._backends.base import SOCKET_OPTION, NetworkBackend from .._exceptions import ProxyError @@ -24,16 +24,17 @@ from .http11 import HTTP11Connection from .interfaces import ConnectionInterface -HeadersAsSequence = Sequence[Tuple[Union[bytes, str], Union[bytes, str]]] -HeadersAsMapping = Mapping[Union[bytes, str], Union[bytes, str]] +ByteOrStr = typing.Union[bytes, str] +HeadersAsSequence = typing.Sequence[typing.Tuple[ByteOrStr, ByteOrStr]] +HeadersAsMapping = typing.Mapping[ByteOrStr, ByteOrStr] logger = logging.getLogger("httpcore.proxy") def merge_headers( - default_headers: Sequence[tuple[bytes, bytes]] | None = None, - override_headers: Sequence[tuple[bytes, bytes]] | None = None, + default_headers: typing.Sequence[tuple[bytes, bytes]] | None = None, + override_headers: typing.Sequence[tuple[bytes, bytes]] | None = None, ) -> list[tuple[bytes, bytes]]: """ Append default_headers and override_headers, de-duplicating if a key exists @@ -52,7 +53,7 @@ def merge_headers( def build_auth_header(username: bytes, password: bytes) -> bytes: userpass = username + b":" + password - return b"Basic " + b64encode(userpass) + return b"Basic " + base64.b64encode(userpass) class HTTPProxy(ConnectionPool): @@ -76,7 +77,7 @@ def __init__( local_address: str | None = None, uds: str | None = None, network_backend: NetworkBackend | None = None, - socket_options: Iterable[SOCKET_OPTION] | None = None, + socket_options: typing.Iterable[SOCKET_OPTION] | None = None, ) -> None: """ A connection pool for making HTTP requests. @@ -177,7 +178,7 @@ def __init__( proxy_headers: HeadersAsMapping | HeadersAsSequence | None = None, keepalive_expiry: float | None = None, network_backend: NetworkBackend | None = None, - socket_options: Iterable[SOCKET_OPTION] | None = None, + socket_options: typing.Iterable[SOCKET_OPTION] | None = None, proxy_ssl_context: ssl.SSLContext | None = None, ) -> None: self._connection = HTTPConnection( @@ -240,12 +241,12 @@ def __init__( remote_origin: Origin, ssl_context: ssl.SSLContext | None = None, proxy_ssl_context: ssl.SSLContext | None = None, - proxy_headers: Sequence[tuple[bytes, bytes]] | None = None, + proxy_headers: typing.Sequence[tuple[bytes, bytes]] | None = None, keepalive_expiry: float | None = None, http1: bool = True, http2: bool = False, network_backend: NetworkBackend | None = None, - socket_options: Iterable[SOCKET_OPTION] | None = None, + socket_options: typing.Iterable[SOCKET_OPTION] | None = None, ) -> None: self._connection: ConnectionInterface = HTTPConnection( origin=proxy_origin, diff --git a/httpcore/_sync/interfaces.py b/httpcore/_sync/interfaces.py index b7defbae..e673d4cc 100644 --- a/httpcore/_sync/interfaces.py +++ b/httpcore/_sync/interfaces.py @@ -1,7 +1,7 @@ from __future__ import annotations -from contextlib import contextmanager -from typing import Iterator +import contextlib +import typing from .._models import ( URL, @@ -24,7 +24,7 @@ def request( url: URL | bytes | str, *, headers: HeaderTypes = None, - content: bytes | Iterator[bytes] | None = None, + content: bytes | typing.Iterator[bytes] | None = None, extensions: Extensions | None = None, ) -> Response: # Strict type checking on our parameters. @@ -49,16 +49,16 @@ def request( response.close() return response - @contextmanager + @contextlib.contextmanager def stream( self, method: bytes | str, url: URL | bytes | str, *, headers: HeaderTypes = None, - content: bytes | Iterator[bytes] | None = None, + content: bytes | typing.Iterator[bytes] | None = None, extensions: Extensions | None = None, - ) -> Iterator[Response]: + ) -> typing.Iterator[Response]: # Strict type checking on our parameters. method = enforce_bytes(method, name="method") url = enforce_url(url, name="url") diff --git a/httpcore/_sync/socks_proxy.py b/httpcore/_sync/socks_proxy.py index 9b633675..61dd7e38 100644 --- a/httpcore/_sync/socks_proxy.py +++ b/httpcore/_sync/socks_proxy.py @@ -3,7 +3,7 @@ import logging import ssl -from socksio import socks5 +import socksio from .._backends.sync import SyncBackend from .._backends.base import NetworkBackend, NetworkStream @@ -46,22 +46,22 @@ def _init_socks5_connection( port: int, auth: tuple[bytes, bytes] | None = None, ) -> None: - conn = socks5.SOCKS5Connection() + conn = socksio.socks5.SOCKS5Connection() # Auth method request auth_method = ( - socks5.SOCKS5AuthMethod.NO_AUTH_REQUIRED + socksio.socks5.SOCKS5AuthMethod.NO_AUTH_REQUIRED if auth is None - else socks5.SOCKS5AuthMethod.USERNAME_PASSWORD + else socksio.socks5.SOCKS5AuthMethod.USERNAME_PASSWORD ) - conn.send(socks5.SOCKS5AuthMethodsRequest([auth_method])) + conn.send(socksio.socks5.SOCKS5AuthMethodsRequest([auth_method])) outgoing_bytes = conn.data_to_send() stream.write(outgoing_bytes) # Auth method response incoming_bytes = stream.read(max_bytes=4096) response = conn.receive_data(incoming_bytes) - assert isinstance(response, socks5.SOCKS5AuthReply) + assert isinstance(response, socksio.socks5.SOCKS5AuthReply) if response.method != auth_method: requested = AUTH_METHODS.get(auth_method, "UNKNOWN") responded = AUTH_METHODS.get(response.method, "UNKNOWN") @@ -69,25 +69,25 @@ def _init_socks5_connection( f"Requested {requested} from proxy server, but got {responded}." ) - if response.method == socks5.SOCKS5AuthMethod.USERNAME_PASSWORD: + if response.method == socksio.socks5.SOCKS5AuthMethod.USERNAME_PASSWORD: # Username/password request assert auth is not None username, password = auth - conn.send(socks5.SOCKS5UsernamePasswordRequest(username, password)) + conn.send(socksio.socks5.SOCKS5UsernamePasswordRequest(username, password)) outgoing_bytes = conn.data_to_send() stream.write(outgoing_bytes) # Username/password response incoming_bytes = stream.read(max_bytes=4096) response = conn.receive_data(incoming_bytes) - assert isinstance(response, socks5.SOCKS5UsernamePasswordReply) + assert isinstance(response, socksio.socks5.SOCKS5UsernamePasswordReply) if not response.success: raise ProxyError("Invalid username/password") # Connect request conn.send( - socks5.SOCKS5CommandRequest.from_address( - socks5.SOCKS5Command.CONNECT, (host, port) + socksio.socks5.SOCKS5CommandRequest.from_address( + socksio.socks5.SOCKS5Command.CONNECT, (host, port) ) ) outgoing_bytes = conn.data_to_send() @@ -96,8 +96,8 @@ def _init_socks5_connection( # Connect response incoming_bytes = stream.read(max_bytes=4096) response = conn.receive_data(incoming_bytes) - assert isinstance(response, socks5.SOCKS5Reply) - if response.reply_code != socks5.SOCKS5ReplyCode.SUCCEEDED: + assert isinstance(response, socksio.socks5.SOCKS5Reply) + if response.reply_code != socksio.socks5.SOCKS5ReplyCode.SUCCEEDED: reply_code = REPLY_CODES.get(response.reply_code, "UNKOWN") raise ProxyError(f"Proxy Server could not connect: {reply_code}.") diff --git a/httpcore/_synchronization.py b/httpcore/_synchronization.py index 189f2c21..2ecc9e9c 100644 --- a/httpcore/_synchronization.py +++ b/httpcore/_synchronization.py @@ -1,7 +1,7 @@ from __future__ import annotations import threading -from types import TracebackType +import types from ._exceptions import ExceptionMapping, PoolTimeout, map_exceptions @@ -82,7 +82,7 @@ async def __aexit__( self, exc_type: type[BaseException] | None = None, exc_value: BaseException | None = None, - traceback: TracebackType | None = None, + traceback: types.TracebackType | None = None, ) -> None: if self._backend == "trio": self._trio_lock.release() @@ -105,7 +105,7 @@ def __exit__( self, exc_type: type[BaseException] | None = None, exc_value: BaseException | None = None, - traceback: TracebackType | None = None, + traceback: types.TracebackType | None = None, ) -> None: pass @@ -218,7 +218,7 @@ def __exit__( self, exc_type: type[BaseException] | None = None, exc_value: BaseException | None = None, - traceback: TracebackType | None = None, + traceback: types.TracebackType | None = None, ) -> None: if self._backend == "trio": self._trio_shield.__exit__(exc_type, exc_value, traceback) @@ -248,7 +248,7 @@ def __exit__( self, exc_type: type[BaseException] | None = None, exc_value: BaseException | None = None, - traceback: TracebackType | None = None, + traceback: types.TracebackType | None = None, ) -> None: self._lock.release() @@ -272,7 +272,7 @@ def __exit__( self, exc_type: type[BaseException] | None = None, exc_value: BaseException | None = None, - traceback: TracebackType | None = None, + traceback: types.TracebackType | None = None, ) -> None: self._lock.release() @@ -313,6 +313,6 @@ def __exit__( self, exc_type: type[BaseException] | None = None, exc_value: BaseException | None = None, - traceback: TracebackType | None = None, + traceback: types.TracebackType | None = None, ) -> None: pass diff --git a/httpcore/_trace.py b/httpcore/_trace.py index 3a58b79c..5f1cd7c4 100644 --- a/httpcore/_trace.py +++ b/httpcore/_trace.py @@ -2,8 +2,8 @@ import inspect import logging -from types import TracebackType -from typing import Any +import types +import typing from ._models import Request @@ -14,7 +14,7 @@ def __init__( name: str, logger: logging.Logger, request: Request | None = None, - kwargs: dict[str, Any] | None = None, + kwargs: dict[str, typing.Any] | None = None, ) -> None: self.name = name self.logger = logger @@ -23,11 +23,11 @@ def __init__( ) self.debug = self.logger.isEnabledFor(logging.DEBUG) self.kwargs = kwargs or {} - self.return_value: Any = None + self.return_value: typing.Any = None self.should_trace = self.debug or self.trace_extension is not None self.prefix = self.logger.name.split(".")[-1] - def trace(self, name: str, info: dict[str, Any]) -> None: + def trace(self, name: str, info: dict[str, typing.Any]) -> None: if self.trace_extension is not None: prefix_and_name = f"{self.prefix}.{name}" ret = self.trace_extension(prefix_and_name, info) @@ -56,7 +56,7 @@ def __exit__( self, exc_type: type[BaseException] | None = None, exc_value: BaseException | None = None, - traceback: TracebackType | None = None, + traceback: types.TracebackType | None = None, ) -> None: if self.should_trace: if exc_value is None: @@ -66,7 +66,7 @@ def __exit__( info = {"exception": exc_value} self.trace(f"{self.name}.failed", info) - async def atrace(self, name: str, info: dict[str, Any]) -> None: + async def atrace(self, name: str, info: dict[str, typing.Any]) -> None: if self.trace_extension is not None: prefix_and_name = f"{self.prefix}.{name}" coro = self.trace_extension(prefix_and_name, info) @@ -96,7 +96,7 @@ async def __aexit__( self, exc_type: type[BaseException] | None = None, exc_value: BaseException | None = None, - traceback: TracebackType | None = None, + traceback: types.TracebackType | None = None, ) -> None: if self.should_trace: if exc_value is None: