Typing: always fill in generic type parameters (#2468)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* Typing: always fill in generic type parameters Being explicit about the parameters helps find bugs and makes the library easier to use for users. - Tell mypy to disallow generics without parameter values - Give all generic types parameters values * fix things that aren't coming in from other commits * lint
authored by Adrian Garcia Badaracco · committed by GitHub · parent 16e2830 · Browse files · 10 files·+39 added−18 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Trailers
- Co-authored-by: Martijn Pieters <mj@zopatista.com>
- Co-authored-by: Tom Christie <tom@tomchristie.com>
Diff stats
10 files+39 added−18 removed
- tests:+2 added−2 removed
- other:+37 added−16 removed
Provenance
- Commit
1b4e7fb- Tree
dc74e3d- Author
Adrian Garcia Badaracco <1755071+adriangb@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent
16e2830
10 files changed+39 added−18 removed
modified:httpx/_transports/asgi.py+13 added-3 removed
12 unmodified lines13 14 Event = typing.Union[asyncio.Event, trio.Event]15 16 17+_Message = typing.Dict[str, typing.Any]18+_Receive = typing.Callable[[], typing.Awaitable[_Message]]19+_Send = typing.Callable[20+ [typing.Dict[str, typing.Any]], typing.Coroutine[None, None, None]21+]22+_ASGIApp = typing.Callable[23+ [typing.Dict[str, typing.Any], _Receive, _Send], typing.Coroutine[None, None, None]24+]25+26+27 def create_event() -> "Event":28 if sniffio.current_async_library() == "trio":29 import trio30 46 unmodified lines77 """78 79 def __init__(80 self,71- app: typing.Callable,81+ app: _ASGIApp,82 raise_app_exceptions: bool = True,83 root_path: str = "",84 client: typing.Tuple[str, int] = ("127.0.0.1", 123),85 ) -> None:36 unmodified lines122 response_complete = create_event()123 124 # ASGI callables.125 116- async def receive() -> dict:126+ async def receive() -> typing.Dict[str, typing.Any]:127 nonlocal request_complete128 129 if request_complete:130 await response_complete.wait()5 unmodified lines136 request_complete = True137 return {"type": "http.request", "body": b"", "more_body": False}138 return {"type": "http.request", "body": body, "more_body": True}139 130- async def send(message: dict) -> None:140+ async def send(message: typing.Dict[str, typing.Any]) -> None:141 nonlocal status_code, response_headers, response_started142 143 if message["type"] == "http.response.start":144 assert not response_started29 unmodified linesmodified:httpx/_transports/mock.py+2 added-2 removed
4 unmodified lines5 from .base import AsyncBaseTransport, BaseTransport6 7 8 class MockTransport(AsyncBaseTransport, BaseTransport):9- def __init__(self, handler: typing.Callable) -> None:9+ def __init__(self, handler: typing.Callable[[Request], Response]) -> None:10 self.handler = handler11 12 def handle_request(13 self,14 unmodified lines28 # return the result.29 30 # https://simonwillison.net/2020/Sep/2/await-me-maybe/31 if asyncio.iscoroutine(response):32- response = await response32+ response = await response # type: ignore[func-returns-value,assignment]33 34 return responsemodified:httpx/_transports/wsgi.py+5 added-3 removed
6 unmodified lines7 from .._types import SyncByteStream8 from .base import BaseTransport9 10 11-def _skip_leading_empty_chunks(body: typing.Iterable) -> typing.Iterable:11+def _skip_leading_empty_chunks(body: typing.Iterable[bytes]) -> typing.Iterable[bytes]:12 body = iter(body)13 for chunk in body:14 if chunk:15 return itertools.chain([chunk], body)48 unmodified lines64 """65 66 def __init__(67 self,68- app: typing.Callable,68+ app: typing.Callable[..., typing.Any],69 raise_app_exceptions: bool = True,70 script_name: str = "",71 remote_addr: str = "127.0.0.1",72 wsgi_errors: typing.Optional[typing.TextIO] = None,35 unmodified lines108 seen_response_headers = None109 seen_exc_info = None110 111 def start_response(112- status: str, response_headers: list, exc_info: typing.Any = None112+ status: str,113+ response_headers: typing.List[typing.Tuple[str, str]],114+ exc_info: typing.Any = None,115 ) -> None:116 nonlocal seen_status, seen_response_headers, seen_exc_info117 seen_status = status118 seen_response_headers = response_headers18 unmodified linesmodified:httpx/_auth.py+4 added-1 removed
8 unmodified lines9 from ._exceptions import ProtocolError10 from ._models import Request, Response11 from ._utils import to_bytes, to_str, unquote12 13+if typing.TYPE_CHECKING: # pragma: no cover14+ from hashlib import _Hash15 16+17 class Auth:18 """19 Base class for all authentication schemes.20 120 unmodified lines141 return f"Basic {token}"142 143 144 class DigestAuth(Auth):142- _ALGORITHM_TO_HASH_FUNCTION: typing.Dict[str, typing.Callable] = {145+ _ALGORITHM_TO_HASH_FUNCTION: typing.Dict[str, typing.Callable[[bytes], "_Hash"]] = {146 "MD5": hashlib.md5,147 "MD5-SESS": hashlib.md5,148 "SHA": hashlib.sha1,149 "SHA-SESS": hashlib.sha1,158 unmodified linesmodified:httpx/_main.py+6 added-1 removed
177 unmodified lines178 else:179 console.print(f"<{len(response.content)} bytes of binary data>")180 181 182+_PCTRTT = typing.Tuple[typing.Tuple[str, str], ...]183+_PCTRTTT = typing.Tuple[_PCTRTT, ...]184+_PeerCertRetDictType = typing.Dict[str, typing.Union[str, _PCTRTTT, _PCTRTT]]185+186+182-def format_certificate(cert: dict) -> str: # pragma: no cover187+def format_certificate(cert: _PeerCertRetDictType) -> str: # pragma: no cover188 lines = []189 for key, value in cert.items():190 if isinstance(value, (list, tuple)):191 lines.append(f"* {key}:")313 unmodified linesmodified:httpx/_models.py+2 added-2 removed
1 unmodified line2 import email.message3 import json as jsonlib4 import typing5 import urllib.request6-from collections.abc import Mapping, MutableMapping6+from collections.abc import Mapping7 from http.cookiejar import Cookie, CookieJar8 9 from ._content import ByteStream, UnattachedStream, encode_request, encode_response10 from ._decoders import (990 unmodified lines1001 with request_context(request=self._request):1002 await self.stream.aclose()1003 1004 1005-class Cookies(MutableMapping):1005+class Cookies(typing.MutableMapping[str, str]):1006 """1007 HTTP Cookies, as a mutable mapping.1008 """1009 196 unmodified linesmodified:httpx/_urls.py+3 added-3 removed
568 unmodified lines569 str(k): [primitive_value_to_str(item) for item in v]570 for k, v in dict_value.items()571 }572 573- def keys(self) -> typing.KeysView:573+ def keys(self) -> typing.KeysView[str]:574 """575 Return all the keys in the query params.576 577 Usage:2 unmodified lines580 assert list(q.keys()) == ["a", "b"]581 """582 return self._dict.keys()583 584- def values(self) -> typing.ValuesView:584+ def values(self) -> typing.ValuesView[str]:585 """586 Return all the values in the query params. If a key occurs more than once587 only the first item for that key is returned.588 3 unmodified lines592 assert list(q.values()) == ["123", "789"]593 """594 return {k: v[0] for k, v in self._dict.items()}.values()595 596- def items(self) -> typing.ItemsView:596+ def items(self) -> typing.ItemsView[str, str]:597 """598 Return all items in the query params. If a key occurs more than once599 only the first item for that key is returned.600 151 unmodified linesmodified:httpx/_utils.py+1 added-1 removed
506 unmodified lines507 return False508 return True509 510 @property511- def priority(self) -> tuple:511+ def priority(self) -> typing.Tuple[int, int, int]:512 """513 The priority allows URLPattern instances to be sortable, so that514 we can match from most specific to least specific.515 """16 unmodified linesmodified:tests/client/test_auth.py+2 added-2 removed
426 unmodified lines427 428 assert response.status_code == 200429 assert len(response.history) == 1430 431- authorization = typing.cast(dict, response.json())["auth"]431+ authorization = typing.cast(typing.Dict[str, typing.Any], response.json())["auth"]432 scheme, _, fields = authorization.partition(" ")433 assert scheme == "Digest"434 435 response_fields = [field.strip() for field in fields.split(",")]22 unmodified lines458 459 assert response.status_code == 200460 assert len(response.history) == 1461 462- authorization = typing.cast(dict, response.json())["auth"]462+ authorization = typing.cast(typing.Dict[str, typing.Any], response.json())["auth"]463 scheme, _, fields = authorization.partition(" ")464 assert scheme == "Digest"465 466 response_fields = [field.strip() for field in fields.split(",")]240 unmodified linesmodified:setup.cfg+1 added
2 unmodified lines3 max-line-length = 1204 5 [mypy]6 disallow_untyped_defs = True7+disallow_any_generics = True8 ignore_missing_imports = True9 no_implicit_optional = True10 show_error_codes = True11 20 unmodified lines