Typing cleanup

- Compatibility with older Python versions
  - use `Optional` and `Union` instead of `... | None` and `a | b`
  - use `typing_extensions.Protocol` instead of `typing.Protocol`
  - use `typing.Dict`, `typing.List`, etc. instead of the concrete types.

- Fix backend `.get()` annotations; not all were marked as `Optional[str]`
- Don't return anything from `Backend.set()` methods.
- The `Coder.decode_as_type()` type parameter must be a type to be
  compatible with `ModelField(..., type_=...)`.
- Clean up `Optional[]` use, remove where it is not needed.
- Clean up variable use in decorator, keeping the raw cached value
  separate from the return value from the wrapped endpoint.
- Annotate the wrapper as returning either the original type _or_ a
  Response (returning a 304 Not Modified response).
- Clean up small edge-case where `response` could be `None`.
- Correct type annotation on `JsonCoder.decode()` to match `Coder.decode()`.
This commit is contained in:
Martijn Pieters
2023-05-09 15:30:46 +01:00
parent 564026e189
commit 013be85f97
8 changed files with 46 additions and 42 deletions

View File

@@ -1,5 +1,5 @@
import hashlib
from typing import Any, Callable, Optional
from typing import Any, Callable, Dict, Optional, Tuple
from starlette.requests import Request
from starlette.responses import Response
@@ -10,8 +10,8 @@ def default_key_builder(
namespace: str = "",
request: Optional[Request] = None,
response: Optional[Response] = None,
args: Optional[tuple[Any, ...]] = None,
kwargs: Optional[dict[str, Any]] = None,
args: Optional[Tuple[Any, ...]] = None,
kwargs: Optional[Dict[str, Any]] = None,
) -> str:
cache_key = hashlib.md5( # nosec:B303
f"{func.__module__}:{func.__name__}:{args}:{kwargs}".encode()