Skip to content

armgit / zulip

Public Imported from GitHub
0

Zulip server and web application. Open-source team chat that helps teams stay productive and focused.

typing: Broaden type annotations for QuerySet compatibility.

Zixuan James Liab1bbdda6527
diff --git a/analytics/views/activity_common.py b/analytics/views/activity_common.py
index c6cf762aac1..9e1ad68553c 100644
--- a/analytics/views/activity_common.py
+++ b/analytics/views/activity_common.py
@@ -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
diff --git a/zerver/actions/custom_profile_fields.py b/zerver/actions/custom_profile_fields.py
index 11ae58cad5e..a6c5377bbe0 100644
--- a/zerver/actions/custom_profile_fields.py
+++ b/zerver/actions/custom_profile_fields.py
@@ -1,4 +1,4 @@
-from typing import Dict, List, Optional, Union
+from typing import Dict, Iterable, List, Optional, Union
import orjson
from django.db import transaction
@@ -96,7 +96,7 @@ def try_update_realm_custom_profile_field(
notify_realm_custom_profile_fields(realm)
-def try_reorder_realm_custom_profile_fields(realm: Realm, order: List[int]) -> None:
+def try_reorder_realm_custom_profile_fields(realm: Realm, order: Iterable[int]) -> None:
order_mapping = {_[1]: _[0] for _ in enumerate(order)}
custom_profile_fields = CustomProfileField.objects.filter(realm=realm)
for custom_profile_field in custom_profile_fields:
diff --git a/zerver/actions/default_streams.py b/zerver/actions/default_streams.py
index dba7608c706..76c966e33cd 100644
--- a/zerver/actions/default_streams.py
+++ b/zerver/actions/default_streams.py
@@ -1,4 +1,4 @@
-from typing import Any, Dict, List
+from typing import Any, Dict, Iterable, List
from django.db import transaction
from django.utils.translation import gettext as _
@@ -188,5 +188,7 @@ def streams_to_dicts_sorted(streams: List[Stream]) -> List[APIStreamDict]:
return sorted((stream.to_dict() for stream in streams), key=lambda elt: elt["name"])
-def default_stream_groups_to_dicts_sorted(groups: List[DefaultStreamGroup]) -> List[Dict[str, Any]]:
+def default_stream_groups_to_dicts_sorted(
+ groups: Iterable[DefaultStreamGroup],
+) -> List[Dict[str, Any]]:
return sorted((group.to_dict() for group in groups), key=lambda elt: elt["name"])
diff --git a/zerver/actions/message_send.py b/zerver/actions/message_send.py
index 19cd1443ce3..b517dba28ab 100644
--- a/zerver/actions/message_send.py
+++ b/zerver/actions/message_send.py
@@ -182,7 +182,7 @@ def get_recipient_info(
if recipient.type == Recipient.PERSONAL:
# The sender and recipient may be the same id, so
# de-duplicate using a set.
- message_to_user_ids = list({recipient.type_id, sender_id})
+ message_to_user_ids: Collection[int] = list({recipient.type_id, sender_id})
assert len(message_to_user_ids) in [1, 2]
elif recipient.type == Recipient.STREAM:
diff --git a/zerver/lib/digest.py b/zerver/lib/digest.py
index 60211de8c6b..e73ea162399 100644
--- a/zerver/lib/digest.py
+++ b/zerver/lib/digest.py
@@ -2,7 +2,7 @@ import datetime
import heapq
import logging
from collections import defaultdict
-from typing import Any, Dict, List, Set, Tuple
+from typing import Any, Collection, Dict, List, Set, Tuple
from django.conf import settings
from django.db import transaction
@@ -276,10 +276,12 @@ def get_slim_stream_map(stream_ids: Set[int]) -> Dict[int, Stream]:
return {stream.id: stream for stream in streams}
-def bulk_get_digest_context(users: List[UserProfile], cutoff: float) -> Dict[int, Dict[str, Any]]:
+def bulk_get_digest_context(
+ users: Collection[UserProfile], cutoff: float
+) -> Dict[int, Dict[str, Any]]:
# We expect a non-empty list of users all from the same realm.
assert users
- realm = users[0].realm
+ realm = next(iter(users)).realm
for user in users:
assert user.realm_id == realm.id
diff --git a/zerver/lib/export.py b/zerver/lib/export.py
index e27dc6e4906..c6ec862555b 100644
--- a/zerver/lib/export.py
+++ b/zerver/lib/export.py
@@ -14,7 +14,7 @@ import shutil
import subprocess
import tempfile
from functools import lru_cache
-from typing import Any, Callable, Dict, List, Optional, Set, Tuple, TypedDict
+from typing import Any, Callable, Dict, Iterable, List, Mapping, Optional, Set, Tuple, TypedDict
import orjson
from django.apps import apps
@@ -1199,7 +1199,7 @@ def export_partial_message_files(
if output_dir is None:
output_dir = tempfile.mkdtemp(prefix="zulip-export")
- def get_ids(records: List[Record]) -> Set[int]:
+ def get_ids(records: Iterable[Mapping[str, Any]]) -> Set[int]:
return {x["id"] for x in records}
# Basic security rule: You can export everything either...
diff --git a/zerver/lib/management.py b/zerver/lib/management.py
index 83a45c93022..a6a54b35e23 100644
--- a/zerver/lib/management.py
+++ b/zerver/lib/management.py
@@ -2,7 +2,7 @@
import logging
from argparse import ArgumentParser, RawTextHelpFormatter
from dataclasses import dataclass
-from typing import Any, Dict, List, Optional
+from typing import Any, Collection, Dict, Optional
from django.conf import settings
from django.core import validators
@@ -116,7 +116,7 @@ server via `ps -ef` or reading bash history. Prefer
realm: Optional[Realm],
is_bot: Optional[bool] = None,
include_deactivated: bool = False,
- ) -> List[UserProfile]:
+ ) -> Collection[UserProfile]:
if "all_users" in options:
all_users = options["all_users"]
diff --git a/zerver/lib/message.py b/zerver/lib/message.py
index 0d4a0cb178e..800d90a63f8 100644
--- a/zerver/lib/message.py
+++ b/zerver/lib/message.py
@@ -2,7 +2,19 @@ import copy
import datetime
import zlib
from dataclasses import dataclass, field
-from typing import Any, Dict, List, Mapping, Optional, Sequence, Set, Tuple, TypedDict, Union
+from typing import (
+ Any,
+ Collection,
+ Dict,
+ List,
+ Mapping,
+ Optional,
+ Sequence,
+ Set,
+ Tuple,
+ TypedDict,
+ Union,
+)
import ahocorasick
import orjson
@@ -835,7 +847,7 @@ def has_message_access(
def bulk_access_messages(
- user_profile: UserProfile, messages: Sequence[Message], *, stream: Optional[Stream] = None
+ user_profile: UserProfile, messages: Collection[Message], *, stream: Optional[Stream] = None
) -> List[Message]:
"""This function does the full has_message_access check for each
message. If stream is provided, it is used to avoid unnecessary
diff --git a/zerver/lib/retention.py b/zerver/lib/retention.py
index 8338cdb05b9..ec8478d10a1 100644
--- a/zerver/lib/retention.py
+++ b/zerver/lib/retention.py
@@ -29,7 +29,7 @@
import logging
import time
from datetime import timedelta
-from typing import Any, Dict, List, Mapping, Optional, Tuple, Type, Union
+from typing import Any, Dict, Iterable, List, Mapping, Optional, Tuple, Type, Union
from django.conf import settings
from django.db import connection, transaction
@@ -629,7 +629,7 @@ def restore_data_from_archive(archive_transaction: ArchiveTransaction) -> int:
def restore_data_from_archive_by_transactions(
- archive_transactions: List[ArchiveTransaction],
+ archive_transactions: Iterable[ArchiveTransaction],
) -> int:
# Looping over the list of ids means we're batching the restoration process by the size of the
# transactions:
diff --git a/zerver/lib/send_email.py b/zerver/lib/send_email.py
index f53ab0f80cf..e26feacc20a 100644
--- a/zerver/lib/send_email.py
+++ b/zerver/lib/send_email.py
@@ -7,7 +7,7 @@ from email.headerregistry import Address
from email.parser import Parser
from email.policy import default
from email.utils import formataddr, parseaddr
-from typing import Any, Dict, List, Mapping, Optional, Sequence, Tuple, Union
+from typing import Any, Dict, Iterable, List, Mapping, Optional, Sequence, Tuple, Union
import backoff
import orjson
@@ -497,7 +497,7 @@ def get_header(option: Optional[str], header: Optional[str], name: str) -> str:
def send_custom_email(
- users: List[UserProfile], *, target_emails: Sequence[str] = [], options: Dict[str, Any]
+ users: Iterable[UserProfile], *, target_emails: Sequence[str] = [], options: Dict[str, Any]
) -> None:
"""
Helper for `manage.py send_custom_email`.
diff --git a/zerver/lib/soft_deactivation.py b/zerver/lib/soft_deactivation.py
index c6714e4049d..74d38dec79c 100644
--- a/zerver/lib/soft_deactivation.py
+++ b/zerver/lib/soft_deactivation.py
@@ -1,11 +1,12 @@
# Documented in https://zulip.readthedocs.io/en/latest/subsystems/sending-messages.html#soft-deactivation
import logging
from collections import defaultdict
-from typing import Any, DefaultDict, Dict, List, Optional, Set, TypedDict, Union
+from typing import Any, DefaultDict, Dict, Iterable, List, Optional, Sequence, Set, TypedDict, Union
from django.conf import settings
from django.db import transaction
from django.db.models import Max
+from django.db.models.query import QuerySet
from django.utils.timezone import now as timezone_now
from sentry_sdk import capture_exception
@@ -259,7 +260,9 @@ def do_soft_deactivate_user(user_profile: UserProfile) -> None:
logger.info("Soft deactivated user %s", user_profile.id)
-def do_soft_deactivate_users(users: List[UserProfile]) -> List[UserProfile]:
+def do_soft_deactivate_users(
+ users: Union[Sequence[UserProfile], QuerySet[UserProfile]]
+) -> List[UserProfile]:
BATCH_SIZE = 100
users_soft_deactivated = []
while True:
@@ -346,7 +349,7 @@ def get_users_for_soft_deactivation(
return users_to_deactivate
-def do_soft_activate_users(users: List[UserProfile]) -> List[UserProfile]:
+def do_soft_activate_users(users: Iterable[UserProfile]) -> List[UserProfile]:
users_soft_activated = []
for user_profile in users:
user_activated = reactivate_user_if_soft_deactivated(user_profile)
@@ -355,7 +358,7 @@ def do_soft_activate_users(users: List[UserProfile]) -> List[UserProfile]:
return users_soft_activated
-def do_catch_up_soft_deactivated_users(users: List[UserProfile]) -> List[UserProfile]:
+def do_catch_up_soft_deactivated_users(users: Iterable[UserProfile]) -> List[UserProfile]:
users_caught_up = []
failures = []
for user_profile in users:
diff --git a/zerver/lib/stream_subscription.py b/zerver/lib/stream_subscription.py
index 5c24d799b74..11a686fc921 100644
--- a/zerver/lib/stream_subscription.py
+++ b/zerver/lib/stream_subscription.py
@@ -2,7 +2,7 @@ import itertools
from collections import defaultdict
from dataclasses import dataclass
from operator import itemgetter
-from typing import AbstractSet, Any, Dict, List, Optional, Set
+from typing import AbstractSet, Any, Collection, Dict, List, Optional, Set
from django.db.models import Q, QuerySet
@@ -164,7 +164,7 @@ def get_user_ids_for_streams(stream_ids: Set[int]) -> Dict[int, Set[int]]:
def bulk_get_subscriber_peer_info(
realm: Realm,
- streams: List[Stream],
+ streams: Collection[Stream],
) -> SubscriberPeerInfo:
"""
Glossary:
diff --git a/zerver/lib/users.py b/zerver/lib/users.py
index bf14923d82d..00e9450e5a8 100644
--- a/zerver/lib/users.py
+++ b/zerver/lib/users.py
@@ -1,7 +1,7 @@
import re
import unicodedata
from collections import defaultdict
-from typing import Any, Dict, List, Optional, Sequence, TypedDict, Union, cast
+from typing import Any, Dict, Iterable, List, Optional, Sequence, TypedDict, Union, cast
import dateutil.parser as date_parser
from django.conf import settings
@@ -554,7 +554,7 @@ def get_cross_realm_dicts() -> List[Dict[str, Any]]:
def get_custom_profile_field_values(
- custom_profile_field_values: List[CustomProfileFieldValue],
+ custom_profile_field_values: Iterable[CustomProfileFieldValue],
) -> Dict[int, Dict[str, Any]]:
profiles_by_user_id: Dict[int, Dict[str, Any]] = defaultdict(dict)
for profile_field in custom_profile_field_values:
diff --git a/zerver/management/commands/send_custom_email.py b/zerver/management/commands/send_custom_email.py
index 5a07383556d..22d82a80ce2 100644
--- a/zerver/management/commands/send_custom_email.py
+++ b/zerver/management/commands/send_custom_email.py
@@ -1,5 +1,5 @@
from argparse import ArgumentParser
-from typing import Any, List
+from typing import Any, Collection, List
from django.conf import settings
from django.core.management.base import CommandError
@@ -70,7 +70,7 @@ class Command(ZulipBaseCommand):
def handle(self, *args: Any, **options: str) -> None:
target_emails: List[str] = []
- users: List[UserProfile] = []
+ users: Collection[UserProfile] = []
if options["entire_server"]:
users = UserProfile.objects.filter(
diff --git a/zerver/management/commands/send_password_reset_email.py b/zerver/management/commands/send_password_reset_email.py
index d681ebfe4a8..eae9d972bc1 100644
--- a/zerver/management/commands/send_password_reset_email.py
+++ b/zerver/management/commands/send_password_reset_email.py
@@ -1,5 +1,5 @@
from argparse import ArgumentParser
-from typing import Any, List
+from typing import Any, Iterable
from django.contrib.auth.tokens import default_token_generator
from django.core.management.base import CommandError
@@ -26,7 +26,9 @@ class Command(ZulipBaseCommand):
def handle(self, *args: Any, **options: str) -> None:
if options["entire_server"]:
- users = UserProfile.objects.filter(is_active=True, is_bot=False, is_mirror_dummy=False)
+ users: Iterable[UserProfile] = UserProfile.objects.filter(
+ is_active=True, is_bot=False, is_mirror_dummy=False
+ )
else:
realm = self.get_realm(options)
try:
@@ -40,7 +42,7 @@ class Command(ZulipBaseCommand):
self.send(users)
- def send(self, users: List[UserProfile]) -> None:
+ def send(self, users: Iterable[UserProfile]) -> None:
"""Sends one-use only links for resetting password to target users"""
for user_profile in users:
context = {
diff --git a/zerver/management/commands/sync_ldap_user_data.py b/zerver/management/commands/sync_ldap_user_data.py
index 8384ee7c333..5c8a957d846 100644
--- a/zerver/management/commands/sync_ldap_user_data.py
+++ b/zerver/management/commands/sync_ldap_user_data.py
@@ -1,6 +1,6 @@
import logging
from argparse import ArgumentParser
-from typing import Any, List
+from typing import Any, Collection
from django.conf import settings
from django.core.management.base import CommandError
@@ -18,7 +18,7 @@ log_to_file(logger, settings.LDAP_SYNC_LOG_PATH)
# Run this on a cron job to pick up on name changes.
@transaction.atomic
def sync_ldap_user_data(
- user_profiles: List[UserProfile], deactivation_protection: bool = True
+ user_profiles: Collection[UserProfile], deactivation_protection: bool = True
) -> None:
logger.info("Starting update.")
try:
diff --git a/zerver/tests/test_import_export.py b/zerver/tests/test_import_export.py
index 529de861819..35a63616868 100644
--- a/zerver/tests/test_import_export.py
+++ b/zerver/tests/test_import_export.py
@@ -1,7 +1,7 @@
import datetime
import os
import shutil
-from typing import Any, Callable, Dict, FrozenSet, List, Optional, Set, Tuple
+from typing import Any, Callable, Dict, FrozenSet, Iterable, List, Optional, Set, Tuple
from unittest.mock import patch
import orjson
@@ -956,7 +956,7 @@ class RealmImportExportTest(ExportFile):
return {get_email(user_id) for user_id in user_id_list}
def custom_profile_field_values_for(
- fields: List[CustomProfileField],
+ fields: Iterable[CustomProfileField],
) -> Set[FrozenSet[str]]:
user_emails: Set[FrozenSet[str]] = set()
for field in fields:
diff --git a/zerver/views/registration.py b/zerver/views/registration.py
index 4eb3dec543c..34a59deec1c 100644
--- a/zerver/views/registration.py
+++ b/zerver/views/registration.py
@@ -1,6 +1,6 @@
import logging
import urllib
-from typing import Any, Dict, List, Optional
+from typing import Any, Dict, Iterable, List, Optional
from urllib.parse import urlencode
from django.conf import settings
@@ -546,7 +546,7 @@ def prepare_activation_url(
*,
realm: Optional[Realm],
realm_creation: bool = False,
- streams: Optional[List[Stream]] = None,
+ streams: Optional[Iterable[Stream]] = None,
invited_as: Optional[int] = None,
) -> str:
"""