Skip to content
Myr

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

10 files+39 added−18 removed

modified:httpx/_transports/asgi.py+13 added-3 removed
12 unmodified lines
1314 Event = typing.Union[asyncio.Event, trio.Event]151617_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]252627def create_event() -> "Event":28 if sniffio.current_async_library() == "trio":29 import trio30
46 unmodified lines
77 """7879 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 lines
122 response_complete = create_event()123124 # ASGI callables.125116 async def receive() -> dict:126 async def receive() -> typing.Dict[str, typing.Any]:127 nonlocal request_complete128129 if request_complete:130 await response_complete.wait()
5 unmodified lines
136 request_complete = True137 return {"type": "http.request", "body": b"", "more_body": False}138 return {"type": "http.request", "body": body, "more_body": True}139130 async def send(message: dict) -> None:140 async def send(message: typing.Dict[str, typing.Any]) -> None:141 nonlocal status_code, response_headers, response_started142143 if message["type"] == "http.response.start":144 assert not response_started
29 unmodified lines
modified:httpx/_transports/mock.py+2 added-2 removed
4 unmodified lines
5from .base import AsyncBaseTransport, BaseTransport678class MockTransport(AsyncBaseTransport, BaseTransport):9 def __init__(self, handler: typing.Callable) -> None:9 def __init__(self, handler: typing.Callable[[Request], Response]) -> None:10 self.handler = handler1112 def handle_request(13 self,
14 unmodified lines
28 # return the result.2930 # 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]3334 return response
modified:httpx/_transports/wsgi.py+5 added-3 removed
6 unmodified lines
7from .._types import SyncByteStream8from .base import BaseTransport91011def _skip_leading_empty_chunks(body: typing.Iterable) -> typing.Iterable:11def _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 lines
64 """6566 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 lines
108 seen_response_headers = None109 seen_exc_info = None110111 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_headers
18 unmodified lines
modified:httpx/_auth.py+4 added-1 removed
8 unmodified lines
9from ._exceptions import ProtocolError10from ._models import Request, Response11from ._utils import to_bytes, to_str, unquote1213if typing.TYPE_CHECKING: # pragma: no cover14 from hashlib import _Hash151617class Auth:18 """19 Base class for all authentication schemes.20
120 unmodified lines
141 return f"Basic {token}"142143144class 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 lines
modified:httpx/_main.py+6 added-1 removed
177 unmodified lines
178 else:179 console.print(f"<{len(response.content)} bytes of binary data>")180181182_PCTRTT = typing.Tuple[typing.Tuple[str, str], ...]183_PCTRTTT = typing.Tuple[_PCTRTT, ...]184_PeerCertRetDictType = typing.Dict[str, typing.Union[str, _PCTRTTT, _PCTRTT]]185186182def format_certificate(cert: dict) -> str: # pragma: no cover187def 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 lines
modified:httpx/_models.py+2 added-2 removed
1 unmodified line
2import email.message3import json as jsonlib4import typing5import urllib.request6from collections.abc import Mapping, MutableMapping6from collections.abc import Mapping7from http.cookiejar import Cookie, CookieJar89from ._content import ByteStream, UnattachedStream, encode_request, encode_response10from ._decoders import (
990 unmodified lines
1001 with request_context(request=self._request):1002 await self.stream.aclose()100310041005class Cookies(MutableMapping):1005class Cookies(typing.MutableMapping[str, str]):1006 """1007 HTTP Cookies, as a mutable mapping.1008 """1009
196 unmodified lines
modified:httpx/_urls.py+3 added-3 removed
568 unmodified lines
569 str(k): [primitive_value_to_str(item) for item in v]570 for k, v in dict_value.items()571 }572573 def keys(self) -> typing.KeysView:573 def keys(self) -> typing.KeysView[str]:574 """575 Return all the keys in the query params.576577 Usage:
2 unmodified lines
580 assert list(q.keys()) == ["a", "b"]581 """582 return self._dict.keys()583584 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 lines
592 assert list(q.values()) == ["123", "789"]593 """594 return {k: v[0] for k, v in self._dict.items()}.values()595596 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 lines
modified:httpx/_utils.py+1 added-1 removed
506 unmodified lines
507 return False508 return True509510 @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 lines
modified:tests/client/test_auth.py+2 added-2 removed
426 unmodified lines
427428 assert response.status_code == 200429 assert len(response.history) == 1430431 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"434435 response_fields = [field.strip() for field in fields.split(",")]
22 unmodified lines
458459 assert response.status_code == 200460 assert len(response.history) == 1461462 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"465466 response_fields = [field.strip() for field in fields.split(",")]
240 unmodified lines
modified:setup.cfg+1 added
2 unmodified lines
3max-line-length = 12045[mypy]6disallow_untyped_defs = True7disallow_any_generics = True8ignore_missing_imports = True9no_implicit_optional = True10show_error_codes = True11
20 unmodified lines