typing: Broaden type annotations for QuerySet compatibility.

To explain the rationale of this change, for example, there is
`get_user_activity_summary` which accepts either a `Collection[UserActivity]`,
where `QuerySet[T]` is not strictly `Sequence[T]` because its slicing behavior
is different from the `Protocol`, making `Collection` necessary.

Similarily, we should have `Iterable[T]` instead of `List[T]` so that
`QuerySet[T]` will also be an acceptable subtype, or `Sequence[T]` when we
also expect it to be indexed.

Signed-off-by: Zixuan James Li <p359101898@gmail.com>
This commit is contained in:
Zixuan James Li
2022-06-23 14:07:19 -04:00
committed by Tim Abbott
parent 40fcf5a633
commit ab1bbdda65
18 changed files with 65 additions and 41 deletions

View File

@@ -1,7 +1,7 @@
import re
from datetime import datetime
from html import escape
from typing import Any, Dict, List, Optional, Sequence
from typing import Any, Collection, Dict, List, Optional, Sequence
import pytz
from django.conf import settings
@@ -11,6 +11,8 @@ from django.template import loader
from django.urls import reverse
from markupsafe import Markup as mark_safe
from zerver.models import UserActivity
eastern_tz = pytz.timezone("US/Eastern")
@@ -84,7 +86,7 @@ def remote_installation_stats_link(server_id: int, hostname: str) -> mark_safe:
return mark_safe(stats_link)
def get_user_activity_summary(records: List[QuerySet]) -> Dict[str, Any]:
def get_user_activity_summary(records: Collection[UserActivity]) -> Dict[str, Any]:
#: The type annotation used above is clearly overly permissive.
#: We should perhaps use TypedDict to clearly lay out the schema
#: for the user activity summary.
@@ -104,8 +106,9 @@ def get_user_activity_summary(records: List[QuerySet]) -> Dict[str, Any]:
)
if records:
summary["name"] = records[0].user_profile.full_name
summary["user_profile_id"] = records[0].user_profile.id
first_record = next(iter(records))
summary["name"] = first_record.user_profile.full_name
summary["user_profile_id"] = first_record.user_profile.id
for record in records:
client = record.client.name