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.

ruff: Fix UP007 Use `X | Y` for type annotations.

Anders Kaseorg531b34cb4ce2
diff --git a/analytics/lib/counts.py b/analytics/lib/counts.py
index 07fefdfd1d5..41b52e00875 100644
--- a/analytics/lib/counts.py
+++ b/analytics/lib/counts.py
@@ -2,7 +2,7 @@ import logging
import time
from collections import OrderedDict, defaultdict
from datetime import datetime, timedelta
-from typing import Callable, Optional, Sequence, Union
+from typing import Callable, Sequence, Union
from django.conf import settings
from django.db import connection, models
@@ -55,7 +55,7 @@ class CountStat:
property: str,
data_collector: "DataCollector",
frequency: str,
- interval: Optional[timedelta] = None,
+ interval: timedelta | None = None,
) -> None:
self.property = property
self.data_collector = data_collector
@@ -72,7 +72,7 @@ class CountStat:
def __repr__(self) -> str:
return f"<CountStat: {self.property}>"
- def last_successful_fill(self) -> Optional[datetime]:
+ def last_successful_fill(self) -> datetime | None:
fillstate = FillState.objects.filter(property=self.property).first()
if fillstate is None:
return None
@@ -92,7 +92,7 @@ class DependentCountStat(CountStat):
property: str,
data_collector: "DataCollector",
frequency: str,
- interval: Optional[timedelta] = None,
+ interval: timedelta | None = None,
dependencies: Sequence[str] = [],
) -> None:
CountStat.__init__(self, property, data_collector, frequency, interval=interval)
@@ -103,7 +103,7 @@ class DataCollector:
def __init__(
self,
output_table: type[BaseCount],
- pull_function: Optional[Callable[[str, datetime, datetime, Optional[Realm]], int]],
+ pull_function: Callable[[str, datetime, datetime, Realm | None], int] | None,
) -> None:
self.output_table = output_table
self.pull_function = pull_function
@@ -115,9 +115,7 @@ class DataCollector:
## CountStat-level operations ##
-def process_count_stat(
- stat: CountStat, fill_to_time: datetime, realm: Optional[Realm] = None
-) -> None:
+def process_count_stat(stat: CountStat, fill_to_time: datetime, realm: Realm | None = None) -> None:
# TODO: The realm argument is not yet supported, in that we don't
# have a solution for how to update FillState if it is passed. It
# exists solely as partial plumbing for when we do fully implement
@@ -180,7 +178,7 @@ def do_update_fill_state(fill_state: FillState, end_time: datetime, state: int)
# We assume end_time is valid (e.g. is on a day or hour boundary as appropriate)
# and is time-zone-aware. It is the caller's responsibility to enforce this!
def do_fill_count_stat_at_hour(
- stat: CountStat, end_time: datetime, realm: Optional[Realm] = None
+ stat: CountStat, end_time: datetime, realm: Realm | None = None
) -> None:
start_time = end_time - stat.interval
if not isinstance(stat, LoggingCountStat):
@@ -209,7 +207,7 @@ def do_delete_counts_at_hour(stat: CountStat, end_time: datetime) -> None:
def do_aggregate_to_summary_table(
- stat: CountStat, end_time: datetime, realm: Optional[Realm] = None
+ stat: CountStat, end_time: datetime, realm: Realm | None = None
) -> None:
cursor = connection.cursor()
@@ -303,7 +301,7 @@ def do_aggregate_to_summary_table(
def do_increment_logging_stat(
model_object_for_bucket: Union[Realm, UserProfile, Stream, "RemoteRealm", "RemoteZulipServer"],
stat: CountStat,
- subgroup: Optional[Union[str, int, bool]],
+ subgroup: str | int | bool | None,
event_time: datetime,
increment: int = 1,
) -> None:
@@ -311,7 +309,7 @@ def do_increment_logging_stat(
return
table = stat.data_collector.output_table
- id_args: dict[str, Union[int, None]] = {}
+ id_args: dict[str, int | None] = {}
conflict_args: list[str] = []
if table == RealmCount:
assert isinstance(model_object_for_bucket, Realm)
@@ -433,7 +431,7 @@ def do_pull_by_sql_query(
start_time: datetime,
end_time: datetime,
query: QueryFn,
- group_by: Optional[tuple[type[models.Model], str]],
+ group_by: tuple[type[models.Model], str] | None,
) -> int:
if group_by is None:
subgroup: Composable = SQL("NULL")
@@ -469,10 +467,10 @@ def do_pull_by_sql_query(
def sql_data_collector(
output_table: type[BaseCount],
query: QueryFn,
- group_by: Optional[tuple[type[models.Model], str]],
+ group_by: tuple[type[models.Model], str] | None,
) -> DataCollector:
def pull_function(
- property: str, start_time: datetime, end_time: datetime, realm: Optional[Realm] = None
+ property: str, start_time: datetime, end_time: datetime, realm: Realm | None = None
) -> int:
# The pull function type needs to accept a Realm argument
# because the 'minutes_active::day' CountStat uses
@@ -485,7 +483,7 @@ def sql_data_collector(
return DataCollector(output_table, pull_function)
-def count_upload_space_used_by_realm_query(realm: Optional[Realm]) -> QueryFn:
+def count_upload_space_used_by_realm_query(realm: Realm | None) -> QueryFn:
if realm is None:
realm_clause: Composable = SQL("")
else:
@@ -520,7 +518,7 @@ def count_upload_space_used_by_realm_query(realm: Optional[Realm]) -> QueryFn:
def do_pull_minutes_active(
- property: str, start_time: datetime, end_time: datetime, realm: Optional[Realm] = None
+ property: str, start_time: datetime, end_time: datetime, realm: Realm | None = None
) -> int:
user_activity_intervals = (
UserActivityInterval.objects.filter(
@@ -555,7 +553,7 @@ def do_pull_minutes_active(
return len(rows)
-def count_message_by_user_query(realm: Optional[Realm]) -> QueryFn:
+def count_message_by_user_query(realm: Realm | None) -> QueryFn:
if realm is None:
realm_clause: Composable = SQL("")
else:
@@ -588,7 +586,7 @@ def count_message_by_user_query(realm: Optional[Realm]) -> QueryFn:
# Note: ignores the group_by / group_by_clause.
-def count_message_type_by_user_query(realm: Optional[Realm]) -> QueryFn:
+def count_message_type_by_user_query(realm: Realm | None) -> QueryFn:
if realm is None:
realm_clause: Composable = SQL("")
else:
@@ -643,7 +641,7 @@ def count_message_type_by_user_query(realm: Optional[Realm]) -> QueryFn:
# use this also subgroup on UserProfile.is_bot. If in the future there is a
# stat that counts messages by stream and doesn't need the UserProfile
# table, consider writing a new query for efficiency.
-def count_message_by_stream_query(realm: Optional[Realm]) -> QueryFn:
+def count_message_by_stream_query(realm: Realm | None) -> QueryFn:
if realm is None:
realm_clause: Composable = SQL("")
else:
@@ -683,7 +681,7 @@ def count_message_by_stream_query(realm: Optional[Realm]) -> QueryFn:
# same event_time and event_type in [RealmAuditLog.USER_CREATED,
# USER_DEACTIVATED, etc]. In particular, it's important to ensure
# that migrations don't cause that to happen.
-def check_realmauditlog_by_user_query(realm: Optional[Realm]) -> QueryFn:
+def check_realmauditlog_by_user_query(realm: Realm | None) -> QueryFn:
if realm is None:
realm_clause: Composable = SQL("")
else:
@@ -722,7 +720,7 @@ def check_realmauditlog_by_user_query(realm: Optional[Realm]) -> QueryFn:
)
-def check_useractivityinterval_by_user_query(realm: Optional[Realm]) -> QueryFn:
+def check_useractivityinterval_by_user_query(realm: Realm | None) -> QueryFn:
if realm is None:
realm_clause: Composable = SQL("")
else:
@@ -746,7 +744,7 @@ def check_useractivityinterval_by_user_query(realm: Optional[Realm]) -> QueryFn:
).format(**kwargs, realm_clause=realm_clause)
-def count_realm_active_humans_query(realm: Optional[Realm]) -> QueryFn:
+def count_realm_active_humans_query(realm: Realm | None) -> QueryFn:
if realm is None:
realm_clause: Composable = SQL("")
else:
@@ -817,7 +815,7 @@ count_stream_by_realm_query = lambda kwargs: SQL(
).format(**kwargs)
-def get_count_stats(realm: Optional[Realm] = None) -> dict[str, CountStat]:
+def get_count_stats(realm: Realm | None = None) -> dict[str, CountStat]:
## CountStat declarations ##
count_stats_ = [
diff --git a/analytics/lib/time_utils.py b/analytics/lib/time_utils.py
index 04b4baaa4f3..b8328ad9278 100644
--- a/analytics/lib/time_utils.py
+++ b/analytics/lib/time_utils.py
@@ -1,5 +1,4 @@
from datetime import datetime, timedelta
-from typing import Optional
from analytics.lib.counts import CountStat
from zerver.lib.timestamp import floor_to_day, floor_to_hour, verify_UTC
@@ -10,7 +9,7 @@ from zerver.lib.timestamp import floor_to_day, floor_to_hour, verify_UTC
# So informally, time_range(Sep 20, Sep 22, day, None) returns [Sep 20, Sep 21, Sep 22],
# and time_range(Sep 20, Sep 22, day, 5) returns [Sep 18, Sep 19, Sep 20, Sep 21, Sep 22]
def time_range(
- start: datetime, end: datetime, frequency: str, min_length: Optional[int]
+ start: datetime, end: datetime, frequency: str, min_length: int | None
) -> list[datetime]:
verify_UTC(start)
verify_UTC(end)
diff --git a/analytics/management/commands/populate_analytics_db.py b/analytics/management/commands/populate_analytics_db.py
index c9c23a6a447..47806fc2e51 100644
--- a/analytics/management/commands/populate_analytics_db.py
+++ b/analytics/management/commands/populate_analytics_db.py
@@ -1,5 +1,5 @@
from datetime import timedelta
-from typing import Any, Mapping, Union
+from typing import Any, Mapping
from django.core.files.uploadedfile import UploadedFile
from django.utils.timezone import now as timezone_now
@@ -147,7 +147,7 @@ class Command(ZulipBaseCommand):
with open(IMAGE_FILE_PATH, "rb") as fp:
upload_message_attachment_from_request(UploadedFile(fp), shylock)
- FixtureData: TypeAlias = Mapping[Union[str, int, None], list[int]]
+ FixtureData: TypeAlias = Mapping[str | int | None, list[int]]
def insert_fixture_data(
stat: CountStat,
@@ -330,7 +330,7 @@ class Command(ZulipBaseCommand):
"true": self.generate_fixture_data(stat, 20, 2, 3, 0.2, 3),
}
insert_fixture_data(stat, realm_data, RealmCount)
- stream_data: Mapping[Union[int, str, None], list[int]] = {
+ stream_data: Mapping[int | str | None, list[int]] = {
"false": self.generate_fixture_data(stat, 10, 7, 5, 0.6, 4),
"true": self.generate_fixture_data(stat, 5, 3, 2, 0.4, 2),
}
diff --git a/analytics/tests/test_counts.py b/analytics/tests/test_counts.py
index 37453d1d220..42efed54562 100644
--- a/analytics/tests/test_counts.py
+++ b/analytics/tests/test_counts.py
@@ -1,6 +1,6 @@
from contextlib import AbstractContextManager, ExitStack, contextmanager
from datetime import datetime, timedelta, timezone
-from typing import Any, Iterator, Optional
+from typing import Any, Iterator
from unittest import mock
import time_machine
@@ -111,7 +111,7 @@ class AnalyticsTestCase(ZulipTestCase):
# used to generate unique names in self.create_*
self.name_counter = 100
# used as defaults in self.assert_table_count
- self.current_property: Optional[str] = None
+ self.current_property: str | None = None
# Delete RemoteRealm registrations to have a clean slate - the relevant
# tests want to construct this from scratch.
@@ -226,10 +226,10 @@ class AnalyticsTestCase(ZulipTestCase):
self,
table: type[BaseCount],
value: int,
- property: Optional[str] = None,
- subgroup: Optional[str] = None,
+ property: str | None = None,
+ subgroup: str | None = None,
end_time: datetime = TIME_ZERO,
- realm: Optional[Realm] = None,
+ realm: Realm | None = None,
**kwargs: models.Model,
) -> None:
if property is None:
@@ -1812,7 +1812,7 @@ class TestActiveUsersAudit(AnalyticsTestCase):
self.current_property = self.stat.property
def add_event(
- self, event_type: int, days_offset: float, user: Optional[UserProfile] = None
+ self, event_type: int, days_offset: float, user: UserProfile | None = None
) -> None:
hours_offset = int(24 * days_offset)
if user is None:
@@ -1984,7 +1984,7 @@ class TestRealmActiveHumans(AnalyticsTestCase):
self.stat = COUNT_STATS["realm_active_humans::day"]
self.current_property = self.stat.property
- def mark_15day_active(self, user: UserProfile, end_time: Optional[datetime] = None) -> None:
+ def mark_15day_active(self, user: UserProfile, end_time: datetime | None = None) -> None:
if end_time is None:
end_time = self.TIME_ZERO
UserCount.objects.create(
diff --git a/analytics/tests/test_stats_views.py b/analytics/tests/test_stats_views.py
index dd4cbf27e39..fd6c948d330 100644
--- a/analytics/tests/test_stats_views.py
+++ b/analytics/tests/test_stats_views.py
@@ -1,5 +1,4 @@
from datetime import datetime, timedelta, timezone
-from typing import Optional
from django.utils.timezone import now as timezone_now
from typing_extensions import override
@@ -88,7 +87,7 @@ class TestGetChartData(ZulipTestCase):
return [0, 0, i, 0]
def insert_data(
- self, stat: CountStat, realm_subgroups: list[Optional[str]], user_subgroups: list[str]
+ self, stat: CountStat, realm_subgroups: list[str | None], user_subgroups: list[str]
) -> None:
if stat.frequency == CountStat.HOUR:
insert_time = self.end_times_hour[2]
diff --git a/analytics/urls.py b/analytics/urls.py
index 58b0cf5574e..cd81a612ced 100644
--- a/analytics/urls.py
+++ b/analytics/urls.py
@@ -1,5 +1,3 @@
-from typing import Union
-
from django.conf import settings
from django.conf.urls import include
from django.urls import path
@@ -16,7 +14,7 @@ from analytics.views.stats import (
)
from zerver.lib.rest import rest_path
-i18n_urlpatterns: list[Union[URLPattern, URLResolver]] = [
+i18n_urlpatterns: list[URLPattern | URLResolver] = [
# Server admin (user_profile.is_staff) visible stats pages
path("stats/realm/<realm_str>/", stats_for_realm),
path("stats/installation", stats_for_installation),
diff --git a/analytics/views/stats.py b/analytics/views/stats.py
index 62d3c94388d..ec656be10c3 100644
--- a/analytics/views/stats.py
+++ b/analytics/views/stats.py
@@ -1,7 +1,7 @@
import logging
from collections import defaultdict
from datetime import datetime, timedelta, timezone
-from typing import Any, Optional, TypeVar, Union, cast
+from typing import Any, Optional, TypeVar, cast
from django.conf import settings
from django.db.models import QuerySet
@@ -52,9 +52,9 @@ def is_analytics_ready(realm: Realm) -> bool:
def render_stats(
request: HttpRequest,
data_url_suffix: str,
- realm: Optional[Realm],
+ realm: Realm | None,
*,
- title: Optional[str] = None,
+ title: str | None = None,
analytics_ready: bool = True,
) -> HttpResponse:
assert request.user.is_authenticated
@@ -246,25 +246,25 @@ def get_chart_data(
request: HttpRequest,
user_profile: UserProfile,
chart_name: str = REQ(),
- min_length: Optional[int] = REQ(converter=to_non_negative_int, default=None),
- start: Optional[datetime] = REQ(converter=to_utc_datetime, default=None),
- end: Optional[datetime] = REQ(converter=to_utc_datetime, default=None),
+ min_length: int | None = REQ(converter=to_non_negative_int, default=None),
+ start: datetime | None = REQ(converter=to_utc_datetime, default=None),
+ end: datetime | None = REQ(converter=to_utc_datetime, default=None),
# These last several parameters are only used by functions
# wrapping get_chart_data; the callers are responsible for
# parsing/validation/authorization for them.
- realm: Optional[Realm] = None,
+ realm: Realm | None = None,
for_installation: bool = False,
remote: bool = False,
- remote_realm_id: Optional[int] = None,
+ remote_realm_id: int | None = None,
server: Optional["RemoteZulipServer"] = None,
- stream: Optional[Stream] = None,
+ stream: Stream | None = None,
) -> HttpResponse:
- TableType: TypeAlias = Union[
- type["RemoteInstallationCount"],
- type[InstallationCount],
- type["RemoteRealmCount"],
- type[RealmCount],
- ]
+ TableType: TypeAlias = (
+ type["RemoteInstallationCount"]
+ | type[InstallationCount]
+ | type["RemoteRealmCount"]
+ | type[RealmCount]
+ )
if for_installation:
if remote:
assert settings.ZILENCER_ENABLED
@@ -281,9 +281,9 @@ def get_chart_data(
else:
aggregate_table = RealmCount
- tables: Union[
- tuple[TableType], tuple[TableType, type[UserCount]], tuple[TableType, type[StreamCount]]
- ]
+ tables: (
+ tuple[TableType] | tuple[TableType, type[UserCount]] | tuple[TableType, type[StreamCount]]
+ )
if chart_name == "number_of_humans":
stats = [
@@ -292,7 +292,7 @@ def get_chart_data(
COUNT_STATS["active_users_audit:is_bot:day"],
]
tables = (aggregate_table,)
- subgroup_to_label: dict[CountStat, dict[Optional[str], str]] = {
+ subgroup_to_label: dict[CountStat, dict[str | None, str]] = {
stats[0]: {None: "_1day"},
stats[1]: {None: "_15day"},
stats[2]: {"false": "all_time"},
@@ -372,7 +372,7 @@ def get_chart_data(
assert server is not None
assert aggregate_table is RemoteInstallationCount or aggregate_table is RemoteRealmCount
aggregate_table_remote = cast(
- Union[type[RemoteInstallationCount], type[RemoteRealmCount]], aggregate_table
+ type[RemoteInstallationCount] | type[RemoteRealmCount], aggregate_table
) # https://stackoverflow.com/questions/68540528/mypy-assertions-on-the-types-of-types
if not aggregate_table_remote.objects.filter(server=server).exists():
raise JsonableError(
@@ -552,7 +552,7 @@ def get_time_series_by_subgroup(
table: type[BaseCount],
key_id: int,
end_times: list[datetime],
- subgroup_to_label: dict[Optional[str], str],
+ subgroup_to_label: dict[str | None, str],
include_empty_subgroups: bool,
) -> dict[str, list[int]]:
queryset = (
@@ -560,7 +560,7 @@ def get_time_series_by_subgroup(
.filter(property=stat.property)
.values_list("subgroup", "end_time", "value")
)
- value_dicts: dict[Optional[str], dict[datetime, int]] = defaultdict(lambda: defaultdict(int))
+ value_dicts: dict[str | None, dict[datetime, int]] = defaultdict(lambda: defaultdict(int))
for subgroup, end_time, value in queryset:
value_dicts[subgroup][end_time] = value
value_arrays = {}
diff --git a/confirmation/models.py b/confirmation/models.py
index b360539a5dd..7c976fc5c98 100644
--- a/confirmation/models.py
+++ b/confirmation/models.py
@@ -62,21 +62,21 @@ def generate_key() -> str:
return b32encode(secrets.token_bytes(15)).decode().lower()
-NoZilencerConfirmationObjT: TypeAlias = Union[
- MultiuseInvite,
- PreregistrationRealm,
- PreregistrationUser,
- EmailChangeStatus,
- UserProfile,
- RealmReactivationStatus,
-]
+NoZilencerConfirmationObjT: TypeAlias = (
+ MultiuseInvite
+ | PreregistrationRealm
+ | PreregistrationUser
+ | EmailChangeStatus
+ | UserProfile
+ | RealmReactivationStatus
+)
ZilencerConfirmationObjT: TypeAlias = Union[
NoZilencerConfirmationObjT,
"PreregistrationRemoteServerBillingUser",
"PreregistrationRemoteRealmBillingUser",
]
-ConfirmationObjT: TypeAlias = Union[NoZilencerConfirmationObjT, ZilencerConfirmationObjT]
+ConfirmationObjT: TypeAlias = NoZilencerConfirmationObjT | ZilencerConfirmationObjT
def get_object_from_key(
@@ -128,7 +128,7 @@ def create_confirmation_object(
obj: ConfirmationObjT,
confirmation_type: int,
*,
- validity_in_minutes: Union[Optional[int], UnspecifiedValue] = UnspecifiedValue(),
+ validity_in_minutes: int | None | UnspecifiedValue = UnspecifiedValue(),
no_associated_realm_object: bool = False,
) -> "Confirmation":
# validity_in_minutes is an override for the default values which are
@@ -171,7 +171,7 @@ def create_confirmation_link(
obj: ConfirmationObjT,
confirmation_type: int,
*,
- validity_in_minutes: Union[Optional[int], UnspecifiedValue] = UnspecifiedValue(),
+ validity_in_minutes: int | None | UnspecifiedValue = UnspecifiedValue(),
url_args: Mapping[str, str] = {},
no_associated_realm_object: bool = False,
) -> str:
@@ -194,7 +194,7 @@ def confirmation_url_for(confirmation_obj: "Confirmation", url_args: Mapping[str
def confirmation_url(
confirmation_key: str,
- realm: Optional[Realm],
+ realm: Realm | None,
confirmation_type: int,
url_args: Mapping[str, str] = {},
) -> str:
@@ -290,7 +290,7 @@ def one_click_unsubscribe_link(user_profile: UserProfile, email_type: str) -> st
# add another Confirmation.type for this; it's this way for historical reasons.
-def validate_key(creation_key: Optional[str]) -> Optional["RealmCreationKey"]:
+def validate_key(creation_key: str | None) -> Optional["RealmCreationKey"]:
"""Get the record for this key, raising InvalidCreationKey if non-None but invalid."""
if creation_key is None:
return None
diff --git a/corporate/lib/activity.py b/corporate/lib/activity.py
index dc8a9aed0b9..e377eae592c 100644
--- a/corporate/lib/activity.py
+++ b/corporate/lib/activity.py
@@ -2,7 +2,7 @@ from collections import defaultdict
from dataclasses import dataclass
from datetime import datetime
from decimal import Decimal
-from typing import Any, Callable, Optional, Sequence, Union
+from typing import Any, Callable, Sequence
from urllib.parse import urlencode
from django.conf import settings
@@ -46,8 +46,8 @@ def make_table(
cols: Sequence[str],
rows: Sequence[Any],
*,
- totals: Optional[Any] = None,
- stats_link: Optional[Markup] = None,
+ totals: Any | None = None,
+ stats_link: Markup | None = None,
has_row_class: bool = False,
) -> str:
if not has_row_class:
@@ -70,7 +70,7 @@ def make_table(
def fix_rows(
rows: list[list[Any]],
i: int,
- fixup_func: Union[Callable[[str], Markup], Callable[[datetime], str], Callable[[int], int]],
+ fixup_func: Callable[[str], Markup] | Callable[[datetime], str] | Callable[[int], int],
) -> None:
for row in rows:
row[i] = fixup_func(row[i])
@@ -91,7 +91,7 @@ def dictfetchall(cursor: CursorWrapper) -> list[dict[str, Any]]:
return [dict(zip((col[0] for col in desc), row)) for row in cursor.fetchall()]
-def format_optional_datetime(date: Optional[datetime], display_none: bool = False) -> str:
+def format_optional_datetime(date: datetime | None, display_none: bool = False) -> str:
if date:
return date.strftime("%Y-%m-%d %H:%M")
elif display_none:
@@ -104,7 +104,7 @@ def format_datetime_as_date(date: datetime) -> str:
return date.strftime("%Y-%m-%d")
-def format_none_as_zero(value: Optional[int]) -> int:
+def format_none_as_zero(value: int | None) -> int:
if value:
return value
else:
@@ -159,7 +159,7 @@ def remote_installation_support_link(hostname: str) -> Markup:
return Markup('<a href="{url}"><i class="fa fa-gear"></i></a>').format(url=url)
-def get_plan_rate_percentage(discount: Optional[str]) -> str:
+def get_plan_rate_percentage(discount: str | None) -> str:
# CustomerPlan.discount is a string field that stores the discount.
if discount is None or discount == "0":
return "100%"
@@ -176,8 +176,8 @@ def get_remote_activity_plan_data(
plan: CustomerPlan,
license_ledger: LicenseLedger,
*,
- remote_realm: Optional[RemoteRealm] = None,
- remote_server: Optional[RemoteZulipServer] = None,
+ remote_realm: RemoteRealm | None = None,
+ remote_server: RemoteZulipServer | None = None,
) -> RemoteActivityPlanData:
if plan.tier == CustomerPlan.TIER_SELF_HOSTED_LEGACY or plan.status in (
CustomerPlan.DOWNGRADE_AT_END_OF_FREE_TRIAL,
diff --git a/corporate/lib/decorator.py b/corporate/lib/decorator.py
index 49059f79fd9..178453c218b 100644
--- a/corporate/lib/decorator.py
+++ b/corporate/lib/decorator.py
@@ -1,5 +1,5 @@
from functools import wraps
-from typing import Callable, Optional
+from typing import Callable
from urllib.parse import urlencode, urljoin
from django.conf import settings
@@ -128,7 +128,7 @@ def authenticated_remote_realm_management_endpoint(
return _wrapped_view_func
-def get_next_page_param_from_request_path(request: HttpRequest) -> Optional[str]:
+def get_next_page_param_from_request_path(request: HttpRequest) -> str | None:
# Our endpoint URLs in this subsystem end with something like
# /sponsorship or /plans etc.
# Therefore we can use this nice property to figure out easily what
diff --git a/corporate/lib/registration.py b/corporate/lib/registration.py
index 336f0065231..8fed382bf5d 100644
--- a/corporate/lib/registration.py
+++ b/corporate/lib/registration.py
@@ -1,5 +1,3 @@
-from typing import Optional
-
from django.conf import settings
from django.utils.translation import gettext as _
@@ -11,7 +9,7 @@ from zerver.models import Realm, UserProfile
from zerver.models.users import get_system_bot
-def generate_licenses_low_warning_message_if_required(realm: Realm) -> Optional[str]:
+def generate_licenses_low_warning_message_if_required(realm: Realm) -> str | None:
plan = get_current_plan_by_realm(realm)
if plan is None or plan.automanage_licenses:
return None
diff --git a/corporate/lib/remote_billing_util.py b/corporate/lib/remote_billing_util.py
index f36b90266e6..711dfd9d4e5 100644
--- a/corporate/lib/remote_billing_util.py
+++ b/corporate/lib/remote_billing_util.py
@@ -1,5 +1,5 @@
import logging
-from typing import Literal, Optional, TypedDict, Union, cast
+from typing import Literal, TypedDict, cast
from django.http import HttpRequest
from django.utils.timezone import now as timezone_now
@@ -33,11 +33,11 @@ class RemoteBillingIdentityDict(TypedDict):
remote_server_uuid: str
remote_realm_uuid: str
- remote_billing_user_id: Optional[int]
+ remote_billing_user_id: int | None
authenticated_at: int
uri_scheme: Literal["http://", "https://"]
- next_page: Optional[str]
+ next_page: str | None
class LegacyServerIdentityDict(TypedDict):
@@ -45,7 +45,7 @@ class LegacyServerIdentityDict(TypedDict):
# to add more information as appropriate.
remote_server_uuid: str
- remote_billing_user_id: Optional[int]
+ remote_billing_user_id: int | None
authenticated_at: int
@@ -53,9 +53,9 @@ class RemoteBillingIdentityExpiredError(Exception):
def __init__(
self,
*,
- realm_uuid: Optional[str] = None,
- server_uuid: Optional[str] = None,
- uri_scheme: Optional[Literal["http://", "https://"]] = None,
+ realm_uuid: str | None = None,
+ server_uuid: str | None = None,
+ uri_scheme: Literal["http://", "https://"] | None = None,
) -> None:
self.realm_uuid = realm_uuid
self.server_uuid = server_uuid
@@ -65,9 +65,9 @@ class RemoteBillingIdentityExpiredError(Exception):
def get_identity_dict_from_session(
request: HttpRequest,
*,
- realm_uuid: Optional[str],
- server_uuid: Optional[str],
-) -> Optional[Union[RemoteBillingIdentityDict, LegacyServerIdentityDict]]:
+ realm_uuid: str | None,
+ server_uuid: str | None,
+) -> RemoteBillingIdentityDict | LegacyServerIdentityDict | None:
if not (realm_uuid or server_uuid):
return None
@@ -101,12 +101,12 @@ def get_identity_dict_from_session(
def get_remote_realm_and_user_from_session(
request: HttpRequest,
- realm_uuid: Optional[str],
+ realm_uuid: str | None,
) -> tuple[RemoteRealm, RemoteRealmBillingUser]:
# Cannot use isinstance with TypeDicts, to make mypy know
# which of the TypedDicts in the Union this is - so just cast it.
identity_dict = cast(
- Optional[RemoteBillingIdentityDict],
+ RemoteBillingIdentityDict | None,
get_identity_dict_from_session(request, realm_uuid=realm_uuid, server_uuid=None),
)
@@ -151,8 +151,8 @@ def get_remote_realm_and_user_from_session(
def get_remote_server_and_user_from_session(
request: HttpRequest,
server_uuid: str,
-) -> tuple[RemoteZulipServer, Optional[RemoteServerBillingUser]]:
- identity_dict: Optional[LegacyServerIdentityDict] = get_identity_dict_from_session(
+) -> tuple[RemoteZulipServer, RemoteServerBillingUser | None]:
+ identity_dict: LegacyServerIdentityDict | None = get_identity_dict_from_session(
request, realm_uuid=None, server_uuid=server_uuid
)
diff --git a/corporate/lib/stripe.py b/corporate/lib/stripe.py
index 626f4d1994c..7fdab1d7961 100644
--- a/corporate/lib/stripe.py
+++ b/corporate/lib/stripe.py
@@ -8,7 +8,7 @@ from datetime import datetime, timedelta, timezone
from decimal import Decimal
from enum import Enum
from functools import wraps
-from typing import Any, Callable, Generator, Literal, Optional, TypedDict, TypeVar, Union
+from typing import Any, Callable, Generator, Literal, TypedDict, TypeVar
from urllib.parse import urlencode, urljoin
import stripe
@@ -129,7 +129,7 @@ def get_amount_due_fixed_price_plan(fixed_price: int, billing_schedule: int) ->
return amount_due
-def format_discount_percentage(discount: Optional[Decimal]) -> Optional[str]:
+def format_discount_percentage(discount: Decimal | None) -> str | None:
if type(discount) is not Decimal or discount == Decimal(0):
return None
@@ -196,7 +196,7 @@ def unsign_seat_count(signed_seat_count: str, salt: str) -> int:
def validate_licenses(
charge_automatically: bool,
- licenses: Optional[int],
+ licenses: int | None,
seat_count: int,
exempt_from_license_number_check: bool,
min_licenses_for_plan: int,
@@ -228,8 +228,8 @@ def validate_licenses(
def check_upgrade_parameters(
billing_modality: str,
schedule: str,
- license_management: Optional[str],
- licenses: Optional[int],
+ license_management: str | None,
+ licenses: int | None,
seat_count: int,
exempt_from_license_number_check: bool,
min_licenses_for_plan: int,
@@ -306,7 +306,7 @@ def start_of_next_billing_cycle(plan: CustomerPlan, event_time: datetime) -> dat
return dt
-def next_invoice_date(plan: CustomerPlan) -> Optional[datetime]:
+def next_invoice_date(plan: CustomerPlan) -> datetime | None:
if plan.status == CustomerPlan.ENDED:
return None
assert plan.next_invoice_date is not None # for mypy
@@ -341,7 +341,7 @@ def get_amount_to_credit_for_plan_tier_change(
return amount_to_credit_back
-def get_idempotency_key(ledger_entry: LicenseLedger) -> Optional[str]:
+def get_idempotency_key(ledger_entry: LicenseLedger) -> str | None:
if settings.TEST_SUITE:
return None
return f"ledger_entry:{ledger_entry.id}" # nocoverage
@@ -387,7 +387,7 @@ def build_support_url(support_view: str, query_text: str) -> str:
def get_configured_fixed_price_plan_offer(
customer: Customer, plan_tier: int
-) -> Optional[CustomerPlanOffer]:
+) -> CustomerPlanOffer | None:
"""
Fixed price plan offer configured via /support which the
customer is yet to buy or schedule a purchase.
@@ -408,7 +408,7 @@ class BillingError(JsonableError):
CONTACT_SUPPORT = gettext_lazy("Something went wrong. Please contact {email}.")
TRY_RELOADING = gettext_lazy("Something went wrong. Please reload the page.")
- def __init__(self, description: str, message: Optional[str] = None) -> None:
+ def __init__(self, description: str, message: str | None = None) -> None:
self.error_description = description
if message is None:
message = BillingError.CONTACT_SUPPORT.format(email=settings.ZULIP_ADMINISTRATOR)
@@ -539,10 +539,10 @@ class UpgradeRequest:
schedule: str
signed_seat_count: str
salt: str
- license_management: Optional[str]
- licenses: Optional[int]
+ license_management: str | None
+ licenses: int | None
tier: int
- remote_server_plan_start_date: Optional[str]
+ remote_server_plan_start_date: str | None
@dataclass
@@ -555,16 +555,16 @@ class InitialUpgradeRequest:
@dataclass
class UpdatePlanRequest:
- status: Optional[int]
- licenses: Optional[int]
- licenses_at_next_renewal: Optional[int]
- schedule: Optional[int]
+ status: int | None
+ licenses: int | None
+ licenses_at_next_renewal: int | None
+ schedule: int | None
@dataclass
class EventStatusRequest:
- stripe_session_id: Optional[str]
- stripe_invoice_id: Optional[str]
+ stripe_session_id: str | None
+ stripe_invoice_id: str | None
class SupportType(Enum):
@@ -582,17 +582,17 @@ class SupportType(Enum):
class SupportViewRequest(TypedDict, total=False):
support_type: SupportType
- sponsorship_status: Optional[bool]
- monthly_discounted_price: Optional[int]
- annual_discounted_price: Optional[int]
- billing_modality: Optional[str]
- plan_modification: Optional[str]
- new_plan_tier: Optional[int]
- minimum_licenses: Optional[int]
- plan_end_date: Optional[str]
- required_plan_tier: Optional[int]
- fixed_price: Optional[int]
- sent_invoice_id: Optional[str]
+ sponsorship_status: bool | None
+ monthly_discounted_price: int | None
+ annual_discounted_price: int | None
+ billing_modality: str | None
+ plan_modification: str | None
+ new_plan_tier: int | None
+ minimum_licenses: int | None
+ plan_end_date: str | None
+ required_plan_tier: int | None
+ fixed_price: int | None
+ sent_invoice_id: str | None
class AuditLogEventType(Enum):
@@ -626,25 +626,25 @@ class BillingSessionAuditLogEventError(Exception):
class UpgradePageParams(TypedDict):
page_type: Literal["upgrade"]
annual_price: int
- demo_organization_scheduled_deletion_date: Optional[datetime]
+ demo_organization_scheduled_deletion_date: datetime | None
monthly_price: int
seat_count: int
billing_base_url: str
tier: int
flat_discount: int
flat_discounted_months: int
- fixed_price: Optional[int]
+ fixed_price: int | None
setup_payment_by_invoice: bool
- free_trial_days: Optional[int]
- percent_off_annual_price: Optional[str]
- percent_off_monthly_price: Optional[str]
+ free_trial_days: int | None
+ percent_off_annual_price: str | None
+ percent_off_monthly_price: str | None
class UpgradePageSessionTypeSpecificContext(TypedDict):
customer_name: str
email: str
is_demo_organization: bool
- demo_organization_scheduled_deletion_date: Optional[datetime]
+ demo_organization_scheduled_deletion_date: datetime | None
is_self_hosting: bool
@@ -656,7 +656,7 @@ class SponsorshipApplicantInfo(TypedDict):
class SponsorshipRequestSessionSpecificContext(TypedDict):
# We don't store UserProfile for remote realms.
- realm_user: Optional[UserProfile]
+ realm_user: UserProfile | None
user_info: SponsorshipApplicantInfo
# TODO: Call this what we end up calling it for /support page.
realm_string_id: str
@@ -666,26 +666,26 @@ class UpgradePageContext(TypedDict):
customer_name: str
email: str
exempt_from_license_number_check: bool
- free_trial_end_date: Optional[str]
+ free_trial_end_date: str | None
is_demo_organization: bool
manual_license_management: bool
using_min_licenses_for_plan: bool
min_licenses_for_plan: int
page_params: UpgradePageParams
- payment_method: Optional[str]
+ payment_method: str | None
plan: str
fixed_price_plan: bool
- pay_by_invoice_payments_page: Optional[str]
- remote_server_legacy_plan_end_date: Optional[str]
+ pay_by_invoice_payments_page: str | None
+ remote_server_legacy_plan_end_date: str | None
salt: str
seat_count: int
signed_seat_count: str
success_message: str
is_sponsorship_pending: bool
sponsorship_plan_name: str
- scheduled_upgrade_invoice_amount_due: Optional[str]
+ scheduled_upgrade_invoice_amount_due: str | None
is_free_trial_invoice_expired_notice: bool
- free_trial_invoice_expired_notice_page_plan_name: Optional[str]
+ free_trial_invoice_expired_notice_page_plan_name: str | None
class SponsorshipRequestForm(forms.Form):
@@ -721,7 +721,7 @@ class BillingSession(ABC):
pass
@abstractmethod
- def get_customer(self) -> Optional[Customer]:
+ def get_customer(self) -> Customer | None:
pass
@abstractmethod
@@ -743,7 +743,7 @@ class BillingSession(ABC):
event_time: datetime,
*,
background_update: bool = False,
- extra_data: Optional[dict[str, Any]] = None,
+ extra_data: dict[str, Any] | None = None,
) -> None:
pass
@@ -811,7 +811,7 @@ class BillingSession(ABC):
self,
return_to_billing_page: bool,
manual_license_management: bool,
- tier: Optional[int] = None,
+ tier: int | None = None,
setup_payment_by_invoice: bool = False,
) -> str:
customer = self.get_customer()
@@ -850,17 +850,17 @@ class BillingSession(ABC):
def generate_invoice_for_upgrade(
self,
customer: Customer,
- price_per_license: Optional[int],
- fixed_price: Optional[int],
+ price_per_license: int | None,
+ fixed_price: int | None,
licenses: int,
plan_tier: int,
billing_schedule: int,
charge_automatically: bool,
invoice_period: stripe.InvoiceItem.CreateParamsPeriod,
- license_management: Optional[str] = None,
- days_until_due: Optional[int] = None,
+ license_management: str | None = None,
+ days_until_due: int | None = None,
on_free_trial: bool = False,
- current_plan_id: Optional[int] = None,
+ current_plan_id: int | None = None,
) -> stripe.Invoice:
assert customer.stripe_customer_id is not None
plan_name = CustomerPlan.name_from_tier(plan_tier)
@@ -945,13 +945,13 @@ class BillingSession(ABC):
@abstractmethod
def update_or_create_customer(
- self, stripe_customer_id: Optional[str] = None, *, defaults: Optional[dict[str, Any]] = None
+ self, stripe_customer_id: str | None = None, *, defaults: dict[str, Any] | None = None
) -> Customer:
pass
@abstractmethod
def do_change_plan_type(
- self, *, tier: Optional[int], is_sponsored: bool = False, background_update: bool = False
+ self, *, tier: int | None, is_sponsored: bool = False, background_update: bool = False
) -> None:
pass
@@ -1026,14 +1026,14 @@ class BillingSession(ABC):
# audit logs we will be processing.
pass
- def is_sponsored_or_pending(self, customer: Optional[Customer]) -> bool:
+ def is_sponsored_or_pending(self, customer: Customer | None) -> bool:
if (customer is not None and customer.sponsorship_pending) or self.is_sponsored():
return True
return False
def get_remote_server_legacy_plan(
- self, customer: Optional[Customer], status: int = CustomerPlan.ACTIVE
- ) -> Optional[CustomerPlan]:
+ self, customer: Customer | None, status: int = CustomerPlan.ACTIVE
+ ) -> CustomerPlan | None:
# status = CustomerPlan.ACTIVE means that the legacy plan is not scheduled for an upgrade.
# status = CustomerPlan.SWITCH_PLAN_TIER_AT_PLAN_END means that the legacy plan is scheduled for an upgrade.
if customer is None:
@@ -1046,8 +1046,8 @@ class BillingSession(ABC):
).first()
def get_formatted_remote_server_legacy_plan_end_date(
- self, customer: Optional[Customer], status: int = CustomerPlan.ACTIVE
- ) -> Optional[str]: # nocoverage
+ self, customer: Customer | None, status: int = CustomerPlan.ACTIVE
+ ) -> str | None: # nocoverage
plan = self.get_remote_server_legacy_plan(customer, status)
if plan is None:
return None
@@ -1055,7 +1055,7 @@ class BillingSession(ABC):
assert plan.end_date is not None
return plan.end_date.strftime("%B %d, %Y")
- def get_legacy_remote_server_next_plan(self, customer: Customer) -> Optional[CustomerPlan]:
+ def get_legacy_remote_server_next_plan(self, customer: Customer) -> CustomerPlan | None:
legacy_plan = self.get_remote_server_legacy_plan(
customer, CustomerPlan.SWITCH_PLAN_TIER_AT_PLAN_END
)
@@ -1070,7 +1070,7 @@ class BillingSession(ABC):
status=CustomerPlan.NEVER_STARTED,
)
- def get_legacy_remote_server_next_plan_name(self, customer: Customer) -> Optional[str]:
+ def get_legacy_remote_server_next_plan_name(self, customer: Customer) -> str | None:
next_plan = self.get_legacy_remote_server_next_plan(customer)
if next_plan is None:
return None
@@ -1114,7 +1114,7 @@ class BillingSession(ABC):
# Returns Customer instead of stripe_customer so that we don't make a Stripe
# API call if there's nothing to update
@catch_stripe_errors
- def update_or_create_stripe_customer(self, payment_method: Optional[str] = None) -> Customer:
+ def update_or_create_stripe_customer(self, payment_method: str | None = None) -> Customer:
customer = self.get_customer()
if customer is None or customer.stripe_customer_id is None:
# A stripe.PaymentMethod should be attached to a stripe.Customer via replace_payment_method.
@@ -1408,7 +1408,7 @@ class BillingSession(ABC):
plan_tier_name = CustomerPlan.name_from_tier(new_plan_tier)
return f"Required plan tier for {self.billing_entity_display_name} set to {plan_tier_name}."
- def configure_fixed_price_plan(self, fixed_price: int, sent_invoice_id: Optional[str]) -> str:
+ def configure_fixed_price_plan(self, fixed_price: int, sent_invoice_id: str | None) -> str:
customer = self.get_customer()
if customer is None:
customer = self.update_or_create_customer()
@@ -1616,8 +1616,8 @@ class BillingSession(ABC):
billing_schedule: int,
billing_modality: str,
on_free_trial: bool = False,
- days_until_due: Optional[int] = None,
- current_plan_id: Optional[int] = None,
+ days_until_due: int | None = None,
+ current_plan_id: int | None = None,
) -> str:
customer = self.update_or_create_stripe_customer()
assert customer is not None # for mypy
@@ -1713,7 +1713,7 @@ class BillingSession(ABC):
billing_schedule: int,
charge_automatically: bool,
free_trial: bool,
- remote_server_legacy_plan: Optional[CustomerPlan] = None,
+ remote_server_legacy_plan: CustomerPlan | None = None,
should_schedule_upgrade_for_legacy_remote_server: bool = False,
stripe_invoice_paid: bool = False,
) -> None:
@@ -2109,7 +2109,7 @@ class BillingSession(ABC):
@transaction.atomic
def make_end_of_cycle_updates_if_needed(
self, plan: CustomerPlan, event_time: datetime
- ) -> tuple[Optional[CustomerPlan], Optional[LicenseLedger]]:
+ ) -> tuple[CustomerPlan | None, LicenseLedger | None]:
last_ledger_entry = (
LicenseLedger.objects.filter(plan=plan, event_time__lte=event_time)
.order_by("-id")
@@ -2284,7 +2284,7 @@ class BillingSession(ABC):
return None, None
return None, last_ledger_entry
- def get_next_plan(self, plan: CustomerPlan) -> Optional[CustomerPlan]:
+ def get_next_plan(self, plan: CustomerPlan) -> CustomerPlan | None:
if plan.status == CustomerPlan.SWITCH_PLAN_TIER_AT_PLAN_END:
assert plan.end_date is not None
return CustomerPlan.objects.filter(
@@ -2513,7 +2513,7 @@ class BillingSession(ABC):
context[key] = next_plan_context[key]
return context
- def get_flat_discount_info(self, customer: Optional[Customer] = None) -> tuple[int, int]:
+ def get_flat_discount_info(self, customer: Customer | None = None) -> tuple[int, int]:
is_self_hosted_billing = not isinstance(self, RealmBillingSession)
flat_discount = 0
flat_discounted_months = 0
@@ -2531,7 +2531,7 @@ class BillingSession(ABC):
def get_initial_upgrade_context(
self, initial_upgrade_request: InitialUpgradeRequest
- ) -> tuple[Optional[str], Optional[UpgradePageContext]]:
+ ) -> tuple[str | None, UpgradePageContext | None]:
customer = self.get_customer()
# Allow users to upgrade to business regardless of current sponsorship status.
@@ -2695,7 +2695,7 @@ class BillingSession(ABC):
def min_licenses_for_flat_discount_to_self_hosted_basic_plan(
self,
- customer: Optional[Customer],
+ customer: Customer | None,
is_plan_free_trial_with_invoice_payment: bool = False,
) -> int:
# Since monthly and annual TIER_SELF_HOSTED_BASIC plans have same per user price we only need to do this calculation once.
@@ -2732,7 +2732,7 @@ class BillingSession(ABC):
return 25
return 1
- def downgrade_at_the_end_of_billing_cycle(self, plan: Optional[CustomerPlan] = None) -> None:
+ def downgrade_at_the_end_of_billing_cycle(self, plan: CustomerPlan | None = None) -> None:
if plan is None: # nocoverage
# TODO: Add test coverage. Right now, this logic is used
# in production but mocked in tests.
@@ -2760,7 +2760,7 @@ class BillingSession(ABC):
# for the cancellation of Free Trial.
def downgrade_now_without_creating_additional_invoices(
self,
- plan: Optional[CustomerPlan] = None,
+ plan: CustomerPlan | None = None,
background_update: bool = False,
) -> None:
if plan is None:
@@ -3224,9 +3224,7 @@ class BillingSession(ABC):
raise JsonableError(_("Pass stripe_session_id or stripe_invoice_id"))
- def get_sponsorship_plan_name(
- self, customer: Optional[Customer], is_remotely_hosted: bool
- ) -> str:
+ def get_sponsorship_plan_name(self, customer: Customer | None, is_remotely_hosted: bool) -> str:
if customer is not None and customer.sponsorship_pending:
# For sponsorship pending requests, we also show the type of sponsorship requested.
# In other cases, we just show the plan user is currently on.
@@ -3250,7 +3248,7 @@ class BillingSession(ABC):
return sponsored_plan_name
- def get_sponsorship_request_context(self) -> Optional[dict[str, Any]]:
+ def get_sponsorship_request_context(self) -> dict[str, Any] | None:
customer = self.get_customer()
is_remotely_hosted = isinstance(
self, (RemoteRealmBillingSession, RemoteServerBillingSession)
@@ -3510,8 +3508,8 @@ class BillingSession(ABC):
self,
plan: CustomerPlan,
event_time: datetime,
- licenses: Optional[int] = None,
- licenses_at_next_renewal: Optional[int] = None,
+ licenses: int | None = None,
+ licenses_at_next_renewal: int | None = None,
) -> None:
if licenses is not None:
if not plan.customer.exempt_from_license_number_check:
@@ -3543,7 +3541,7 @@ class BillingSession(ABC):
self,
customer: Customer,
tier: int,
- licenses: Optional[int] = None,
+ licenses: int | None = None,
event_time: datetime = timezone_now(),
) -> int:
if licenses is not None and customer.exempt_from_license_number_check:
@@ -3559,7 +3557,7 @@ class BillingSession(ABC):
def update_license_ledger_for_automanaged_plan(
self, plan: CustomerPlan, event_time: datetime
- ) -> Optional[CustomerPlan]:
+ ) -> CustomerPlan | None:
new_plan, last_ledger_entry = self.make_end_of_cycle_updates_if_needed(plan, event_time)
if last_ledger_entry is None:
return None
@@ -3714,7 +3712,7 @@ class BillingSession(ABC):
def get_last_ledger_for_automanaged_plan_if_exists(
self,
- ) -> Optional[LicenseLedger]:
+ ) -> LicenseLedger | None:
customer = self.get_customer()
if customer is None:
return None
@@ -3735,8 +3733,8 @@ class BillingSession(ABC):
class RealmBillingSession(BillingSession):
def __init__(
self,
- user: Optional[UserProfile] = None,
- realm: Optional[Realm] = None,
+ user: UserProfile | None = None,
+ realm: Realm | None = None,
*,
support_session: bool = False,
) -> None:
@@ -3780,7 +3778,7 @@ class RealmBillingSession(BillingSession):
return build_support_url("support", self.realm.string_id)
@override
- def get_customer(self) -> Optional[Customer]:
+ def get_customer(self) -> Customer | None:
return get_customer_by_realm(self.realm)
@override
@@ -3826,7 +3824,7 @@ class RealmBillingSession(BillingSession):
event_time: datetime,
*,
background_update: bool = False,
- extra_data: Optional[dict[str, Any]] = None,
+ extra_data: dict[str, Any] | None = None,
) -> None:
audit_log_event = self.get_audit_log_event(event_type)
audit_log_data = {
@@ -3874,7 +3872,7 @@ class RealmBillingSession(BillingSession):
@override
def update_or_create_customer(
- self, stripe_customer_id: Optional[str] = None, *, defaults: Optional[dict[str, Any]] = None
+ self, stripe_customer_id: str | None = None, *, defaults: dict[str, Any] | None = None
) -> Customer:
if stripe_customer_id is not None:
# Support requests do not set any stripe billing information.
@@ -3895,7 +3893,7 @@ class RealmBillingSession(BillingSession):
@override
def do_change_plan_type(
- self, *, tier: Optional[int], is_sponsored: bool = False, background_update: bool = False
+ self, *, tier: int | None, is_sponsored: bool = False, background_update: bool = False
) -> None:
from zerver.actions.realm_settings import do_change_realm_plan_type
@@ -4101,8 +4099,8 @@ class RemoteRealmBillingSession(BillingSession):
def __init__(
self,
remote_realm: RemoteRealm,
- remote_billing_user: Optional[RemoteRealmBillingUser] = None,
- support_staff: Optional[UserProfile] = None,
+ remote_billing_user: RemoteRealmBillingUser | None = None,
+ support_staff: UserProfile | None = None,
) -> None:
self.remote_realm = remote_realm
self.remote_billing_user = remote_billing_user
@@ -4133,7 +4131,7 @@ class RemoteRealmBillingSession(BillingSession):
return build_support_url("remote_servers_support", str(self.remote_realm.uuid))
@override
- def get_customer(self) -> Optional[Customer]:
+ def get_customer(self) -> Customer | None:
return get_customer_by_remote_realm(self.remote_realm)
@override
@@ -4205,7 +4203,7 @@ class RemoteRealmBillingSession(BillingSession):
event_time: datetime,
*,
background_update: bool = False,
- extra_data: Optional[dict[str, Any]] = None,
+ extra_data: dict[str, Any] | None = None,
) -> None:
# These audit logs don't use all the fields of `RemoteRealmAuditLog`:
#
@@ -4264,7 +4262,7 @@ class RemoteRealmBillingSession(BillingSession):
@override
def update_or_create_customer(
- self, stripe_customer_id: Optional[str] = None, *, defaults: Optional[dict[str, Any]] = None
+ self, stripe_customer_id: str | None = None, *, defaults: dict[str, Any] | None = None
) -> Customer:
if stripe_customer_id is not None:
# Support requests do not set any stripe billing information.
@@ -4291,7 +4289,7 @@ class RemoteRealmBillingSession(BillingSession):
@override
@transaction.atomic
def do_change_plan_type(
- self, *, tier: Optional[int], is_sponsored: bool = False, background_update: bool = False
+ self, *, tier: int | None, is_sponsored: bool = False, background_update: bool = False
) -> None: # nocoverage
if is_sponsored:
plan_type = RemoteRealm.PLAN_TYPE_COMMUNITY
@@ -4546,8 +4544,8 @@ class RemoteServerBillingSession(BillingSession):
def __init__(
self,
remote_server: RemoteZulipServer,
- remote_billing_user: Optional[RemoteServerBillingUser] = None,
- support_staff: Optional[UserProfile] = None,
+ remote_billing_user: RemoteServerBillingUser | None = None,
+ support_staff: UserProfile | None = None,
) -> None:
self.remote_server = remote_server
self.remote_billing_user = remote_billing_user
@@ -4578,7 +4576,7 @@ class RemoteServerBillingSession(BillingSession):
return build_support_url("remote_servers_support", str(self.remote_server.uuid))
@override
- def get_customer(self) -> Optional[Customer]:
+ def get_customer(self) -> Customer | None:
return get_customer_by_remote_server(self.remote_server)
@override
@@ -4648,7 +4646,7 @@ class RemoteServerBillingSession(BillingSession):
event_time: datetime,
*,
background_update: bool = False,
- extra_data: Optional[dict[str, Any]] = None,
+ extra_data: dict[str, Any] | None = None,
) -> None:
audit_log_event = self.get_audit_log_event(event_type)
log_data = {
@@ -4701,7 +4699,7 @@ class RemoteServerBillingSession(BillingSession):
@override
def update_or_create_customer(
- self, stripe_customer_id: Optional[str] = None, *, defaults: Optional[dict[str, Any]] = None
+ self, stripe_customer_id: str | None = None, *, defaults: dict[str, Any] | None = None
) -> Customer:
if stripe_customer_id is not None:
# Support requests do not set any stripe billing information.
@@ -4728,7 +4726,7 @@ class RemoteServerBillingSession(BillingSession):
@override
@transaction.atomic
def do_change_plan_type(
- self, *, tier: Optional[int], is_sponsored: bool = False, background_update: bool = False
+ self, *, tier: int | None, is_sponsored: bool = False, background_update: bool = False
) -> None:
# This function needs to translate between the different
# formats of CustomerPlan.tier and RealmZulipServer.plan_type.
@@ -5006,7 +5004,7 @@ def customer_has_credit_card_as_default_payment_method(customer: Customer) -> bo
def get_price_per_license(
- tier: int, billing_schedule: int, customer: Optional[Customer] = None
+ tier: int, billing_schedule: int, customer: Customer | None = None
) -> int:
if customer is not None:
price_per_license = customer.get_discounted_price_for_plan(tier, billing_schedule)
@@ -5035,8 +5033,8 @@ def get_price_per_license(
def get_price_per_license_and_discount(
- tier: int, billing_schedule: int, customer: Optional[Customer]
-) -> tuple[int, Union[str, None]]:
+ tier: int, billing_schedule: int, customer: Customer | None
+) -> tuple[int, str | None]:
original_price_per_license = get_price_per_license(tier, billing_schedule)
if customer is None:
return original_price_per_license, None
@@ -5054,9 +5052,9 @@ def get_price_per_license_and_discount(
def compute_plan_parameters(
tier: int,
billing_schedule: int,
- customer: Optional[Customer],
+ customer: Customer | None,
free_trial: bool = False,
- billing_cycle_anchor: Optional[datetime] = None,
+ billing_cycle_anchor: datetime | None = None,
is_self_hosted_billing: bool = False,
should_schedule_upgrade_for_legacy_remote_server: bool = False,
) -> tuple[datetime, datetime, datetime, int]:
@@ -5089,8 +5087,8 @@ def compute_plan_parameters(
def get_free_trial_days(
- is_self_hosted_billing: bool = False, tier: Optional[int] = None
-) -> Optional[int]:
+ is_self_hosted_billing: bool = False, tier: int | None = None
+) -> int | None:
if is_self_hosted_billing:
# Free trial is only available for self-hosted basic plan.
if tier is not None and tier != CustomerPlan.TIER_SELF_HOSTED_BASIC:
@@ -5100,7 +5098,7 @@ def get_free_trial_days(
return settings.CLOUD_FREE_TRIAL_DAYS
-def is_free_trial_offer_enabled(is_self_hosted_billing: bool, tier: Optional[int] = None) -> bool:
+def is_free_trial_offer_enabled(is_self_hosted_billing: bool, tier: int | None = None) -> bool:
return get_free_trial_days(is_self_hosted_billing, tier) not in (None, 0)
@@ -5196,13 +5194,13 @@ def get_plan_renewal_or_end_date(plan: CustomerPlan, event_time: datetime) -> da
return billing_period_end
-def invoice_plans_as_needed(event_time: Optional[datetime] = None) -> None:
+def invoice_plans_as_needed(event_time: datetime | None = None) -> None:
if event_time is None:
event_time = timezone_now()
# For self hosted legacy plan with status SWITCH_PLAN_TIER_AT_PLAN_END, we need
# to invoice legacy plan followed by new plan on the same day, hence ordered by ID.
for plan in CustomerPlan.objects.filter(next_invoice_date__lte=event_time).order_by("id"):
- remote_server: Optional[RemoteZulipServer] = None
+ remote_server: RemoteZulipServer | None = None
if plan.customer.realm is not None:
billing_session: BillingSession = RealmBillingSession(realm=plan.customer.realm)
elif plan.customer.remote_realm is not None:
@@ -5343,7 +5341,7 @@ def downgrade_small_realms_behind_on_payments_as_needed() -> None:
billing_session = RealmBillingSession(user=None, realm=realm)
billing_session.downgrade_now_without_creating_additional_invoices()
billing_session.void_all_open_invoices()
- context: dict[str, Union[str, Realm]] = {
+ context: dict[str, str | Realm] = {
"upgrade_url": f"{realm.url}{reverse('upgrade_page')}",
"realm": realm,
}
@@ -5366,7 +5364,7 @@ def downgrade_small_realms_behind_on_payments_as_needed() -> None:
@dataclass
class PushNotificationsEnabledStatus:
can_push: bool
- expected_end_timestamp: Optional[int]
+ expected_end_timestamp: int | None
# Not sent to clients, just for debugging
message: str
@@ -5376,14 +5374,14 @@ MAX_USERS_WITHOUT_PLAN = 10
def get_push_status_for_remote_request(
- remote_server: RemoteZulipServer, remote_realm: Optional[RemoteRealm]
+ remote_server: RemoteZulipServer, remote_realm: RemoteRealm | None
) -> PushNotificationsEnabledStatus:
# First, get the operative Customer object for this
# installation.
customer = None
current_plan = None
- realm_billing_session: Optional[BillingSession] = None
- server_billing_session: Optional[RemoteServerBillingSession] = None
+ realm_billing_session: BillingSession | None = None
+ server_billing_session: RemoteServerBillingSession | None = None
if remote_realm is not None:
realm_billing_session = RemoteRealmBillingSession(remote_realm)
@@ -5420,7 +5418,7 @@ def get_push_status_for_remote_request(
assert server_billing_session is not None
user_count_billing_session = server_billing_session
- user_count: Optional[int] = None
+ user_count: int | None = None
if current_plan is None:
try:
user_count = user_count_billing_session.current_count_for_billed_licenses()
diff --git a/corporate/lib/stripe_event_handler.py b/corporate/lib/stripe_event_handler.py
index b01ab02ee8b..026255288a5 100644
--- a/corporate/lib/stripe_event_handler.py
+++ b/corporate/lib/stripe_event_handler.py
@@ -1,5 +1,5 @@
import logging
-from typing import Any, Callable, Optional, Union
+from typing import Any, Callable
import stripe
from django.conf import settings
@@ -28,9 +28,9 @@ billing_logger = logging.getLogger("corporate.stripe")
def stripe_event_handler_decorator(
func: Callable[[Any, Any], None],
-) -> Callable[[Union[stripe.checkout.Session, stripe.Invoice], Event], None]:
+) -> Callable[[stripe.checkout.Session | stripe.Invoice, Event], None]:
def wrapper(
- stripe_object: Union[stripe.checkout.Session, stripe.Invoice],
+ stripe_object: stripe.checkout.Session | stripe.Invoice,
event: Event,
) -> None:
event.status = Event.EVENT_HANDLER_STARTED
@@ -84,8 +84,8 @@ def stripe_event_handler_decorator(
def get_billing_session_for_stripe_webhook(
- customer: Customer, user_id: Optional[str]
-) -> Union[RealmBillingSession, RemoteRealmBillingSession, RemoteServerBillingSession]:
+ customer: Customer, user_id: str | None
+) -> RealmBillingSession | RemoteRealmBillingSession | RemoteServerBillingSession:
if customer.remote_realm is not None: # nocoverage
return RemoteRealmBillingSession(customer.remote_realm)
elif customer.remote_server is not None: # nocoverage
diff --git a/corporate/lib/support.py b/corporate/lib/support.py
index 1acfd0c5669..cfc0211d9c2 100644
--- a/corporate/lib/support.py
+++ b/corporate/lib/support.py
@@ -58,19 +58,19 @@ class SponsorshipRequestDict(TypedDict):
@dataclass
class SponsorshipData:
sponsorship_pending: bool = False
- monthly_discounted_price: Optional[int] = None
- annual_discounted_price: Optional[int] = None
- original_monthly_plan_price: Optional[int] = None
- original_annual_plan_price: Optional[int] = None
- minimum_licenses: Optional[int] = None
- required_plan_tier: Optional[int] = None
- latest_sponsorship_request: Optional[SponsorshipRequestDict] = None
+ monthly_discounted_price: int | None = None
+ annual_discounted_price: int | None = None
+ original_monthly_plan_price: int | None = None
+ original_annual_plan_price: int | None = None
+ minimum_licenses: int | None = None
+ required_plan_tier: int | None = None
+ latest_sponsorship_request: SponsorshipRequestDict | None = None
@dataclass
class NextPlanData:
plan: Union["CustomerPlan", "CustomerPlanOffer", None] = None
- estimated_revenue: Optional[int] = None
+ estimated_revenue: int | None = None
@dataclass
@@ -78,24 +78,24 @@ class PlanData:
customer: Optional["Customer"] = None
current_plan: Optional["CustomerPlan"] = None
next_plan: Union["CustomerPlan", "CustomerPlanOffer", None] = None
- licenses: Optional[int] = None
- licenses_used: Optional[int] = None
- next_billing_cycle_start: Optional[datetime] = None
+ licenses: int | None = None
+ licenses_used: int | None = None
+ next_billing_cycle_start: datetime | None = None
is_legacy_plan: bool = False
has_fixed_price: bool = False
is_current_plan_billable: bool = False
- stripe_customer_url: Optional[str] = None
- warning: Optional[str] = None
- annual_recurring_revenue: Optional[int] = None
- estimated_next_plan_revenue: Optional[int] = None
+ stripe_customer_url: str | None = None
+ warning: str | None = None
+ annual_recurring_revenue: int | None = None
+ estimated_next_plan_revenue: int | None = None
@dataclass
class MobilePushData:
total_mobile_users: int
push_notification_status: PushNotificationsEnabledStatus
- uncategorized_mobile_users: Optional[int] = None
- mobile_pushes_forwarded: Optional[int] = None
+ uncategorized_mobile_users: int | None = None
+ mobile_pushes_forwarded: int | None = None
last_mobile_push_sent: str = ""
@@ -193,9 +193,9 @@ def get_annual_invoice_count(billing_schedule: int) -> int:
def get_next_plan_data(
billing_session: BillingSession,
customer: Customer,
- current_plan: Optional[CustomerPlan] = None,
+ current_plan: CustomerPlan | None = None,
) -> NextPlanData:
- plan_offer: Optional[CustomerPlanOffer] = None
+ plan_offer: CustomerPlanOffer | None = None
# A customer can have a CustomerPlanOffer with or without a current plan.
if customer.required_plan_tier:
@@ -230,7 +230,7 @@ def get_next_plan_data(
def get_plan_data_for_support_view(
- billing_session: BillingSession, user_count: Optional[int] = None, stale_user_data: bool = False
+ billing_session: BillingSession, user_count: int | None = None, stale_user_data: bool = False
) -> PlanData:
customer = billing_session.get_customer()
plan = None
@@ -307,7 +307,7 @@ def get_plan_data_for_support_view(
return plan_data
-def get_mobile_push_data(remote_entity: Union[RemoteZulipServer, RemoteRealm]) -> MobilePushData:
+def get_mobile_push_data(remote_entity: RemoteZulipServer | RemoteRealm) -> MobilePushData:
if isinstance(remote_entity, RemoteZulipServer):
total_users = (
RemotePushDeviceToken.objects.filter(server=remote_entity)
diff --git a/corporate/models.py b/corporate/models.py
index 30d61d9903b..6690e6d8cfe 100644
--- a/corporate/models.py
+++ b/corporate/models.py
@@ -1,5 +1,5 @@
from enum import Enum
-from typing import Any, Optional, Union
+from typing import Any, Union
from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
@@ -69,7 +69,7 @@ class Customer(models.Model):
else:
return f"{self.remote_server!r} (with stripe_customer_id: {self.stripe_customer_id})"
- def get_discounted_price_for_plan(self, plan_tier: int, schedule: int) -> Optional[int]:
+ def get_discounted_price_for_plan(self, plan_tier: int, schedule: int) -> int | None:
if plan_tier != self.required_plan_tier:
return None
@@ -80,15 +80,15 @@ class Customer(models.Model):
return self.monthly_discounted_price
-def get_customer_by_realm(realm: Realm) -> Optional[Customer]:
+def get_customer_by_realm(realm: Realm) -> Customer | None:
return Customer.objects.filter(realm=realm).first()
-def get_customer_by_remote_server(remote_server: RemoteZulipServer) -> Optional[Customer]:
+def get_customer_by_remote_server(remote_server: RemoteZulipServer) -> Customer | None:
return Customer.objects.filter(remote_server=remote_server).first()
-def get_customer_by_remote_realm(remote_realm: RemoteRealm) -> Optional[Customer]: # nocoverage
+def get_customer_by_remote_realm(remote_realm: RemoteRealm) -> Customer | None: # nocoverage
return Customer.objects.filter(remote_realm=remote_realm).first()
@@ -124,7 +124,7 @@ class Event(models.Model):
def get_last_associated_event_by_type(
content_object: Union["Invoice", "PaymentIntent", "Session"], event_type: str
-) -> Optional[Event]:
+) -> Event | None:
content_type = ContentType.objects.get_for_model(type(content_object))
return Event.objects.filter(
content_type=content_type, object_id=content_object.id, type=event_type
@@ -172,7 +172,7 @@ class Session(models.Model):
session_dict["event_handler"] = event.get_event_handler_details_as_dict()
return session_dict
- def get_last_associated_event(self) -> Optional[Event]:
+ def get_last_associated_event(self) -> Event | None:
if self.status == Session.CREATED:
return None
return get_last_associated_event_by_type(self, "checkout.session.completed")
@@ -208,7 +208,7 @@ class PaymentIntent(models.Model): # nocoverage
PaymentIntent.SUCCEEDED: "succeeded",
}[self.status]
- def get_last_associated_event(self) -> Optional[Event]:
+ def get_last_associated_event(self) -> Event | None:
if self.status == PaymentIntent.SUCCEEDED:
event_type = "payment_intent.succeeded"
# TODO: Add test for this case. Not sure how to trigger naturally.
@@ -243,7 +243,7 @@ class Invoice(models.Model):
Invoice.VOID: "void",
}[self.status]
- def get_last_associated_event(self) -> Optional[Event]:
+ def get_last_associated_event(self) -> Event | None:
if self.status == Invoice.PAID:
event_type = "invoice.paid"
# TODO: Add test for this case. Not sure how to trigger naturally.
@@ -475,7 +475,7 @@ class CustomerPlan(AbstractCustomerPlan):
assert ledger_entry is not None
return ledger_entry.licenses
- def licenses_at_next_renewal(self) -> Optional[int]:
+ def licenses_at_next_renewal(self) -> int | None:
if self.status in (
CustomerPlan.DOWNGRADE_AT_END_OF_CYCLE,
CustomerPlan.DOWNGRADE_AT_END_OF_FREE_TRIAL,
@@ -492,13 +492,13 @@ class CustomerPlan(AbstractCustomerPlan):
return self.tier in self.PAID_PLAN_TIERS
-def get_current_plan_by_customer(customer: Customer) -> Optional[CustomerPlan]:
+def get_current_plan_by_customer(customer: Customer) -> CustomerPlan | None:
return CustomerPlan.objects.filter(
customer=customer, status__lt=CustomerPlan.LIVE_STATUS_THRESHOLD
).first()
-def get_current_plan_by_realm(realm: Realm) -> Optional[CustomerPlan]:
+def get_current_plan_by_realm(realm: Realm) -> CustomerPlan | None:
customer = get_customer_by_realm(realm)
if customer is None:
return None
diff --git a/corporate/tests/test_activity_views.py b/corporate/tests/test_activity_views.py
index 058f0974df3..9fe6c3d514f 100644
--- a/corporate/tests/test_activity_views.py
+++ b/corporate/tests/test_activity_views.py
@@ -1,6 +1,5 @@
import uuid
from datetime import datetime, timedelta, timezone
-from typing import Optional
from unittest import mock
from django.utils.timezone import now as timezone_now
@@ -263,7 +262,7 @@ class ActivityTest(ZulipTestCase):
)
def add_audit_log_data(
- server: RemoteZulipServer, remote_realm: Optional[RemoteRealm], realm_id: Optional[int]
+ server: RemoteZulipServer, remote_realm: RemoteRealm | None, realm_id: int | None
) -> None:
extra_data = {
RemoteRealmAuditLog.ROLE_COUNT: {
diff --git a/corporate/tests/test_remote_billing.py b/corporate/tests/test_remote_billing.py
index f0601bc7906..28d3ecac38b 100644
--- a/corporate/tests/test_remote_billing.py
+++ b/corporate/tests/test_remote_billing.py
@@ -1,5 +1,5 @@
from datetime import timedelta
-from typing import TYPE_CHECKING, Optional
+from typing import TYPE_CHECKING
from unittest import mock
import responses
@@ -50,7 +50,7 @@ class RemoteRealmBillingTestCase(BouncerTestCase):
def execute_remote_billing_authentication_flow(
self,
user: UserProfile,
- next_page: Optional[str] = None,
+ next_page: str | None = None,
expect_tos: bool = True,
confirm_tos: bool = True,
first_time_login: bool = True,
@@ -1195,7 +1195,7 @@ class RemoteServerTestCase(BouncerTestCase):
self,
email: str,
full_name: str,
- next_page: Optional[str] = None,
+ next_page: str | None = None,
expect_tos: bool = True,
confirm_tos: bool = True,
return_without_clicking_confirmation_link: bool = False,
diff --git a/corporate/tests/test_stripe.py b/corporate/tests/test_stripe.py
index 63d1295b3ad..7150de00395 100644
--- a/corporate/tests/test_stripe.py
+++ b/corporate/tests/test_stripe.py
@@ -10,18 +10,7 @@ from dataclasses import dataclass
from datetime import datetime, timedelta, timezone
from decimal import Decimal
from functools import wraps
-from typing import (
- TYPE_CHECKING,
- Any,
- Callable,
- Literal,
- Mapping,
- Optional,
- Sequence,
- TypeVar,
- Union,
- cast,
-)
+from typing import TYPE_CHECKING, Any, Callable, Literal, Mapping, Optional, Sequence, TypeVar, cast
from unittest import mock
from unittest.mock import MagicMock, Mock, patch
@@ -434,23 +423,23 @@ class StripeTestCase(ZulipTestCase):
hamlet.is_billing_admin = True
hamlet.save(update_fields=["is_billing_admin"])
- self.billing_session: Union[
- RealmBillingSession, RemoteRealmBillingSession, RemoteServerBillingSession
- ] = RealmBillingSession(user=hamlet, realm=realm)
+ self.billing_session: (
+ RealmBillingSession | RemoteRealmBillingSession | RemoteServerBillingSession
+ ) = RealmBillingSession(user=hamlet, realm=realm)
- def get_signed_seat_count_from_response(self, response: "TestHttpResponse") -> Optional[str]:
+ def get_signed_seat_count_from_response(self, response: "TestHttpResponse") -> str | None:
match = re.search(r"name=\"signed_seat_count\" value=\"(.+)\"", response.content.decode())
return match.group(1) if match else None
- def get_salt_from_response(self, response: "TestHttpResponse") -> Optional[str]:
+ def get_salt_from_response(self, response: "TestHttpResponse") -> str | None:
match = re.search(r"name=\"salt\" value=\"(\w+)\"", response.content.decode())
return match.group(1) if match else None
def get_test_card_token(
self,
attaches_to_customer: bool,
- charge_succeeds: Optional[bool] = None,
- card_provider: Optional[str] = None,
+ charge_succeeds: bool | None = None,
+ card_provider: str | None = None,
) -> str:
if attaches_to_customer:
assert charge_succeeds is not None
@@ -699,7 +688,7 @@ class StripeTestCase(ZulipTestCase):
return upgrade_json_response
def add_card_and_upgrade(
- self, user: Optional[UserProfile] = None, **kwargs: Any
+ self, user: UserProfile | None = None, **kwargs: Any
) -> stripe.Customer:
# Add card
with time_machine.travel(self.now, tick=False):
@@ -2169,7 +2158,7 @@ class StripeTest(StripeTestCase):
def check_min_licenses_error(
invoice: bool,
- licenses: Optional[int],
+ licenses: int | None,
min_licenses_in_response: int,
upgrade_params: Mapping[str, Any] = {},
) -> None:
@@ -2199,7 +2188,7 @@ class StripeTest(StripeTestCase):
)
def check_success(
- invoice: bool, licenses: Optional[int], upgrade_params: Mapping[str, Any] = {}
+ invoice: bool, licenses: int | None, upgrade_params: Mapping[str, Any] = {}
) -> None:
upgrade_params = dict(upgrade_params)
if licenses is None:
@@ -4494,8 +4483,8 @@ class StripeTest(StripeTestCase):
users_to_create: int,
create_stripe_customer: bool,
create_plan: bool,
- num_invoices: Optional[int] = None,
- ) -> tuple[Realm, Optional[CustomerPlan], list[stripe.Invoice]]:
+ num_invoices: int | None = None,
+ ) -> tuple[Realm, CustomerPlan | None, list[stripe.Invoice]]:
nonlocal test_realm_count
test_realm_count += 1
realm_string_id = "test-realm-" + str(test_realm_count)
@@ -4532,8 +4521,8 @@ class StripeTest(StripeTestCase):
class Row:
realm: Realm
expected_plan_type: int
- plan: Optional[CustomerPlan]
- expected_plan_status: Optional[int]
+ plan: CustomerPlan | None
+ expected_plan_status: int | None
expected_invoice_count: int
email_expected_to_be_sent: bool
@@ -6475,9 +6464,9 @@ class TestRemoteBillingWriteAuditLog(StripeTestCase):
event_time = timezone_now()
def assert_audit_log(
- audit_log: Union[RemoteRealmAuditLog, RemoteZulipServerAuditLog],
- acting_remote_user: Optional[Union[RemoteRealmBillingUser, RemoteServerBillingUser]],
- acting_support_user: Optional[UserProfile],
+ audit_log: RemoteRealmAuditLog | RemoteZulipServerAuditLog,
+ acting_remote_user: RemoteRealmBillingUser | RemoteServerBillingUser | None,
+ acting_support_user: UserProfile | None,
event_type: int,
event_time: datetime,
) -> None:
@@ -6503,7 +6492,7 @@ class TestRemoteBillingWriteAuditLog(StripeTestCase):
# Necessary cast or mypy doesn't understand that we can use Django's
# model .objects. style queries on this.
audit_log_model = cast(
- Union[type[RemoteRealmAuditLog], type[RemoteZulipServerAuditLog]], audit_log_class
+ type[RemoteRealmAuditLog] | type[RemoteZulipServerAuditLog], audit_log_class
)
assert isinstance(remote_user, (RemoteRealmBillingUser, RemoteServerBillingUser))
# No acting user:
diff --git a/corporate/tests/test_support_views.py b/corporate/tests/test_support_views.py
index 7b5af5e1603..e9a728453ab 100644
--- a/corporate/tests/test_support_views.py
+++ b/corporate/tests/test_support_views.py
@@ -1,5 +1,5 @@
from datetime import datetime, timedelta, timezone
-from typing import TYPE_CHECKING, Any, Optional
+from typing import TYPE_CHECKING, Any
from unittest import mock
import orjson
@@ -712,9 +712,7 @@ class TestSupportEndpoint(ZulipTestCase):
html_response,
)
- def create_invitation(
- stream: str, invitee_email: str, realm: Optional[Realm] = None
- ) -> None:
+ def create_invitation(stream: str, invitee_email: str, realm: Realm | None = None) -> None:
invite_expires_in_minutes = 10 * 24 * 60
with self.captureOnCommitCallbacks(execute=True):
self.client_post(
diff --git a/corporate/views/billing_page.py b/corporate/views/billing_page.py
index 34f8af09265..b59bbc86738 100644
--- a/corporate/views/billing_page.py
+++ b/corporate/views/billing_page.py
@@ -1,5 +1,5 @@
import logging
-from typing import Any, Literal, Optional
+from typing import Any, Literal
from django.http import HttpRequest, HttpResponse, HttpResponseNotAllowed, HttpResponseRedirect
from django.shortcuts import render
@@ -239,14 +239,13 @@ def update_plan(
request: HttpRequest,
user: UserProfile,
*,
- status: Optional[
- Annotated[
- Json[int], AfterValidator(lambda x: check_int_in(x, ALLOWED_PLANS_API_STATUS_VALUES))
- ]
- ] = None,
- licenses: Optional[Json[int]] = None,
- licenses_at_next_renewal: Optional[Json[int]] = None,
- schedule: Optional[Json[int]] = None,
+ status: Annotated[
+ Json[int], AfterValidator(lambda x: check_int_in(x, ALLOWED_PLANS_API_STATUS_VALUES))
+ ]
+ | None = None,
+ licenses: Json[int] | None = None,
+ licenses_at_next_renewal: Json[int] | None = None,
+ schedule: Json[int] | None = None,
) -> HttpResponse:
update_plan_request = UpdatePlanRequest(
status=status,
@@ -266,14 +265,13 @@ def update_plan_for_remote_realm(
request: HttpRequest,
billing_session: RemoteRealmBillingSession,
*,
- status: Optional[
- Annotated[
- Json[int], AfterValidator(lambda x: check_int_in(x, ALLOWED_PLANS_API_STATUS_VALUES))
- ]
- ] = None,
- licenses: Optional[Json[int]] = None,
- licenses_at_next_renewal: Optional[Json[int]] = None,
- schedule: Optional[Json[int]] = None,
+ status: Annotated[
+ Json[int], AfterValidator(lambda x: check_int_in(x, ALLOWED_PLANS_API_STATUS_VALUES))
+ ]
+ | None = None,
+ licenses: Json[int] | None = None,
+ licenses_at_next_renewal: Json[int] | None = None,
+ schedule: Json[int] | None = None,
) -> HttpResponse:
update_plan_request = UpdatePlanRequest(
status=status,
@@ -292,14 +290,13 @@ def update_plan_for_remote_server(
request: HttpRequest,
billing_session: RemoteServerBillingSession,
*,
- status: Optional[
- Annotated[
- Json[int], AfterValidator(lambda x: check_int_in(x, ALLOWED_PLANS_API_STATUS_VALUES))
- ]
- ] = None,
- licenses: Optional[Json[int]] = None,
- licenses_at_next_renewal: Optional[Json[int]] = None,
- schedule: Optional[Json[int]] = None,
+ status: Annotated[
+ Json[int], AfterValidator(lambda x: check_int_in(x, ALLOWED_PLANS_API_STATUS_VALUES))
+ ]
+ | None = None,
+ licenses: Json[int] | None = None,
+ licenses_at_next_renewal: Json[int] | None = None,
+ schedule: Json[int] | None = None,
) -> HttpResponse:
update_plan_request = UpdatePlanRequest(
status=status,
diff --git a/corporate/views/event_status.py b/corporate/views/event_status.py
index 70c87470e45..64733a6b793 100644
--- a/corporate/views/event_status.py
+++ b/corporate/views/event_status.py
@@ -1,5 +1,4 @@
import logging
-from typing import Optional
from django.http import HttpRequest, HttpResponse
from django.shortcuts import render
@@ -29,8 +28,8 @@ def event_status(
request: HttpRequest,
user: UserProfile,
*,
- stripe_session_id: Optional[str] = None,
- stripe_invoice_id: Optional[str] = None,
+ stripe_session_id: str | None = None,
+ stripe_invoice_id: str | None = None,
) -> HttpResponse:
event_status_request = EventStatusRequest(
stripe_session_id=stripe_session_id, stripe_invoice_id=stripe_invoice_id
@@ -46,8 +45,8 @@ def remote_realm_event_status(
request: HttpRequest,
billing_session: RemoteRealmBillingSession,
*,
- stripe_session_id: Optional[str] = None,
- stripe_invoice_id: Optional[str] = None,
+ stripe_session_id: str | None = None,
+ stripe_invoice_id: str | None = None,
) -> HttpResponse:
event_status_request = EventStatusRequest(
stripe_session_id=stripe_session_id, stripe_invoice_id=stripe_invoice_id
@@ -62,8 +61,8 @@ def remote_server_event_status(
request: HttpRequest,
billing_session: RemoteServerBillingSession,
*,
- stripe_session_id: Optional[str] = None,
- stripe_invoice_id: Optional[str] = None,
+ stripe_session_id: str | None = None,
+ stripe_invoice_id: str | None = None,
) -> HttpResponse: # nocoverage
event_status_request = EventStatusRequest(
stripe_session_id=stripe_session_id, stripe_invoice_id=stripe_invoice_id
diff --git a/corporate/views/installation_activity.py b/corporate/views/installation_activity.py
index c544a909b87..b96bc97cbbc 100644
--- a/corporate/views/installation_activity.py
+++ b/corporate/views/installation_activity.py
@@ -1,5 +1,4 @@
from collections import defaultdict
-from typing import Optional
from django.conf import settings
from django.db import connection
@@ -65,7 +64,7 @@ def get_realm_day_counts() -> dict[str, dict[str, Markup]]:
for row in rows:
counts[row["string_id"]][row["age"]] = row["cnt"]
- def format_count(cnt: int, style: Optional[str] = None) -> Markup:
+ def format_count(cnt: int, style: str | None = None) -> Markup:
if style is not None:
good_bad = style
elif cnt == min_cnt:
diff --git a/corporate/views/portico.py b/corporate/views/portico.py
index 9cbddcae121..dd4de6644da 100644
--- a/corporate/views/portico.py
+++ b/corporate/views/portico.py
@@ -1,5 +1,4 @@
from dataclasses import asdict, dataclass
-from typing import Optional
from urllib.parse import urlencode
import orjson
@@ -36,7 +35,7 @@ from zerver.models import Realm
@add_google_analytics
-def apps_view(request: HttpRequest, platform: Optional[str] = None) -> HttpResponse:
+def apps_view(request: HttpRequest, platform: str | None = None) -> HttpResponse:
if not settings.CORPORATE_ENABLED:
# This seems impossible (CORPORATE_ENABLED set to false when
# rendering a "corporate" view) -- but we add it to make
@@ -71,7 +70,7 @@ def is_customer_on_free_trial(customer_plan: CustomerPlan) -> bool:
@dataclass
class PlansPageContext:
sponsorship_url: str
- free_trial_days: Optional[int]
+ free_trial_days: int | None
on_free_trial: bool = False
sponsorship_pending: bool = False
is_sponsored: bool = False
@@ -81,10 +80,10 @@ class PlansPageContext:
is_new_customer: bool = False
on_free_tier: bool = False
- customer_plan: Optional[CustomerPlan] = None
+ customer_plan: CustomerPlan | None = None
is_legacy_server_with_scheduled_upgrade: bool = False
- legacy_server_new_plan: Optional[CustomerPlan] = None
- requested_sponsorship_plan: Optional[str] = None
+ legacy_server_new_plan: CustomerPlan | None = None
+ requested_sponsorship_plan: str | None = None
billing_base_url: str = ""
@@ -412,7 +411,7 @@ def customer_portal(
*,
return_to_billing_page: Json[bool] = False,
manual_license_management: Json[bool] = False,
- tier: Optional[Json[int]] = None,
+ tier: Json[int] | None = None,
setup_payment_by_invoice: Json[bool] = False,
) -> HttpResponseRedirect:
user = request.user
@@ -436,7 +435,7 @@ def remote_realm_customer_portal(
*,
return_to_billing_page: Json[bool] = False,
manual_license_management: Json[bool] = False,
- tier: Optional[Json[int]] = None,
+ tier: Json[int] | None = None,
setup_payment_by_invoice: Json[bool] = False,
) -> HttpResponseRedirect:
review_billing_information_url = billing_session.get_stripe_customer_portal_url(
@@ -453,7 +452,7 @@ def remote_server_customer_portal(
*,
return_to_billing_page: Json[bool] = False,
manual_license_management: Json[bool] = False,
- tier: Optional[Json[int]] = None,
+ tier: Json[int] | None = None,
setup_payment_by_invoice: Json[bool] = False,
) -> HttpResponseRedirect:
review_billing_information_url = billing_session.get_stripe_customer_portal_url(
diff --git a/corporate/views/realm_activity.py b/corporate/views/realm_activity.py
index 6f289aa694b..84840b92da9 100644
--- a/corporate/views/realm_activity.py
+++ b/corporate/views/realm_activity.py
@@ -2,7 +2,7 @@ import itertools
import re
from dataclasses import dataclass
from datetime import datetime
-from typing import Any, Collection, Optional
+from typing import Any, Collection
from django.db.models import QuerySet
from django.http import HttpRequest, HttpResponse, HttpResponseNotFound
@@ -27,8 +27,8 @@ class UserActivitySummary:
user_id: int
user_type: str
messages_sent: int
- last_heard_from: Optional[datetime]
- last_message_sent: Optional[datetime]
+ last_heard_from: datetime | None
+ last_message_sent: datetime | None
def get_user_activity_records_for_realm(realm: str) -> QuerySet[UserActivity]:
@@ -67,8 +67,8 @@ def get_user_activity_summary(records: Collection[UserActivity]) -> UserActivity
user_type = UserProfile.BOT_TYPES[bot_type]
messages = 0
- heard_from: Optional[datetime] = None
- last_sent: Optional[datetime] = None
+ heard_from: datetime | None = None
+ last_sent: datetime | None = None
for record in records:
query = str(record.query)
diff --git a/corporate/views/remote_billing_page.py b/corporate/views/remote_billing_page.py
index d30f633e84a..4f34b5b4088 100644
--- a/corporate/views/remote_billing_page.py
+++ b/corporate/views/remote_billing_page.py
@@ -1,5 +1,5 @@
import logging
-from typing import Any, Literal, Optional, Union, cast
+from typing import Any, Literal, cast
from urllib.parse import urlsplit, urlunsplit
from django.conf import settings
@@ -146,7 +146,7 @@ def get_identity_dict_from_signed_access_token(
def is_tos_consent_needed_for_user(
- remote_user: Union[RemoteRealmBillingUser, RemoteServerBillingUser],
+ remote_user: RemoteRealmBillingUser | RemoteServerBillingUser,
) -> bool:
assert settings.TERMS_OF_SERVICE_VERSION is not None
return int(settings.TERMS_OF_SERVICE_VERSION.split(".")[0]) > int(
@@ -160,7 +160,7 @@ def remote_realm_billing_finalize_login(
request: HttpRequest,
*,
signed_billing_access_token: PathOnly[str],
- full_name: Optional[str] = None,
+ full_name: str | None = None,
tos_consent: Literal[None, "true"] = None,
enable_major_release_emails: Literal[None, "true", "false"] = None,
enable_maintenance_release_emails: Literal[None, "true", "false"] = None,
@@ -496,7 +496,7 @@ def remote_realm_billing_from_login_confirmation_link(
def create_remote_billing_confirmation_link(
- obj: Union[PreregistrationRemoteRealmBillingUser, PreregistrationRemoteServerBillingUser],
+ obj: PreregistrationRemoteRealmBillingUser | PreregistrationRemoteServerBillingUser,
confirmation_type: int,
validity_in_minutes: int,
) -> str:
@@ -522,8 +522,8 @@ def create_remote_billing_confirmation_link(
def remote_billing_legacy_server_login(
request: HttpRequest,
*,
- zulip_org_id: Optional[str] = None,
- zulip_org_key: Optional[str] = None,
+ zulip_org_id: str | None = None,
+ zulip_org_key: str | None = None,
next_page: VALID_NEXT_PAGES_TYPE = None,
) -> HttpResponse:
context: dict[str, Any] = {"next_page": next_page}
@@ -674,7 +674,7 @@ def remote_billing_legacy_server_from_login_confirmation_link(
request: HttpRequest,
*,
confirmation_key: PathOnly[str],
- full_name: Optional[str] = None,
+ full_name: str | None = None,
tos_consent: Literal[None, "true"] = None,
enable_major_release_emails: Literal[None, "true", "false"] = None,
enable_maintenance_release_emails: Literal[None, "true", "false"] = None,
@@ -821,7 +821,7 @@ def generate_confirmation_link_for_server_deactivation(
def check_rate_limits(
request: HttpRequest, remote_server: RemoteZulipServer
-) -> Optional[HttpResponse]:
+) -> HttpResponse | None:
try:
rate_limit_request_by_ip(request, domain="sends_email_by_ip")
except RateLimitedError as e:
diff --git a/corporate/views/support.py b/corporate/views/support.py
index 60283d2297d..7dd3e6e6abe 100644
--- a/corporate/views/support.py
+++ b/corporate/views/support.py
@@ -3,7 +3,7 @@ from contextlib import suppress
from dataclasses import dataclass
from datetime import timedelta
from operator import attrgetter
-from typing import Any, Iterable, Optional, Union
+from typing import Any, Iterable
from urllib.parse import urlencode, urlsplit
from django import forms
@@ -215,7 +215,7 @@ def get_plan_type_string(plan_type: int) -> str:
def get_confirmations(
- types: list[int], object_ids: Iterable[int], hostname: Optional[str] = None
+ types: list[int], object_ids: Iterable[int], hostname: str | None = None
) -> list[dict[str, Any]]:
lowest_datetime = timezone_now() - timedelta(days=30)
confirmations = Confirmation.objects.filter(
@@ -332,22 +332,22 @@ VALID_BILLING_MODALITY_VALUES = Literal[
def support(
request: HttpRequest,
*,
- realm_id: Optional[Json[NonNegativeInt]] = None,
- plan_type: Optional[Json[NonNegativeInt]] = None,
- monthly_discounted_price: Optional[Json[NonNegativeInt]] = None,
- annual_discounted_price: Optional[Json[NonNegativeInt]] = None,
- minimum_licenses: Optional[Json[NonNegativeInt]] = None,
- required_plan_tier: Optional[Json[NonNegativeInt]] = None,
- new_subdomain: Optional[str] = None,
- status: Optional[VALID_STATUS_VALUES] = None,
- billing_modality: Optional[VALID_BILLING_MODALITY_VALUES] = None,
- sponsorship_pending: Optional[Json[bool]] = None,
+ realm_id: Json[NonNegativeInt] | None = None,
+ plan_type: Json[NonNegativeInt] | None = None,
+ monthly_discounted_price: Json[NonNegativeInt] | None = None,
+ annual_discounted_price: Json[NonNegativeInt] | None = None,
+ minimum_licenses: Json[NonNegativeInt] | None = None,
+ required_plan_tier: Json[NonNegativeInt] | None = None,
+ new_subdomain: str | None = None,
+ status: VALID_STATUS_VALUES | None = None,
+ billing_modality: VALID_BILLING_MODALITY_VALUES | None = None,
+ sponsorship_pending: Json[bool] | None = None,
approve_sponsorship: Json[bool] = False,
- modify_plan: Optional[VALID_MODIFY_PLAN_METHODS] = None,
+ modify_plan: VALID_MODIFY_PLAN_METHODS | None = None,
scrub_realm: Json[bool] = False,
- delete_user_by_id: Optional[Json[NonNegativeInt]] = None,
- query: Annotated[Optional[str], ApiParamConfig("q")] = None,
- org_type: Optional[Json[NonNegativeInt]] = None,
+ delete_user_by_id: Json[NonNegativeInt] | None = None,
+ query: Annotated[str | None, ApiParamConfig("q")] = None,
+ org_type: Json[NonNegativeInt] | None = None,
) -> HttpResponse:
context: dict[str, Any] = {}
@@ -580,7 +580,7 @@ def support(
def get_remote_servers_for_support(
- email_to_search: Optional[str], uuid_to_search: Optional[str], hostname_to_search: Optional[str]
+ email_to_search: str | None, uuid_to_search: str | None, hostname_to_search: str | None
) -> list["RemoteZulipServer"]:
remote_servers_query = RemoteZulipServer.objects.order_by("id")
@@ -626,24 +626,23 @@ def get_remote_servers_for_support(
def remote_servers_support(
request: HttpRequest,
*,
- query: Annotated[Optional[str], ApiParamConfig("q")] = None,
- remote_server_id: Optional[Json[NonNegativeInt]] = None,
- remote_realm_id: Optional[Json[NonNegativeInt]] = None,
- monthly_discounted_price: Optional[Json[NonNegativeInt]] = None,
- annual_discounted_price: Optional[Json[NonNegativeInt]] = None,
- minimum_licenses: Optional[Json[NonNegativeInt]] = None,
- required_plan_tier: Optional[Json[NonNegativeInt]] = None,
- fixed_price: Optional[Json[NonNegativeInt]] = None,
- sent_invoice_id: Optional[str] = None,
- sponsorship_pending: Optional[Json[bool]] = None,
+ query: Annotated[str | None, ApiParamConfig("q")] = None,
+ remote_server_id: Json[NonNegativeInt] | None = None,
+ remote_realm_id: Json[NonNegativeInt] | None = None,
+ monthly_discounted_price: Json[NonNegativeInt] | None = None,
+ annual_discounted_price: Json[NonNegativeInt] | None = None,
+ minimum_licenses: Json[NonNegativeInt] | None = None,
+ required_plan_tier: Json[NonNegativeInt] | None = None,
+ fixed_price: Json[NonNegativeInt] | None = None,
+ sent_invoice_id: str | None = None,
+ sponsorship_pending: Json[bool] | None = None,
approve_sponsorship: Json[bool] = False,
- billing_modality: Optional[VALID_BILLING_MODALITY_VALUES] = None,
- plan_end_date: Optional[
- Annotated[str, AfterValidator(lambda x: check_date("plan_end_date", x))]
- ] = None,
- modify_plan: Optional[VALID_MODIFY_PLAN_METHODS] = None,
+ billing_modality: VALID_BILLING_MODALITY_VALUES | None = None,
+ plan_end_date: Annotated[str, AfterValidator(lambda x: check_date("plan_end_date", x))]
+ | None = None,
+ modify_plan: VALID_MODIFY_PLAN_METHODS | None = None,
delete_fixed_price_next_plan: Json[bool] = False,
- remote_server_status: Optional[VALID_STATUS_VALUES] = None,
+ remote_server_status: VALID_STATUS_VALUES | None = None,
) -> HttpResponse:
context: dict[str, Any] = {}
@@ -778,7 +777,7 @@ def remote_servers_support(
uuid_to_search=uuid_to_search,
hostname_to_search=hostname_to_search,
)
- remote_server_to_max_monthly_messages: dict[int, Union[int, str]] = dict()
+ remote_server_to_max_monthly_messages: dict[int, int | str] = dict()
server_support_data: dict[int, RemoteSupportData] = {}
realm_support_data: dict[int, RemoteSupportData] = {}
remote_realms: dict[int, list[RemoteRealm]] = {}
diff --git a/corporate/views/upgrade.py b/corporate/views/upgrade.py
index 523381f639f..84dcc56950e 100644
--- a/corporate/views/upgrade.py
+++ b/corporate/views/upgrade.py
@@ -1,5 +1,4 @@
import logging
-from typing import Optional
from django.conf import settings
from django.http import HttpRequest, HttpResponse, HttpResponseRedirect
@@ -47,12 +46,11 @@ def upgrade(
],
signed_seat_count: str,
salt: str,
- license_management: Optional[
- Annotated[
- str, AfterValidator(lambda val: check_string_in(val, VALID_LICENSE_MANAGEMENT_VALUES))
- ]
- ] = None,
- licenses: Optional[Json[int]] = None,
+ license_management: Annotated[
+ str, AfterValidator(lambda val: check_string_in(val, VALID_LICENSE_MANAGEMENT_VALUES))
+ ]
+ | None = None,
+ licenses: Json[int] | None = None,
tier: Json[int] = CustomerPlan.TIER_CLOUD_STANDARD,
) -> HttpResponse:
try:
@@ -104,13 +102,12 @@ def remote_realm_upgrade(
],
signed_seat_count: str,
salt: str,
- license_management: Optional[
- Annotated[
- str, AfterValidator(lambda val: check_string_in(val, VALID_LICENSE_MANAGEMENT_VALUES))
- ]
- ] = None,
- licenses: Optional[Json[int]] = None,
- remote_server_plan_start_date: Optional[str] = None,
+ license_management: Annotated[
+ str, AfterValidator(lambda val: check_string_in(val, VALID_LICENSE_MANAGEMENT_VALUES))
+ ]
+ | None = None,
+ licenses: Json[int] | None = None,
+ remote_server_plan_start_date: str | None = None,
tier: Json[int] = CustomerPlan.TIER_SELF_HOSTED_BUSINESS,
) -> HttpResponse:
try:
@@ -160,13 +157,12 @@ def remote_server_upgrade(
],
signed_seat_count: str,
salt: str,
- license_management: Optional[
- Annotated[
- str, AfterValidator(lambda val: check_string_in(val, VALID_LICENSE_MANAGEMENT_VALUES))
- ]
- ] = None,
- licenses: Optional[Json[int]] = None,
- remote_server_plan_start_date: Optional[str] = None,
+ license_management: Annotated[
+ str, AfterValidator(lambda val: check_string_in(val, VALID_LICENSE_MANAGEMENT_VALUES))
+ ]
+ | None = None,
+ licenses: Json[int] | None = None,
+ remote_server_plan_start_date: str | None = None,
tier: Json[int] = CustomerPlan.TIER_SELF_HOSTED_BUSINESS,
) -> HttpResponse:
try:
diff --git a/manage.py b/manage.py
index 8139db3450a..f917dfe0857 100755
--- a/manage.py
+++ b/manage.py
@@ -3,7 +3,6 @@ import configparser
import os
import sys
from collections import defaultdict
-from typing import Optional
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
sys.path.append(BASE_DIR)
@@ -110,7 +109,7 @@ class FilteredManagementUtility(ManagementUtility):
return "\n".join(usage)
-def execute_from_command_line(argv: Optional[list[str]] = None) -> None:
+def execute_from_command_line(argv: list[str] | None = None) -> None:
"""Run a FilteredManagementUtility."""
utility = FilteredManagementUtility(argv)
utility.execute()
diff --git a/puppet/kandra/files/memcached_exporter b/puppet/kandra/files/memcached_exporter
index 34504e16c21..b2d0b7a8466 100755
--- a/puppet/kandra/files/memcached_exporter
+++ b/puppet/kandra/files/memcached_exporter
@@ -3,7 +3,7 @@
import contextlib
import sys
import time
-from typing import Any, Iterable, Optional, Sequence, Union
+from typing import Any, Iterable, Sequence
sys.path.append("/home/zulip/deployments/current")
from scripts.lib.setup_path import setup_path
@@ -27,8 +27,8 @@ class MemcachedCollector(Collector):
def gauge(
name: str,
doc: str,
- value: Optional[Union[float, bytes]] = None,
- labels: Optional[Sequence[str]] = None,
+ value: float | bytes | None = None,
+ labels: Sequence[str] | None = None,
) -> GaugeMetricFamily:
return GaugeMetricFamily(
f"memcached_{name}", doc, float(value) if value else None, labels
@@ -37,7 +37,7 @@ class MemcachedCollector(Collector):
def counter(
name: str,
doc: str,
- labels: Optional[Iterable[str]] = None,
+ labels: Iterable[str] | None = None,
) -> CounterMetricFamily:
return CounterMetricFamily(
f"memcached_{name}", doc, labels=list(labels) if labels is not None else None
@@ -46,8 +46,8 @@ class MemcachedCollector(Collector):
def counter_value(
name: str,
doc: str,
- value: Union[bytes, float],
- labels: Optional[dict[str, str]] = None,
+ value: bytes | float,
+ labels: dict[str, str] | None = None,
) -> CounterMetricFamily:
if labels is None:
labels = {}
diff --git a/puppet/zulip/files/nagios_plugins/zulip_app_frontend/check_send_receive_time b/puppet/zulip/files/nagios_plugins/zulip_app_frontend/check_send_receive_time
index e32594c07a0..3568c52e706 100755
--- a/puppet/zulip/files/nagios_plugins/zulip_app_frontend/check_send_receive_time
+++ b/puppet/zulip/files/nagios_plugins/zulip_app_frontend/check_send_receive_time
@@ -13,7 +13,7 @@ import random
import sys
import time
import traceback
-from typing import Any, Literal, NoReturn, Optional
+from typing import Any, Literal, NoReturn
sys.path.append(".")
sys.path.append("/home/zulip/deployments/current")
@@ -50,8 +50,8 @@ options = parser.parse_args()
def report(
state: Literal["ok", "warning", "critical", "unknown"],
- timestamp: Optional[float] = None,
- msg: Optional[str] = None,
+ timestamp: float | None = None,
+ msg: str | None = None,
) -> NoReturn:
if msg is None:
msg = f"send time was {timestamp}"
diff --git a/puppet/zulip/files/postgresql/process_fts_updates b/puppet/zulip/files/postgresql/process_fts_updates
index 6aece323067..c80834019bc 100755
--- a/puppet/zulip/files/postgresql/process_fts_updates
+++ b/puppet/zulip/files/postgresql/process_fts_updates
@@ -41,7 +41,6 @@ import os
import select
import sys
import time
-from typing import Optional
import psycopg2
import psycopg2.extensions
@@ -164,7 +163,7 @@ except (ImportError, PermissionError):
pg_args["host"] = "localhost"
pg_args["dbname"] = get_config(config_file, "postgresql", "database_name", "zulip")
-conn: Optional[psycopg2.extensions.connection]
+conn: psycopg2.extensions.connection | None
if options.nagios_check:
# Nagios connects as itself, unless you specify otherwise
diff --git a/puppet/zulip/files/postgresql/wal-g-exporter b/puppet/zulip/files/postgresql/wal-g-exporter
index 8795e61c658..280c047faec 100755
--- a/puppet/zulip/files/postgresql/wal-g-exporter
+++ b/puppet/zulip/files/postgresql/wal-g-exporter
@@ -9,12 +9,12 @@ import sys
from collections import defaultdict
from datetime import datetime, timedelta, timezone
from http.server import BaseHTTPRequestHandler, HTTPServer
-from typing import Mapping, Optional, Protocol
+from typing import Mapping, Protocol
from urllib.parse import parse_qs, urlsplit
class GaugeMetric(Protocol):
- def __call__(self, value: float, labels: Optional[Mapping[str, str]] = None, /) -> None:
+ def __call__(self, value: float, labels: Mapping[str, str] | None = None, /) -> None:
pass
@@ -27,7 +27,7 @@ class WalGPrometheusServer(BaseHTTPRequestHandler):
server_version = "wal-g-prometheus-server/1.0"
def gauge(
- self, name: str, description: Optional[str] = None, default_value: Optional[float] = None
+ self, name: str, description: str | None = None, default_value: float | None = None
) -> GaugeMetric:
if name in self.metrics:
raise ValueError(f"Redefinition of {name} metric")
@@ -35,7 +35,7 @@ class WalGPrometheusServer(BaseHTTPRequestHandler):
if description is not None:
self.metrics[name].append(f"# HELP {self.METRIC_PREFIX}{name} {description}")
- def inner(value: float, labels: Optional[Mapping[str, str]] = None) -> None:
+ def inner(value: float, labels: Mapping[str, str] | None = None) -> None:
label_str = ""
if labels:
label_str = "{" + ",".join(f'{k}="{v}"' for k, v in labels.items()) + "}"
diff --git a/scripts/lib/setup_venv.py b/scripts/lib/setup_venv.py
index bf95663b5e6..57ad06b34b3 100644
--- a/scripts/lib/setup_venv.py
+++ b/scripts/lib/setup_venv.py
@@ -2,7 +2,6 @@ import logging
import os
import shutil
import subprocess
-from typing import Optional
from scripts.lib.hash_reqs import expand_reqs, python_version
from scripts.lib.zulip_tools import ENDC, WARNING, os_families, run, run_as_root
@@ -276,7 +275,7 @@ def generate_hash(requirements_file: str) -> str:
def setup_virtualenv(
- target_venv_path: Optional[str],
+ target_venv_path: str | None,
requirements_file: str,
patch_activate_script: bool = False,
) -> str:
diff --git a/scripts/lib/sharding.py b/scripts/lib/sharding.py
index c8b66010753..5dbf11117bc 100755
--- a/scripts/lib/sharding.py
+++ b/scripts/lib/sharding.py
@@ -5,7 +5,6 @@ import json
import os
import subprocess
import sys
-from typing import Union
BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
sys.path.append(BASE_DIR)
@@ -46,8 +45,8 @@ def write_updated_configs() -> None:
nginx_sharding_conf_f.write("map $host $tornado_server {\n")
nginx_sharding_conf_f.write(" default http://tornado9800;\n")
- shard_map: dict[str, Union[int, list[int]]] = {}
- shard_regexes: list[tuple[str, Union[int, list[int]]]] = []
+ shard_map: dict[str, int | list[int]] = {}
+ shard_regexes: list[tuple[str, int | list[int]]] = []
external_host = subprocess.check_output(
[os.path.join(BASE_DIR, "scripts/get-django-setting"), "EXTERNAL_HOST"],
text=True,
diff --git a/scripts/lib/supervisor.py b/scripts/lib/supervisor.py
index ee64067c930..f6f3dd3b1b9 100644
--- a/scripts/lib/supervisor.py
+++ b/scripts/lib/supervisor.py
@@ -1,7 +1,6 @@
import socket
import time
from http.client import HTTPConnection
-from typing import Optional, Union
from xmlrpc import client
from typing_extensions import override
@@ -32,9 +31,7 @@ class UnixStreamTransport(client.Transport):
super().__init__()
@override
- def make_connection(
- self, host: Union[tuple[str, dict[str, str]], str]
- ) -> UnixStreamHTTPConnection:
+ def make_connection(self, host: tuple[str, dict[str, str]] | str) -> UnixStreamHTTPConnection:
return UnixStreamHTTPConnection(self.socket_path)
@@ -45,7 +42,7 @@ def rpc() -> client.ServerProxy:
def list_supervisor_processes(
- filter_names: Optional[list[str]] = None, *, only_running: Optional[bool] = None
+ filter_names: list[str] | None = None, *, only_running: bool | None = None
) -> list[str]:
results = []
processes = rpc().supervisor.getAllProcessInfo()
diff --git a/scripts/lib/upgrade-zulip-stage-3 b/scripts/lib/upgrade-zulip-stage-3
index ecfa13a212e..0a38b7bea92 100755
--- a/scripts/lib/upgrade-zulip-stage-3
+++ b/scripts/lib/upgrade-zulip-stage-3
@@ -14,7 +14,7 @@ import shutil
import subprocess
import sys
import time
-from typing import Literal, Optional
+from typing import Literal
os.environ["PYTHONUNBUFFERED"] = "y"
@@ -122,7 +122,7 @@ old_merge_base = (
# Check if rabbitmq port 25672 is listening on anything except 127.0.0.1
rabbitmq_dist_listen = listening_publicly(25672)
# Check the erlang magic cookie size
-cookie_size: Optional[int] = None
+cookie_size: int | None = None
if os.path.exists("/var/lib/rabbitmq/.erlang.cookie"):
with open("/var/lib/rabbitmq/.erlang.cookie") as cookie_fh:
cookie_size = len(cookie_fh.readline())
diff --git a/scripts/lib/zulip_tools.py b/scripts/lib/zulip_tools.py
index 77f594b1a9d..d65c00b889a 100755
--- a/scripts/lib/zulip_tools.py
+++ b/scripts/lib/zulip_tools.py
@@ -16,7 +16,7 @@ import sys
import time
import uuid
from datetime import datetime, timedelta
-from typing import IO, Any, Literal, Optional, Sequence, Union, overload
+from typing import IO, Any, Literal, Sequence, overload
from urllib.parse import SplitResult
import zoneinfo
@@ -586,7 +586,7 @@ def get_config(
section: str,
key: str,
default_value: None = None,
-) -> Optional[str]: ...
+) -> str | None: ...
@overload
def get_config(
config_file: configparser.RawConfigParser,
@@ -602,8 +602,8 @@ def get_config(
config_file: configparser.RawConfigParser,
section: str,
key: str,
- default_value: Union[str, bool, None] = None,
-) -> Union[str, bool, None]:
+ default_value: str | bool | None = None,
+) -> str | bool | None:
if config_file.has_option(section, key):
val = config_file.get(section, key)
if isinstance(default_value, bool):
@@ -726,8 +726,8 @@ def listening_publicly(port: int) -> list[str]:
def atomic_nagios_write(
name: str,
status: Literal["ok", "warning", "critical", "unknown"],
- message: Optional[str] = None,
- event_time: Optional[int] = None,
+ message: str | None = None,
+ event_time: int | None = None,
) -> int:
if message is None:
message = status
diff --git a/scripts/log-search b/scripts/log-search
index 653bfaaa332..351888890b8 100755
--- a/scripts/log-search
+++ b/scripts/log-search
@@ -10,7 +10,7 @@ import signal
import sys
from datetime import date, datetime, timedelta, timezone
from enum import Enum, auto
-from typing import Match, Optional, TextIO
+from typing import Match, TextIO
ZULIP_PATH = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(ZULIP_PATH)
@@ -428,7 +428,7 @@ def passes_filters(
return not args.no_other
-last_match_end: Optional[datetime] = None
+last_match_end: datetime | None = None
def print_line(
diff --git a/scripts/setup/compare-settings-to-template b/scripts/setup/compare-settings-to-template
index f49e07d6f51..f4280745e9d 100755
--- a/scripts/setup/compare-settings-to-template
+++ b/scripts/setup/compare-settings-to-template
@@ -4,7 +4,6 @@ import difflib
import os
import re
import sys
-from typing import Optional
BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
sys.path.append(BASE_DIR)
@@ -25,7 +24,7 @@ import requests
print("Fetching old versions of setting templates from Github...")
templ = {}
-url: Optional[str] = "https://api.github.com/repos/zulip/zulip/tags?per_page=100"
+url: str | None = "https://api.github.com/repos/zulip/zulip/tags?per_page=100"
while url is not None:
resp = requests.get(url)
diff --git a/tools/check-issue-labels b/tools/check-issue-labels
index 081d5487d92..20f659f41b5 100755
--- a/tools/check-issue-labels
+++ b/tools/check-issue-labels
@@ -4,7 +4,7 @@ import configparser
import os
import re
import sys
-from typing import Any, Optional
+from typing import Any
import requests
@@ -39,7 +39,7 @@ def is_issue(item: dict[str, Any]) -> bool:
return "issues" in item["html_url"]
-def get_next_page_url(link_header: str) -> Optional[str]:
+def get_next_page_url(link_header: str) -> str | None:
matches = re.findall(r"\<(\S+)\>; rel=\"next\"", link_header)
try:
return matches[0]
@@ -63,7 +63,7 @@ def check_issue_labels() -> None:
)
sys.exit(1)
- next_page_url: Optional[str] = "https://api.github.com/repos/zulip/zulip/issues"
+ next_page_url: str | None = "https://api.github.com/repos/zulip/zulip/issues"
unlabeled_issue_urls: list[str] = []
while next_page_url:
try:
diff --git a/tools/check-schemas b/tools/check-schemas
index 2b2a18d857c..c3b7da2ddbd 100755
--- a/tools/check-schemas
+++ b/tools/check-schemas
@@ -14,7 +14,7 @@ import difflib
import os
import subprocess
import sys
-from typing import Any, Callable, Optional
+from typing import Any, Callable
import orjson
@@ -87,7 +87,7 @@ DEPRECATED_EVENTS = [
]
-def get_event_checker(event: dict[str, Any]) -> Optional[Callable[[str, dict[str, Any]], None]]:
+def get_event_checker(event: dict[str, Any]) -> Callable[[str, dict[str, Any]], None] | None:
name = event["type"]
if "op" in event:
name += "_" + event["op"]
diff --git a/tools/documentation_crawler/documentation_crawler/commands/crawl_with_status.py b/tools/documentation_crawler/documentation_crawler/commands/crawl_with_status.py
index 184df7fa048..0962afed506 100644
--- a/tools/documentation_crawler/documentation_crawler/commands/crawl_with_status.py
+++ b/tools/documentation_crawler/documentation_crawler/commands/crawl_with_status.py
@@ -1,5 +1,4 @@
import optparse
-from typing import Union
from scrapy.commands import crawl
from scrapy.crawler import Crawler
@@ -10,7 +9,7 @@ class Command(crawl.Command):
crawlers = []
real_create_crawler = self.crawler_process.create_crawler
- def create_crawler(crawler_or_spidercls: Union[Crawler, str]) -> Crawler:
+ def create_crawler(crawler_or_spidercls: Crawler | str) -> Crawler:
crawler = real_create_crawler(crawler_or_spidercls)
crawlers.append(crawler)
return crawler
diff --git a/tools/documentation_crawler/documentation_crawler/spiders/common/spiders.py b/tools/documentation_crawler/documentation_crawler/spiders/common/spiders.py
index 7816b4f1055..ded0da2cf41 100644
--- a/tools/documentation_crawler/documentation_crawler/spiders/common/spiders.py
+++ b/tools/documentation_crawler/documentation_crawler/spiders/common/spiders.py
@@ -1,7 +1,7 @@
import json
import os
import re
-from typing import Callable, Iterator, Optional, Union
+from typing import Callable, Iterator
from urllib.parse import urlsplit
import scrapy
@@ -58,7 +58,7 @@ ZULIP_SERVER_GITHUB_DIRECTORY_PATH_PREFIX = "/zulip/zulip/tree/main"
class BaseDocumentationSpider(scrapy.Spider):
- name: Optional[str] = None
+ name: str | None = None
# Exclude domain address.
deny_domains: list[str] = []
start_urls: list[str] = []
@@ -155,7 +155,7 @@ class BaseDocumentationSpider(scrapy.Spider):
if url.startswith("http://localhost:9981/plans"):
return
- callback: Callable[[Response], Optional[Iterator[Request]]] = self.parse
+ callback: Callable[[Response], Iterator[Request] | None] = self.parse
dont_filter = False
method = "GET"
if self._is_external_url(url):
@@ -233,7 +233,7 @@ class BaseDocumentationSpider(scrapy.Spider):
request.dont_filter = True
yield request
- def error_callback(self, failure: Failure) -> Optional[Union[Failure, Iterator[Request]]]:
+ def error_callback(self, failure: Failure) -> Failure | Iterator[Request] | None:
if isinstance(failure.value, HttpError):
response = failure.value.response
# Hack: The filtering above does not catch this URL,
diff --git a/tools/fetch-contributor-data b/tools/fetch-contributor-data
index 4346fa9f947..5bafd1ee4f9 100755
--- a/tools/fetch-contributor-data
+++ b/tools/fetch-contributor-data
@@ -11,7 +11,6 @@ import os
import sys
import unicodedata
from datetime import datetime, timezone
-from typing import Optional, Union
sys.path.insert(0, os.path.join(os.path.dirname(__file__), ".."))
from scripts.lib.setup_path import setup_path
@@ -42,15 +41,15 @@ args = parser.parse_args()
class ContributorsJSON(TypedDict):
date: str
- contributors: list[dict[str, Union[int, str]]]
+ contributors: list[dict[str, int | str]]
class Contributor(TypedDict):
- avatar_url: Optional[str]
+ avatar_url: str | None
contributions: int
- login: Optional[str]
- email: Optional[str]
- name: Optional[str]
+ login: str | None
+ email: str | None
+ name: str | None
logger = logging.getLogger("zulip.fetch_contributors_json")
@@ -134,7 +133,7 @@ def update_contributor_data_file() -> None:
]
data: ContributorsJSON = dict(date=str(datetime.now(tz=timezone.utc).date()), contributors=[])
- contributor_username_to_data: dict[str, dict[str, Union[str, int]]] = {}
+ contributor_username_to_data: dict[str, dict[str, str | int]] = {}
for repo_name in repo_names:
contributors = fetch_contributors(repo_name, args.max_retries)
diff --git a/tools/lib/pretty_print.py b/tools/lib/pretty_print.py
index ae322e1b9a6..ae1374656b4 100644
--- a/tools/lib/pretty_print.py
+++ b/tools/lib/pretty_print.py
@@ -1,5 +1,4 @@
import subprocess
-from typing import Optional
from zulint.printer import BOLDRED, CYAN, ENDC, GREEN
@@ -40,7 +39,7 @@ def token_allows_children_to_skip_indents(token: Token) -> bool:
def adjust_block_indentation(tokens: list[Token], fn: str) -> None:
- start_token: Optional[Token] = None
+ start_token: Token | None = None
for token in tokens:
if token.kind in ("indent", "whitespace", "newline"):
diff --git a/tools/lib/template_parser.py b/tools/lib/template_parser.py
index f5cda739e95..ff49cb874bf 100644
--- a/tools/lib/template_parser.py
+++ b/tools/lib/template_parser.py
@@ -1,4 +1,4 @@
-from typing import Callable, Optional
+from typing import Callable
from typing_extensions import override
@@ -17,7 +17,7 @@ class TemplateParserError(Exception):
class TokenizationError(Exception):
- def __init__(self, message: str, line_content: Optional[str] = None) -> None:
+ def __init__(self, message: str, line_content: str | None = None) -> None:
self.message = message
self.line_content = line_content
@@ -39,19 +39,19 @@ class Token:
self.line_span = line_span
# These get set during the validation pass.
- self.start_token: Optional[Token] = None
- self.end_token: Optional[Token] = None
+ self.start_token: Token | None = None
+ self.end_token: Token | None = None
# These get set during the pretty-print phase.
self.new_s = ""
- self.indent: Optional[str] = None
- self.orig_indent: Optional[str] = None
- self.child_indent: Optional[str] = None
+ self.indent: str | None = None
+ self.orig_indent: str | None = None
+ self.child_indent: str | None = None
self.indent_is_final = False
- self.parent_token: Optional[Token] = None
+ self.parent_token: Token | None = None
-def tokenize(text: str, template_format: Optional[str] = None) -> list[Token]:
+def tokenize(text: str, template_format: str | None = None) -> list[Token]:
in_code_block = False
def advance(n: int) -> None:
@@ -307,7 +307,7 @@ HTML_INLINE_TAGS = {
}
-def tag_flavor(token: Token) -> Optional[str]:
+def tag_flavor(token: Token) -> str | None:
kind = token.kind
tag = token.tag
if kind in (
@@ -352,9 +352,9 @@ def tag_flavor(token: Token) -> Optional[str]:
def validate(
- fn: Optional[str] = None,
- text: Optional[str] = None,
- template_format: Optional[str] = None,
+ fn: str | None = None,
+ text: str | None = None,
+ template_format: str | None = None,
) -> list[Token]:
assert fn or text
@@ -379,12 +379,12 @@ def validate(
prevent_whitespace_violations(fn, tokens)
class State:
- def __init__(self, func: Callable[[Optional[Token]], None]) -> None:
+ def __init__(self, func: Callable[[Token | None], None]) -> None:
self.depth = 0
self.foreign = False
self.matcher = func
- def no_start_tag(token: Optional[Token]) -> None:
+ def no_start_tag(token: Token | None) -> None:
assert token
raise TemplateParserError(
f"""
@@ -410,7 +410,7 @@ def validate(
if start_tag in ["math", "svg"]:
state.foreign = True
- def f(end_token: Optional[Token]) -> None:
+ def f(end_token: Token | None) -> None:
if end_token is None:
raise TemplateParserError(
f"""
@@ -431,7 +431,7 @@ def validate(
end_line = end_token.line
end_col = end_token.col
- def report_problem() -> Optional[str]:
+ def report_problem() -> str | None:
if (start_tag == "code") and (end_line == start_line + 1):
return "Code tag is split across two lines."
diff --git a/tools/lib/test_script.py b/tools/lib/test_script.py
index 6d7821a6efc..c558cebbe9c 100644
--- a/tools/lib/test_script.py
+++ b/tools/lib/test_script.py
@@ -3,7 +3,7 @@ import os
import subprocess
import sys
from argparse import ArgumentParser
-from typing import Iterable, Optional
+from typing import Iterable
from scripts.lib.zulip_tools import get_dev_uuid_var_path
from version import PROVISION_VERSION
@@ -49,7 +49,7 @@ Do this: `./tools/provision`
"""
-def get_provisioning_status() -> tuple[bool, Optional[str]]:
+def get_provisioning_status() -> tuple[bool, str | None]:
version_file = get_version_file()
if not os.path.exists(version_file):
# If the developer doesn't have a version_file written by
diff --git a/tools/lib/test_server.py b/tools/lib/test_server.py
index 84f360c50ea..6675a05e1b7 100644
--- a/tools/lib/test_server.py
+++ b/tools/lib/test_server.py
@@ -3,7 +3,7 @@ import subprocess
import sys
import time
from contextlib import ExitStack, contextmanager
-from typing import Iterator, Optional
+from typing import Iterator
# Verify the Zulip venv is available.
from tools.lib import sanity_check
@@ -32,7 +32,7 @@ def set_up_django(external_host: str) -> None:
os.environ["PYTHONUNBUFFERED"] = "y"
-def assert_server_running(server: "subprocess.Popen[bytes]", log_file: Optional[str]) -> None:
+def assert_server_running(server: "subprocess.Popen[bytes]", log_file: str | None) -> None:
"""Get the exit code of the server, or None if it is still running."""
if server.poll() is not None:
message = "Server died unexpectedly!"
@@ -41,7 +41,7 @@ def assert_server_running(server: "subprocess.Popen[bytes]", log_file: Optional[
raise RuntimeError(message)
-def server_is_up(server: "subprocess.Popen[bytes]", log_file: Optional[str]) -> bool:
+def server_is_up(server: "subprocess.Popen[bytes]", log_file: str | None) -> bool:
assert_server_running(server, log_file)
try:
# We could get a 501 error if the reverse proxy is up but the Django app isn't.
@@ -55,7 +55,7 @@ def server_is_up(server: "subprocess.Popen[bytes]", log_file: Optional[str]) ->
def test_server_running(
skip_provision_check: bool = False,
external_host: str = "testserver",
- log_file: Optional[str] = None,
+ log_file: str | None = None,
dots: bool = False,
) -> Iterator[None]:
with ExitStack() as stack:
diff --git a/tools/screenshots/generate-integration-docs-screenshot b/tools/screenshots/generate-integration-docs-screenshot
index 7030715e4c1..2d34a98f6f7 100755
--- a/tools/screenshots/generate-integration-docs-screenshot
+++ b/tools/screenshots/generate-integration-docs-screenshot
@@ -6,7 +6,7 @@ import base64
import os
import subprocess
import sys
-from typing import Any, Optional
+from typing import Any
from urllib.parse import parse_qsl, urlencode
SCREENSHOTS_DIR = os.path.abspath(os.path.dirname(__file__))
@@ -56,7 +56,7 @@ from zerver.models.realms import get_realm
from zerver.models.users import get_user_by_delivery_email
-def create_integration_bot(integration: Integration, bot_name: Optional[str] = None) -> UserProfile:
+def create_integration_bot(integration: Integration, bot_name: str | None = None) -> UserProfile:
realm = get_realm("zulip")
owner = get_user_by_delivery_email("[email protected]", realm)
bot_email = f"{integration.name}[email protected]"
diff --git a/tools/screenshots/generate-user-messages-screenshot b/tools/screenshots/generate-user-messages-screenshot
index 40ad3578b2f..a0746bddb6f 100755
--- a/tools/screenshots/generate-user-messages-screenshot
+++ b/tools/screenshots/generate-user-messages-screenshot
@@ -6,7 +6,6 @@ import os
import subprocess
import sys
from datetime import datetime, timezone
-from typing import Optional
from django.conf import settings
from pydantic import BaseModel, ConfigDict
@@ -86,7 +85,7 @@ class MessageThread(BaseModel):
date: dict[str, int]
-def create_user(full_name: str, avatar_filename: Optional[str]) -> None:
+def create_user(full_name: str, avatar_filename: str | None) -> None:
email = f'{full_name.replace(" ", "")}@zulip.com'
try:
user = UserProfile.objects.get(realm=realm, full_name=full_name)
@@ -104,7 +103,7 @@ def set_avatar(user: UserProfile, filename: str) -> None:
def create_and_subscribe_stream(
- stream_name: str, users: list[str], color: Optional[str] = None, invite_only: bool = False
+ stream_name: str, users: list[str], color: str | None = None, invite_only: bool = False
) -> None:
stream = ensure_stream(realm, stream_name, invite_only=invite_only, acting_user=DEFAULT_USER)
bulk_add_subscriptions(
@@ -138,7 +137,7 @@ def send_stream_messages(
subscribers["Notification Bot"] = NOTIFICATION_BOT
- messages: list[Optional[SendMessageRequest]] = []
+ messages: list[SendMessageRequest | None] = []
for message in staged_messages:
date_sent = message["date"]
diff --git a/tools/setup/emoji/build_emoji b/tools/setup/emoji/build_emoji
index f399054f94e..ad7e1fc66bd 100755
--- a/tools/setup/emoji/build_emoji
+++ b/tools/setup/emoji/build_emoji
@@ -5,7 +5,7 @@
import os
import shutil
import sys
-from typing import Any, Iterator, Optional, Sequence
+from typing import Any, Iterator, Sequence
import orjson
@@ -290,7 +290,7 @@ def setup_emoji_farms(cache_path: str, emoji_data: list[dict[str, Any]]) -> None
def setup_emoji_farm(
emojiset: str,
emoji_data: list[dict[str, Any]],
- alt_name: Optional[str] = None,
+ alt_name: str | None = None,
fallback_emoji_data: Sequence[dict[str, Any]] = [],
) -> None:
# `alt_name` is an optional parameter that we use to avoid duplicating below
diff --git a/tools/test-queue-worker-reload b/tools/test-queue-worker-reload
index 5d5080babab..62a35b59484 100755
--- a/tools/test-queue-worker-reload
+++ b/tools/test-queue-worker-reload
@@ -5,7 +5,6 @@ import subprocess
import sys
import time
import types
-from typing import Optional
sys.path.insert(0, os.path.join(os.path.dirname(__file__), ".."))
@@ -23,7 +22,7 @@ def check_worker_launch(run_dev: "subprocess.Popen[str]") -> bool:
failed = False
i = 0
- def on_timer(signum: int, frame: Optional[types.FrameType]) -> None:
+ def on_timer(signum: int, frame: types.FrameType | None) -> None:
nonlocal failed, i
sys.stdout.write(".")
sys.stdout.flush()
diff --git a/tools/tests/test_pretty_print.py b/tools/tests/test_pretty_print.py
index 0e8a89a2c79..86facc58695 100644
--- a/tools/tests/test_pretty_print.py
+++ b/tools/tests/test_pretty_print.py
@@ -1,5 +1,4 @@
import unittest
-from typing import Optional
from tools.lib.pretty_print import pretty_print_html
from tools.lib.template_parser import validate
@@ -281,7 +280,7 @@ GOOD_HTML11 = """
"""
-def pretty_print(html: str, template_format: Optional[str] = None) -> str:
+def pretty_print(html: str, template_format: str | None = None) -> str:
fn = "<test str>"
tokens = validate(fn=fn, text=html, template_format=template_format)
return pretty_print_html(tokens, fn=fn)
diff --git a/tools/tests/test_template_parser.py b/tools/tests/test_template_parser.py
index 66d506a8aca..5ec358073ac 100644
--- a/tools/tests/test_template_parser.py
+++ b/tools/tests/test_template_parser.py
@@ -1,6 +1,5 @@
import sys
import unittest
-from typing import Optional
try:
from tools.lib.template_parser import (
@@ -18,9 +17,9 @@ class ParserTest(unittest.TestCase):
def _assert_validate_error(
self,
error: str,
- fn: Optional[str] = None,
- text: Optional[str] = None,
- template_format: Optional[str] = None,
+ fn: str | None = None,
+ text: str | None = None,
+ template_format: str | None = None,
) -> None:
with self.assertRaisesRegex(TemplateParserError, error):
validate(fn=fn, text=text, template_format=template_format)
diff --git a/tools/webpack b/tools/webpack
index 70098fa5564..1e95f363835 100755
--- a/tools/webpack
+++ b/tools/webpack
@@ -4,7 +4,7 @@ import json
import os
import subprocess
import sys
-from typing import NoReturn, Optional
+from typing import NoReturn
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))
@@ -14,7 +14,7 @@ os.chdir(os.path.join(os.path.dirname(__file__), "../web"))
from version import ZULIP_VERSION
-def build_for_prod_or_puppeteer(quiet: bool, config_name: Optional[str] = None) -> NoReturn:
+def build_for_prod_or_puppeteer(quiet: bool, config_name: str | None = None) -> NoReturn:
"""Builds for production, writing the output to disk"""
with open("/proc/meminfo") as meminfo:
diff --git a/zerver/actions/bots.py b/zerver/actions/bots.py
index 5c30ee50a24..e3065d1af5a 100644
--- a/zerver/actions/bots.py
+++ b/zerver/actions/bots.py
@@ -1,5 +1,3 @@
-from typing import Optional, Union
-
from django.db import transaction
from django.utils.timezone import now as timezone_now
@@ -12,7 +10,7 @@ from zerver.tornado.django_api import send_event_on_commit
def send_bot_owner_update_events(
- user_profile: UserProfile, bot_owner: UserProfile, previous_owner: Optional[UserProfile]
+ user_profile: UserProfile, bot_owner: UserProfile, previous_owner: UserProfile | None
) -> None:
update_users = bot_owner_user_ids(user_profile)
@@ -73,7 +71,7 @@ def send_bot_owner_update_events(
def remove_bot_from_inaccessible_private_streams(
- user_profile: UserProfile, *, acting_user: Optional[UserProfile]
+ user_profile: UserProfile, *, acting_user: UserProfile | None
) -> None:
assert user_profile.bot_owner is not None
@@ -102,7 +100,7 @@ def remove_bot_from_inaccessible_private_streams(
@transaction.atomic(durable=True)
def do_change_bot_owner(
- user_profile: UserProfile, bot_owner: UserProfile, acting_user: Union[UserProfile, None]
+ user_profile: UserProfile, bot_owner: UserProfile, acting_user: UserProfile | None
) -> None:
previous_owner = user_profile.bot_owner
user_profile.bot_owner = bot_owner
@@ -123,7 +121,7 @@ def do_change_bot_owner(
@transaction.atomic(durable=True)
def do_change_default_sending_stream(
- user_profile: UserProfile, stream: Optional[Stream], *, acting_user: Optional[UserProfile]
+ user_profile: UserProfile, stream: Stream | None, *, acting_user: UserProfile | None
) -> None:
old_value = user_profile.default_sending_stream_id
user_profile.default_sending_stream = stream
@@ -144,7 +142,7 @@ def do_change_default_sending_stream(
if user_profile.is_bot:
if stream:
- stream_name: Optional[str] = stream.name
+ stream_name: str | None = stream.name
else:
stream_name = None
event = dict(
@@ -164,7 +162,7 @@ def do_change_default_sending_stream(
@transaction.atomic(durable=True)
def do_change_default_events_register_stream(
- user_profile: UserProfile, stream: Optional[Stream], *, acting_user: Optional[UserProfile]
+ user_profile: UserProfile, stream: Stream | None, *, acting_user: UserProfile | None
) -> None:
old_value = user_profile.default_events_register_stream_id
user_profile.default_events_register_stream = stream
@@ -185,7 +183,7 @@ def do_change_default_events_register_stream(
if user_profile.is_bot:
if stream:
- stream_name: Optional[str] = stream.name
+ stream_name: str | None = stream.name
else:
stream_name = None
@@ -206,7 +204,7 @@ def do_change_default_events_register_stream(
@transaction.atomic(durable=True)
def do_change_default_all_public_streams(
- user_profile: UserProfile, value: bool, *, acting_user: Optional[UserProfile]
+ user_profile: UserProfile, value: bool, *, acting_user: UserProfile | None
) -> None:
old_value = user_profile.default_all_public_streams
user_profile.default_all_public_streams = value
diff --git a/zerver/actions/create_realm.py b/zerver/actions/create_realm.py
index 2f50b8f731b..b0be99393d0 100644
--- a/zerver/actions/create_realm.py
+++ b/zerver/actions/create_realm.py
@@ -1,6 +1,6 @@
import logging
from datetime import datetime, timedelta
-from typing import Any, Optional
+from typing import Any
from django.conf import settings
from django.db import transaction
@@ -55,7 +55,7 @@ def do_change_realm_subdomain(
realm: Realm,
new_subdomain: str,
*,
- acting_user: Optional[UserProfile],
+ acting_user: UserProfile | None,
add_deactivated_redirect: bool = True,
) -> None:
"""Changing a realm's subdomain is a highly disruptive operation,
@@ -136,7 +136,7 @@ def set_realm_permissions_based_on_org_type(realm: Realm) -> None:
@transaction.atomic(savepoint=False)
def set_default_for_realm_permission_group_settings(
- realm: Realm, group_settings_defaults_for_org_types: Optional[dict[str, dict[int, str]]] = None
+ realm: Realm, group_settings_defaults_for_org_types: dict[str, dict[int, str]] | None = None
) -> None:
system_groups_dict = get_role_based_system_groups_dict(realm)
@@ -182,19 +182,19 @@ def do_create_realm(
string_id: str,
name: str,
*,
- emails_restricted_to_domains: Optional[bool] = None,
- description: Optional[str] = None,
- invite_required: Optional[bool] = None,
- plan_type: Optional[int] = None,
- org_type: Optional[int] = None,
- default_language: Optional[str] = None,
- date_created: Optional[datetime] = None,
+ emails_restricted_to_domains: bool | None = None,
+ description: str | None = None,
+ invite_required: bool | None = None,
+ plan_type: int | None = None,
+ org_type: int | None = None,
+ default_language: str | None = None,
+ date_created: datetime | None = None,
is_demo_organization: bool = False,
- enable_read_receipts: Optional[bool] = None,
- enable_spectator_access: Optional[bool] = None,
- prereg_realm: Optional[PreregistrationRealm] = None,
- how_realm_creator_found_zulip: Optional[str] = None,
- how_realm_creator_found_zulip_extra_context: Optional[str] = None,
+ enable_read_receipts: bool | None = None,
+ enable_spectator_access: bool | None = None,
+ prereg_realm: PreregistrationRealm | None = None,
+ how_realm_creator_found_zulip: str | None = None,
+ how_realm_creator_found_zulip_extra_context: str | None = None,
) -> Realm:
if string_id in [settings.SOCIAL_AUTH_SUBDOMAIN, settings.SELF_HOSTING_MANAGEMENT_SUBDOMAIN]:
raise AssertionError(
diff --git a/zerver/actions/create_user.py b/zerver/actions/create_user.py
index e0a85e77114..20dba8ed897 100644
--- a/zerver/actions/create_user.py
+++ b/zerver/actions/create_user.py
@@ -1,6 +1,6 @@
from collections import defaultdict
from datetime import timedelta
-from typing import Any, Iterable, Optional, Sequence
+from typing import Any, Iterable, Sequence
from django.conf import settings
from django.db import transaction
@@ -125,7 +125,7 @@ def notify_new_user(user_profile: UserProfile) -> None:
def set_up_streams_for_new_human_user(
*,
user_profile: UserProfile,
- prereg_user: Optional[PreregistrationUser] = None,
+ prereg_user: PreregistrationUser | None = None,
default_stream_groups: Sequence[DefaultStreamGroup] = [],
add_initial_stream_subscriptions: bool = True,
realm_creation: bool = False,
@@ -134,7 +134,7 @@ def set_up_streams_for_new_human_user(
if prereg_user is not None:
streams: list[Stream] = list(prereg_user.streams.all())
- acting_user: Optional[UserProfile] = prereg_user.referred_by
+ acting_user: UserProfile | None = prereg_user.referred_by
# A PregistrationUser should not be used for another UserProfile
assert prereg_user.created_user is None, "PregistrationUser should not be reused"
@@ -267,7 +267,7 @@ def add_new_user_history(
# * Mark 'visibility_policy_banner' as read
def process_new_human_user(
user_profile: UserProfile,
- prereg_user: Optional[PreregistrationUser] = None,
+ prereg_user: PreregistrationUser | None = None,
default_stream_groups: Sequence[DefaultStreamGroup] = [],
realm_creation: bool = False,
add_initial_stream_subscriptions: bool = True,
@@ -448,7 +448,7 @@ def notify_created_user(user_profile: UserProfile, notify_user_ids: list[int]) -
def created_bot_event(user_profile: UserProfile) -> dict[str, Any]:
- def stream_name(stream: Optional[Stream]) -> Optional[str]:
+ def stream_name(stream: Stream | None) -> str | None:
if not stream:
return None
return stream.name
@@ -486,28 +486,28 @@ def notify_created_bot(user_profile: UserProfile) -> None:
def do_create_user(
email: str,
- password: Optional[str],
+ password: str | None,
realm: Realm,
full_name: str,
- bot_type: Optional[int] = None,
- role: Optional[int] = None,
- bot_owner: Optional[UserProfile] = None,
- tos_version: Optional[str] = None,
+ bot_type: int | None = None,
+ role: int | None = None,
+ bot_owner: UserProfile | None = None,
+ tos_version: str | None = None,
timezone: str = "",
avatar_source: str = UserProfile.AVATAR_FROM_GRAVATAR,
- default_language: Optional[str] = None,
- default_sending_stream: Optional[Stream] = None,
- default_events_register_stream: Optional[Stream] = None,
- default_all_public_streams: Optional[bool] = None,
- prereg_user: Optional[PreregistrationUser] = None,
- prereg_realm: Optional[PreregistrationRealm] = None,
+ default_language: str | None = None,
+ default_sending_stream: Stream | None = None,
+ default_events_register_stream: Stream | None = None,
+ default_all_public_streams: bool | None = None,
+ prereg_user: PreregistrationUser | None = None,
+ prereg_realm: PreregistrationRealm | None = None,
default_stream_groups: Sequence[DefaultStreamGroup] = [],
- source_profile: Optional[UserProfile] = None,
+ source_profile: UserProfile | None = None,
realm_creation: bool = False,
*,
- acting_user: Optional[UserProfile],
+ acting_user: UserProfile | None,
enable_marketing_emails: bool = True,
- email_address_visibility: Optional[int] = None,
+ email_address_visibility: int | None = None,
add_initial_stream_subscriptions: bool = True,
) -> UserProfile:
with transaction.atomic():
@@ -624,7 +624,7 @@ def do_create_user(
def do_activate_mirror_dummy_user(
- user_profile: UserProfile, *, acting_user: Optional[UserProfile]
+ user_profile: UserProfile, *, acting_user: UserProfile | None
) -> None:
"""Called to have a user "take over" a "mirror dummy" user
(i.e. is_mirror_dummy=True) account when they sign up with the
@@ -669,7 +669,7 @@ def do_activate_mirror_dummy_user(
@transaction.atomic(savepoint=False)
-def do_reactivate_user(user_profile: UserProfile, *, acting_user: Optional[UserProfile]) -> None:
+def do_reactivate_user(user_profile: UserProfile, *, acting_user: UserProfile | None) -> None:
"""Reactivate a user that had previously been deactivated"""
if user_profile.is_mirror_dummy:
raise JsonableError(
diff --git a/zerver/actions/custom_profile_fields.py b/zerver/actions/custom_profile_fields.py
index 810f9db36c7..b99763c04b6 100644
--- a/zerver/actions/custom_profile_fields.py
+++ b/zerver/actions/custom_profile_fields.py
@@ -1,4 +1,4 @@
-from typing import Iterable, Optional, Union
+from typing import Iterable
import orjson
from django.db import transaction
@@ -49,7 +49,7 @@ def try_add_realm_custom_profile_field(
name: str,
field_type: int,
hint: str = "",
- field_data: Optional[ProfileFieldData] = None,
+ field_data: ProfileFieldData | None = None,
display_in_profile_summary: bool = False,
required: bool = False,
) -> CustomProfileField:
@@ -101,11 +101,11 @@ def remove_custom_profile_field_value_if_required(
def try_update_realm_custom_profile_field(
realm: Realm,
field: CustomProfileField,
- name: Optional[str] = None,
- hint: Optional[str] = None,
- field_data: Optional[ProfileFieldData] = None,
- display_in_profile_summary: Optional[bool] = None,
- required: Optional[bool] = None,
+ name: str | None = None,
+ hint: str | None = None,
+ field_data: ProfileFieldData | None = None,
+ display_in_profile_summary: bool | None = None,
+ required: bool | None = None,
) -> None:
if name is not None:
field.name = name
@@ -146,7 +146,7 @@ def try_reorder_realm_custom_profile_fields(realm: Realm, order: Iterable[int])
def notify_user_update_custom_profile_data(
- user_profile: UserProfile, field: dict[str, Union[int, str, list[int], None]]
+ user_profile: UserProfile, field: dict[str, int | str | list[int] | None]
) -> None:
data = dict(id=field["id"], value=field["value"])
diff --git a/zerver/actions/invites.py b/zerver/actions/invites.py
index bf6f582dc26..8a5feb0d0b7 100644
--- a/zerver/actions/invites.py
+++ b/zerver/actions/invites.py
@@ -1,6 +1,6 @@
import logging
from datetime import datetime, timedelta
-from typing import Any, Collection, Optional, Sequence
+from typing import Any, Collection, Sequence
from django.conf import settings
from django.contrib.contenttypes.models import ContentType
@@ -176,7 +176,7 @@ def do_invite_users(
streams: Collection[Stream],
notify_referrer_on_join: bool = True,
*,
- invite_expires_in_minutes: Optional[int],
+ invite_expires_in_minutes: int | None,
include_realm_default_subscriptions: bool,
invite_as: int = PreregistrationUser.INVITE_AS["MEMBER"],
) -> list[tuple[str, str, bool]]:
@@ -285,7 +285,7 @@ def do_invite_users(
return skipped
-def get_invitation_expiry_date(confirmation_obj: Confirmation) -> Optional[int]:
+def get_invitation_expiry_date(confirmation_obj: Confirmation) -> int | None:
expiry_date = confirmation_obj.expiry_date
if expiry_date is None:
return expiry_date
@@ -362,7 +362,7 @@ def do_get_invites_controlled_by_user(user_profile: UserProfile) -> list[dict[st
def do_create_multiuse_invite_link(
referred_by: UserProfile,
invited_as: int,
- invite_expires_in_minutes: Optional[int],
+ invite_expires_in_minutes: int | None,
include_realm_default_subscriptions: bool,
streams: Sequence[Stream] = [],
) -> str:
@@ -414,9 +414,9 @@ def do_revoke_multi_use_invite(multiuse_invite: MultiuseInvite) -> None:
def do_send_user_invite_email(
prereg_user: PreregistrationUser,
*,
- confirmation: Optional[Confirmation] = None,
- event_time: Optional[datetime] = None,
- invite_expires_in_minutes: Optional[float] = None,
+ confirmation: Confirmation | None = None,
+ event_time: datetime | None = None,
+ invite_expires_in_minutes: float | None = None,
) -> None:
# Take a lock on the realm, so we can check for invitation limits without races
realm_id = assert_is_not_none(prereg_user.realm_id)
diff --git a/zerver/actions/message_edit.py b/zerver/actions/message_edit.py
index ab05cc29071..463629a67df 100644
--- a/zerver/actions/message_edit.py
+++ b/zerver/actions/message_edit.py
@@ -1,7 +1,7 @@
import itertools
from collections import defaultdict
from datetime import timedelta
-from typing import AbstractSet, Any, Iterable, Optional
+from typing import AbstractSet, Any, Iterable
from django.conf import settings
from django.db import transaction
@@ -90,10 +90,10 @@ def subscriber_info(user_id: int) -> dict[str, Any]:
def validate_message_edit_payload(
message: Message,
- stream_id: Optional[int],
- topic_name: Optional[str],
- propagate_mode: Optional[str],
- content: Optional[str],
+ stream_id: int | None,
+ topic_name: str | None,
+ propagate_mode: str | None,
+ content: str | None,
) -> None:
"""
Checks that the data sent is well-formed. Does not handle editability, permissions etc.
@@ -148,7 +148,7 @@ def maybe_send_resolve_topic_notifications(
new_topic_name: str,
changed_messages: QuerySet[Message],
pre_truncation_new_topic_name: str,
-) -> tuple[Optional[int], bool]:
+) -> tuple[int | None, bool]:
"""Returns resolved_topic_message_id if resolve topic notifications were in fact sent."""
# Note that topics will have already been stripped in check_update_message.
resolved_prefix_len = len(RESOLVED_TOPIC_PREFIX)
@@ -245,10 +245,10 @@ def send_message_moved_breadcrumbs(
user_profile: UserProfile,
old_stream: Stream,
old_topic_name: str,
- old_thread_notification_string: Optional[StrPromise],
+ old_thread_notification_string: StrPromise | None,
new_stream: Stream,
- new_topic_name: Optional[str],
- new_thread_notification_string: Optional[StrPromise],
+ new_topic_name: str | None,
+ new_thread_notification_string: StrPromise | None,
changed_messages_count: int,
) -> None:
# Since moving content between streams is highly disruptive,
@@ -362,7 +362,7 @@ def update_user_message_flags(
def do_update_embedded_data(
user_profile: UserProfile,
message: Message,
- content: Optional[str],
+ content: str | None,
rendering_result: MessageRenderingResult,
) -> None:
timestamp = timezone_now()
@@ -374,7 +374,7 @@ def do_update_embedded_data(
"rendering_only": True,
}
changed_messages = [message]
- rendered_content: Optional[str] = None
+ rendered_content: str | None = None
ums = UserMessage.objects.filter(message=message.id)
@@ -426,15 +426,15 @@ def get_visibility_policy_after_merge(
def do_update_message(
user_profile: UserProfile,
target_message: Message,
- new_stream: Optional[Stream],
- topic_name: Optional[str],
- propagate_mode: Optional[str],
+ new_stream: Stream | None,
+ topic_name: str | None,
+ propagate_mode: str | None,
send_notification_to_old_thread: bool,
send_notification_to_new_thread: bool,
- content: Optional[str],
- rendering_result: Optional[MessageRenderingResult],
+ content: str | None,
+ rendering_result: MessageRenderingResult | None,
prior_mention_user_ids: set[int],
- mention_data: Optional[MentionData] = None,
+ mention_data: MentionData | None = None,
) -> int:
"""
The main function for message editing. A message edit event can
@@ -524,7 +524,7 @@ def do_update_message(
else:
new_topic_name = target_message.topic_name()
- stream_topic: Optional[StreamTopicTarget] = StreamTopicTarget(
+ stream_topic: StreamTopicTarget | None = StreamTopicTarget(
stream_id=stream_id,
topic_name=new_topic_name,
)
@@ -792,7 +792,7 @@ def do_update_message(
# freshly-fetched-from-the-database changed messages.
changed_messages = save_changes_for_propagation_mode()
- realm_id: Optional[int] = None
+ realm_id: int | None = None
if stream_being_edited is not None:
realm_id = stream_being_edited.realm_id
@@ -1145,8 +1145,8 @@ def do_update_message(
def check_time_limit_for_change_all_propagate_mode(
message: Message,
user_profile: UserProfile,
- topic_name: Optional[str] = None,
- stream_id: Optional[int] = None,
+ topic_name: str | None = None,
+ stream_id: int | None = None,
) -> None:
realm = user_profile.realm
message_move_limit_buffer = 20
@@ -1238,12 +1238,12 @@ def check_time_limit_for_change_all_propagate_mode(
def check_update_message(
user_profile: UserProfile,
message_id: int,
- stream_id: Optional[int] = None,
- topic_name: Optional[str] = None,
+ stream_id: int | None = None,
+ topic_name: str | None = None,
propagate_mode: str = "change_one",
send_notification_to_old_thread: bool = True,
send_notification_to_new_thread: bool = True,
- content: Optional[str] = None,
+ content: str | None = None,
) -> int:
"""This will update a message given the message id and user profile.
It checks whether the user profile has the permission to edit the message
@@ -1293,7 +1293,7 @@ def check_update_message(
rendering_result = None
links_for_embed: set[str] = set()
prior_mention_user_ids: set[int] = set()
- mention_data: Optional[MentionData] = None
+ mention_data: MentionData | None = None
if content is not None:
if content.rstrip() == "":
content = "(deleted)"
diff --git a/zerver/actions/message_flags.py b/zerver/actions/message_flags.py
index 74a64bac52d..b4ad2e7e839 100644
--- a/zerver/actions/message_flags.py
+++ b/zerver/actions/message_flags.py
@@ -1,7 +1,6 @@
import time
from collections import defaultdict
from dataclasses import asdict, dataclass, field
-from typing import Optional
from django.conf import settings
from django.db import transaction
@@ -34,9 +33,7 @@ class ReadMessagesEvent:
flag: str = field(default="read", init=False)
-def do_mark_all_as_read(
- user_profile: UserProfile, *, timeout: Optional[float] = None
-) -> Optional[int]:
+def do_mark_all_as_read(user_profile: UserProfile, *, timeout: float | None = None) -> int | None:
start_time = time.monotonic()
# First, we clear mobile push notifications. This is safer in the
@@ -105,7 +102,7 @@ def do_mark_all_as_read(
def do_mark_stream_messages_as_read(
- user_profile: UserProfile, stream_recipient_id: int, topic_name: Optional[str] = None
+ user_profile: UserProfile, stream_recipient_id: int, topic_name: str | None = None
) -> int:
with transaction.atomic(savepoint=False):
query = (
diff --git a/zerver/actions/message_send.py b/zerver/actions/message_send.py
index c31251b7846..c87b72032a3 100644
--- a/zerver/actions/message_send.py
+++ b/zerver/actions/message_send.py
@@ -3,7 +3,7 @@ from collections import defaultdict
from dataclasses import dataclass
from datetime import timedelta
from email.headerregistry import Address
-from typing import AbstractSet, Any, Callable, Collection, Optional, Sequence, TypedDict, Union
+from typing import AbstractSet, Any, Callable, Collection, Sequence, TypedDict
import orjson
from django.conf import settings
@@ -143,8 +143,8 @@ def render_incoming_message(
message: Message,
content: str,
realm: Realm,
- mention_data: Optional[MentionData] = None,
- url_embed_data: Optional[dict[str, Optional[UrlEmbedData]]] = None,
+ mention_data: MentionData | None = None,
+ url_embed_data: dict[str, UrlEmbedData | None] | None = None,
email_gateway: bool = False,
) -> MessageRenderingResult:
realm_alert_words_automaton = get_alert_word_automaton(realm)
@@ -184,7 +184,7 @@ class RecipientInfoResult:
service_bot_tuples: list[tuple[int, int]]
all_bot_user_ids: set[int]
topic_participant_user_ids: set[int]
- sender_muted_stream: Optional[bool]
+ sender_muted_stream: bool | None
class ActiveUserDict(TypedDict):
@@ -194,13 +194,13 @@ class ActiveUserDict(TypedDict):
enable_offline_push_notifications: bool
long_term_idle: bool
is_bot: bool
- bot_type: Optional[int]
+ bot_type: int | None
@dataclass
class SentMessageResult:
message_id: int
- automatic_new_visibility_policy: Optional[int] = None
+ automatic_new_visibility_policy: int | None = None
def get_recipient_info(
@@ -208,7 +208,7 @@ def get_recipient_info(
realm_id: int,
recipient: Recipient,
sender_id: int,
- stream_topic: Optional[StreamTopicTarget],
+ stream_topic: StreamTopicTarget | None,
possibly_mentioned_user_ids: AbstractSet[int] = set(),
possible_topic_wildcard_mention: bool = True,
possible_stream_wildcard_mention: bool = True,
@@ -223,7 +223,7 @@ def get_recipient_info(
stream_wildcard_mention_in_followed_topic_user_ids: set[int] = set()
muted_sender_user_ids: set[int] = get_muting_users(sender_id)
topic_participant_user_ids: set[int] = set()
- sender_muted_stream: Optional[bool] = None
+ sender_muted_stream: bool | None = None
if recipient.type == Recipient.PERSONAL:
# The sender and recipient may be the same id, so
@@ -560,15 +560,15 @@ def get_service_bot_events(
def build_message_send_dict(
message: Message,
- stream: Optional[Stream] = None,
- local_id: Optional[str] = None,
- sender_queue_id: Optional[str] = None,
- widget_content_dict: Optional[dict[str, Any]] = None,
+ stream: Stream | None = None,
+ local_id: str | None = None,
+ sender_queue_id: str | None = None,
+ widget_content_dict: dict[str, Any] | None = None,
email_gateway: bool = False,
- mention_backend: Optional[MentionBackend] = None,
- limit_unread_user_ids: Optional[set[int]] = None,
+ mention_backend: MentionBackend | None = None,
+ limit_unread_user_ids: set[int] | None = None,
disable_external_notifications: bool = False,
- recipients_for_user_creation_events: Optional[dict[UserProfile, set[int]]] = None,
+ recipients_for_user_creation_events: dict[UserProfile, set[int]] | None = None,
) -> SendMessageRequest:
"""Returns a dictionary that can be passed into do_send_messages. In
production, this is always called by check_message, but some
@@ -587,7 +587,7 @@ def build_message_send_dict(
if message.is_stream_message():
stream_id = message.recipient.type_id
- stream_topic: Optional[StreamTopicTarget] = StreamTopicTarget(
+ stream_topic: StreamTopicTarget | None = StreamTopicTarget(
stream_id=stream_id,
topic_name=message.topic_name(),
)
@@ -714,7 +714,7 @@ def create_user_messages(
followed_topic_push_user_ids: AbstractSet[int],
followed_topic_email_user_ids: AbstractSet[int],
mark_as_read_user_ids: set[int],
- limit_unread_user_ids: Optional[set[int]],
+ limit_unread_user_ids: set[int] | None,
topic_participant_user_ids: set[int],
) -> list[UserMessageLite]:
# These properties on the Message are set via
@@ -835,7 +835,7 @@ def get_active_presence_idle_user_ids(
@transaction.atomic(savepoint=False)
def do_send_messages(
- send_message_requests_maybe_none: Sequence[Optional[SendMessageRequest]],
+ send_message_requests_maybe_none: Sequence[SendMessageRequest | None],
*,
mark_as_read: Sequence[int] = [],
) -> list[SentMessageResult]:
@@ -917,7 +917,7 @@ def do_send_messages(
# * Implementing the Welcome Bot reply hack
# * Adding links to the embed_links queue for open graph processing.
for send_request in send_message_requests:
- realm_id: Optional[int] = None
+ realm_id: int | None = None
if send_request.message.is_stream_message():
if send_request.stream is None:
stream_id = send_request.message.recipient.type_id
@@ -1033,7 +1033,7 @@ def do_send_messages(
class UserData(TypedDict):
id: int
flags: list[str]
- mentioned_user_group_id: Optional[int]
+ mentioned_user_group_id: int | None
users: list[UserData] = []
for user_id in user_list:
@@ -1209,7 +1209,7 @@ def do_send_messages(
return sent_message_results
-def already_sent_mirrored_message_id(message: Message) -> Optional[int]:
+def already_sent_mirrored_message_id(message: Message) -> int | None:
if message.recipient.type == Recipient.DIRECT_MESSAGE_GROUP:
# For group direct messages, we use a 10-second window because
# the timestamps aren't guaranteed to actually match between
@@ -1235,7 +1235,7 @@ def already_sent_mirrored_message_id(message: Message) -> Optional[int]:
return None
-def extract_stream_indicator(s: str) -> Union[str, int]:
+def extract_stream_indicator(s: str) -> str | int:
# Users can pass stream name as either an id or a name,
# and if they choose to pass a name, they may JSON encode
# it for legacy reasons.
@@ -1265,7 +1265,7 @@ def extract_stream_indicator(s: str) -> Union[str, int]:
raise JsonableError(_("Invalid data type for channel"))
-def extract_private_recipients(s: str) -> Union[list[str], list[int]]:
+def extract_private_recipients(s: str) -> list[str] | list[int]:
# We try to accept multiple incoming formats for recipients.
# See test_extract_recipients() for examples of what we allow.
@@ -1316,7 +1316,7 @@ def check_send_stream_message(
topic_name: str,
body: str,
*,
- realm: Optional[Realm] = None,
+ realm: Realm | None = None,
read_by_sender: bool = False,
) -> int:
addressee = Addressee.for_stream_name(stream_name, topic_name)
@@ -1333,7 +1333,7 @@ def check_send_stream_message_by_id(
stream_id: int,
topic_name: str,
body: str,
- realm: Optional[Realm] = None,
+ realm: Realm | None = None,
) -> int:
addressee = Addressee.for_stream_id(stream_id, topic_name)
message = check_message(sender, client, addressee, body, realm)
@@ -1356,16 +1356,16 @@ def check_send_message(
sender: UserProfile,
client: Client,
recipient_type_name: str,
- message_to: Union[Sequence[int], Sequence[str]],
- topic_name: Optional[str],
+ message_to: Sequence[int] | Sequence[str],
+ topic_name: str | None,
message_content: str,
- realm: Optional[Realm] = None,
+ realm: Realm | None = None,
forged: bool = False,
- forged_timestamp: Optional[float] = None,
- forwarder_user_profile: Optional[UserProfile] = None,
- local_id: Optional[str] = None,
- sender_queue_id: Optional[str] = None,
- widget_content: Optional[str] = None,
+ forged_timestamp: float | None = None,
+ forwarder_user_profile: UserProfile | None = None,
+ local_id: str | None = None,
+ sender_queue_id: str | None = None,
+ widget_content: str | None = None,
*,
skip_stream_access_check: bool = False,
read_by_sender: bool = False,
@@ -1430,11 +1430,11 @@ def send_rate_limited_pm_notification_to_bot_owner(
def send_pm_if_empty_stream(
- stream: Optional[Stream],
+ stream: Stream | None,
realm: Realm,
sender: UserProfile,
- stream_name: Optional[str] = None,
- stream_id: Optional[int] = None,
+ stream_name: str | None = None,
+ stream_id: int | None = None,
) -> None:
"""If a bot sends a message to a stream that doesn't exist or has no
subscribers, sends a notification to the bot owner (if not a
@@ -1641,19 +1641,19 @@ def check_message(
client: Client,
addressee: Addressee,
message_content_raw: str,
- realm: Optional[Realm] = None,
+ realm: Realm | None = None,
forged: bool = False,
- forged_timestamp: Optional[float] = None,
- forwarder_user_profile: Optional[UserProfile] = None,
- local_id: Optional[str] = None,
- sender_queue_id: Optional[str] = None,
- widget_content: Optional[str] = None,
+ forged_timestamp: float | None = None,
+ forwarder_user_profile: UserProfile | None = None,
+ local_id: str | None = None,
+ sender_queue_id: str | None = None,
+ widget_content: str | None = None,
email_gateway: bool = False,
*,
skip_stream_access_check: bool = False,
message_type: int = Message.MessageType.NORMAL,
- mention_backend: Optional[MentionBackend] = None,
- limit_unread_user_ids: Optional[set[int]] = None,
+ mention_backend: MentionBackend | None = None,
+ limit_unread_user_ids: set[int] | None = None,
disable_external_notifications: bool = False,
) -> SendMessageRequest:
"""See
@@ -1827,12 +1827,12 @@ def _internal_prep_message(
*,
email_gateway: bool = False,
message_type: int = Message.MessageType.NORMAL,
- mention_backend: Optional[MentionBackend] = None,
- limit_unread_user_ids: Optional[set[int]] = None,
+ mention_backend: MentionBackend | None = None,
+ limit_unread_user_ids: set[int] | None = None,
disable_external_notifications: bool = False,
forged: bool = False,
- forged_timestamp: Optional[float] = None,
-) -> Optional[SendMessageRequest]:
+ forged_timestamp: float | None = None,
+) -> SendMessageRequest | None:
"""
Create a message object and checks it, but doesn't send it or save it to the database.
The internal function that calls this can therefore batch send a bunch of created
@@ -1883,10 +1883,10 @@ def internal_prep_stream_message(
*,
email_gateway: bool = False,
message_type: int = Message.MessageType.NORMAL,
- limit_unread_user_ids: Optional[set[int]] = None,
+ limit_unread_user_ids: set[int] | None = None,
forged: bool = False,
- forged_timestamp: Optional[float] = None,
-) -> Optional[SendMessageRequest]:
+ forged_timestamp: float | None = None,
+) -> SendMessageRequest | None:
"""
See _internal_prep_message for details of how this works.
"""
@@ -1912,7 +1912,7 @@ def internal_prep_stream_message_by_name(
stream_name: str,
topic_name: str,
content: str,
-) -> Optional[SendMessageRequest]:
+) -> SendMessageRequest | None:
"""
See _internal_prep_message for details of how this works.
"""
@@ -1931,9 +1931,9 @@ def internal_prep_private_message(
recipient_user: UserProfile,
content: str,
*,
- mention_backend: Optional[MentionBackend] = None,
+ mention_backend: MentionBackend | None = None,
disable_external_notifications: bool = False,
-) -> Optional[SendMessageRequest]:
+) -> SendMessageRequest | None:
"""
See _internal_prep_message for details of how this works.
"""
@@ -1959,7 +1959,7 @@ def internal_send_private_message(
content: str,
*,
disable_external_notifications: bool = False,
-) -> Optional[int]:
+) -> int | None:
message = internal_prep_private_message(
sender,
recipient_user,
@@ -1980,8 +1980,8 @@ def internal_send_stream_message(
*,
email_gateway: bool = False,
message_type: int = Message.MessageType.NORMAL,
- limit_unread_user_ids: Optional[set[int]] = None,
-) -> Optional[int]:
+ limit_unread_user_ids: set[int] | None = None,
+) -> int | None:
message = internal_prep_stream_message(
sender,
stream,
@@ -2005,7 +2005,7 @@ def internal_send_stream_message_by_name(
stream_name: str,
topic_name: str,
content: str,
-) -> Optional[int]:
+) -> int | None:
message = internal_prep_stream_message_by_name(
realm,
sender,
@@ -2025,9 +2025,9 @@ def internal_prep_group_direct_message(
sender: UserProfile,
content: str,
*,
- emails: Optional[list[str]] = None,
- recipient_users: Optional[list[UserProfile]] = None,
-) -> Optional[SendMessageRequest]:
+ emails: list[str] | None = None,
+ recipient_users: list[UserProfile] | None = None,
+) -> SendMessageRequest | None:
if recipient_users is not None:
addressee = Addressee.for_user_profiles(recipient_users)
else:
@@ -2047,9 +2047,9 @@ def internal_send_group_direct_message(
sender: UserProfile,
content: str,
*,
- emails: Optional[list[str]] = None,
- recipient_users: Optional[list[UserProfile]] = None,
-) -> Optional[int]:
+ emails: list[str] | None = None,
+ recipient_users: list[UserProfile] | None = None,
+) -> int | None:
message = internal_prep_group_direct_message(
realm, sender, content, emails=emails, recipient_users=recipient_users
)
diff --git a/zerver/actions/muted_users.py b/zerver/actions/muted_users.py
index b8a0a5f0762..6c35cfe0631 100644
--- a/zerver/actions/muted_users.py
+++ b/zerver/actions/muted_users.py
@@ -1,5 +1,4 @@
from datetime import datetime
-from typing import Optional
from django.utils.timezone import now as timezone_now
@@ -12,7 +11,7 @@ from zerver.tornado.django_api import send_event
def do_mute_user(
user_profile: UserProfile,
muted_user: UserProfile,
- date_muted: Optional[datetime] = None,
+ date_muted: datetime | None = None,
) -> None:
if date_muted is None:
date_muted = timezone_now()
diff --git a/zerver/actions/reactions.py b/zerver/actions/reactions.py
index 201d2d056f5..8f18c6305ce 100644
--- a/zerver/actions/reactions.py
+++ b/zerver/actions/reactions.py
@@ -1,4 +1,4 @@
-from typing import Any, Optional
+from typing import Any
from zerver.actions.user_topics import do_set_user_topic_visibility_policy
from zerver.lib.emoji import check_emoji_request, get_emoji_data
@@ -123,8 +123,8 @@ def check_add_reaction(
user_profile: UserProfile,
message_id: int,
emoji_name: str,
- emoji_code: Optional[str],
- reaction_type: Optional[str],
+ emoji_code: str | None,
+ reaction_type: str | None,
) -> None:
message, user_message = access_message_and_usermessage(
user_profile, message_id, lock_message=True
diff --git a/zerver/actions/realm_domains.py b/zerver/actions/realm_domains.py
index 1ea401beae4..376bebd173b 100644
--- a/zerver/actions/realm_domains.py
+++ b/zerver/actions/realm_domains.py
@@ -1,5 +1,3 @@
-from typing import Optional
-
from django.db import transaction
from django.utils.timezone import now as timezone_now
@@ -12,7 +10,7 @@ from zerver.tornado.django_api import send_event_on_commit
@transaction.atomic(durable=True)
def do_add_realm_domain(
- realm: Realm, domain: str, allow_subdomains: bool, *, acting_user: Optional[UserProfile]
+ realm: Realm, domain: str, allow_subdomains: bool, *, acting_user: UserProfile | None
) -> RealmDomain:
realm_domain = RealmDomain.objects.create(
realm=realm, domain=domain, allow_subdomains=allow_subdomains
@@ -44,7 +42,7 @@ def do_add_realm_domain(
@transaction.atomic(durable=True)
def do_change_realm_domain(
- realm_domain: RealmDomain, allow_subdomains: bool, *, acting_user: Optional[UserProfile]
+ realm_domain: RealmDomain, allow_subdomains: bool, *, acting_user: UserProfile | None
) -> None:
realm_domain.allow_subdomains = allow_subdomains
realm_domain.save(update_fields=["allow_subdomains"])
@@ -75,9 +73,7 @@ def do_change_realm_domain(
@transaction.atomic(durable=True)
-def do_remove_realm_domain(
- realm_domain: RealmDomain, *, acting_user: Optional[UserProfile]
-) -> None:
+def do_remove_realm_domain(realm_domain: RealmDomain, *, acting_user: UserProfile | None) -> None:
realm = realm_domain.realm
domain = realm_domain.domain
realm_domain.delete()
diff --git a/zerver/actions/realm_emoji.py b/zerver/actions/realm_emoji.py
index 2101f67b458..e81d36a65d3 100644
--- a/zerver/actions/realm_emoji.py
+++ b/zerver/actions/realm_emoji.py
@@ -1,4 +1,4 @@
-from typing import IO, Optional
+from typing import IO
from django.core.exceptions import ValidationError
from django.db import transaction
@@ -66,7 +66,7 @@ def check_add_realm_emoji(
@transaction.atomic(durable=True)
-def do_remove_realm_emoji(realm: Realm, name: str, *, acting_user: Optional[UserProfile]) -> None:
+def do_remove_realm_emoji(realm: Realm, name: str, *, acting_user: UserProfile | None) -> None:
emoji = RealmEmoji.objects.get(realm=realm, name=name, deactivated=False)
emoji.deactivated = True
emoji.save(update_fields=["deactivated"])
diff --git a/zerver/actions/realm_icon.py b/zerver/actions/realm_icon.py
index 820eeee36c4..c44fc03a085 100644
--- a/zerver/actions/realm_icon.py
+++ b/zerver/actions/realm_icon.py
@@ -1,5 +1,3 @@
-from typing import Optional
-
from django.db import transaction
from django.utils.timezone import now as timezone_now
@@ -11,7 +9,7 @@ from zerver.tornado.django_api import send_event_on_commit
@transaction.atomic(durable=True)
def do_change_icon_source(
- realm: Realm, icon_source: str, *, acting_user: Optional[UserProfile]
+ realm: Realm, icon_source: str, *, acting_user: UserProfile | None
) -> None:
realm.icon_source = icon_source
realm.icon_version += 1
diff --git a/zerver/actions/realm_linkifiers.py b/zerver/actions/realm_linkifiers.py
index 8fe72937734..8928c0c7500 100644
--- a/zerver/actions/realm_linkifiers.py
+++ b/zerver/actions/realm_linkifiers.py
@@ -1,5 +1,3 @@
-from typing import Optional
-
from django.db import transaction
from django.db.models import Max
from django.utils.timezone import now as timezone_now
@@ -28,7 +26,7 @@ def do_add_linkifier(
pattern: str,
url_template: str,
*,
- acting_user: Optional[UserProfile],
+ acting_user: UserProfile | None,
) -> int:
pattern = pattern.strip()
url_template = url_template.strip()
@@ -67,10 +65,10 @@ def do_add_linkifier(
@transaction.atomic(durable=True)
def do_remove_linkifier(
realm: Realm,
- pattern: Optional[str] = None,
- id: Optional[int] = None,
+ pattern: str | None = None,
+ id: int | None = None,
*,
- acting_user: Optional[UserProfile] = None,
+ acting_user: UserProfile | None = None,
) -> None:
if pattern is not None:
realm_linkifier = RealmFilter.objects.get(realm=realm, pattern=pattern)
@@ -106,7 +104,7 @@ def do_update_linkifier(
pattern: str,
url_template: str,
*,
- acting_user: Optional[UserProfile],
+ acting_user: UserProfile | None,
) -> None:
pattern = pattern.strip()
url_template = url_template.strip()
@@ -137,7 +135,7 @@ def do_update_linkifier(
@transaction.atomic(durable=True)
def check_reorder_linkifiers(
- realm: Realm, ordered_linkifier_ids: list[int], *, acting_user: Optional[UserProfile]
+ realm: Realm, ordered_linkifier_ids: list[int], *, acting_user: UserProfile | None
) -> None:
"""ordered_linkifier_ids should contain ids of all existing linkifiers.
In the rare situation when any of the linkifier gets deleted that more ids
diff --git a/zerver/actions/realm_logo.py b/zerver/actions/realm_logo.py
index 687c530062b..272169b5285 100644
--- a/zerver/actions/realm_logo.py
+++ b/zerver/actions/realm_logo.py
@@ -1,5 +1,3 @@
-from typing import Optional
-
from django.db import transaction
from django.utils.timezone import now as timezone_now
@@ -11,7 +9,7 @@ from zerver.tornado.django_api import send_event_on_commit
@transaction.atomic(durable=True)
def do_change_logo_source(
- realm: Realm, logo_source: str, night: bool, *, acting_user: Optional[UserProfile]
+ realm: Realm, logo_source: str, night: bool, *, acting_user: UserProfile | None
) -> None:
if not night:
realm.logo_source = logo_source
diff --git a/zerver/actions/realm_playgrounds.py b/zerver/actions/realm_playgrounds.py
index e09c7cdae72..dee7bc447d9 100644
--- a/zerver/actions/realm_playgrounds.py
+++ b/zerver/actions/realm_playgrounds.py
@@ -1,5 +1,3 @@
-from typing import Optional
-
from django.core.exceptions import ValidationError
from django.db import transaction
from django.utils.timezone import now as timezone_now
@@ -21,7 +19,7 @@ def notify_realm_playgrounds(realm: Realm, realm_playgrounds: list[RealmPlaygrou
def check_add_realm_playground(
realm: Realm,
*,
- acting_user: Optional[UserProfile],
+ acting_user: UserProfile | None,
name: str,
pygments_language: str,
url_template: str,
@@ -63,7 +61,7 @@ def check_add_realm_playground(
@transaction.atomic(durable=True)
def do_remove_realm_playground(
- realm: Realm, realm_playground: RealmPlayground, *, acting_user: Optional[UserProfile]
+ realm: Realm, realm_playground: RealmPlayground, *, acting_user: UserProfile | None
) -> None:
removed_playground = {
"name": realm_playground.name,
diff --git a/zerver/actions/realm_settings.py b/zerver/actions/realm_settings.py
index b70846c3855..ba97788cb6e 100644
--- a/zerver/actions/realm_settings.py
+++ b/zerver/actions/realm_settings.py
@@ -1,6 +1,6 @@
import logging
from email.headerregistry import Address
-from typing import Any, Literal, Optional, Union
+from typing import Any, Literal
import zoneinfo
from django.conf import settings
@@ -56,7 +56,7 @@ if settings.BILLING_ENABLED:
@transaction.atomic(savepoint=False)
def do_set_realm_property(
- realm: Realm, name: str, value: Any, *, acting_user: Optional[UserProfile]
+ realm: Realm, name: str, value: Any, *, acting_user: UserProfile | None
) -> None:
"""Takes in a realm object, the name of an attribute to update, the
value to update and and the user who initiated the update.
@@ -114,7 +114,7 @@ def do_set_realm_property(
def do_set_push_notifications_enabled_end_timestamp(
- realm: Realm, value: Optional[int], *, acting_user: Optional[UserProfile]
+ realm: Realm, value: int | None, *, acting_user: UserProfile | None
) -> None:
# Variant of do_set_realm_property with a bit of extra complexity
# for the fact that we store a datetime object in the database but
@@ -162,9 +162,9 @@ def do_change_realm_permission_group_setting(
realm: Realm,
setting_name: str,
user_group: UserGroup,
- old_setting_api_value: Optional[Union[int, AnonymousSettingGroupDict]] = None,
+ old_setting_api_value: int | AnonymousSettingGroupDict | None = None,
*,
- acting_user: Optional[UserProfile],
+ acting_user: UserProfile | None,
) -> None:
"""Takes in a realm object, the name of an attribute to update, the
user_group to update and and the user who initiated the update.
@@ -219,8 +219,8 @@ def do_change_realm_permission_group_setting(
def parse_and_set_setting_value_if_required(
- realm: Realm, setting_name: str, value: Union[int, str], *, acting_user: Optional[UserProfile]
-) -> tuple[Optional[int], bool]:
+ realm: Realm, setting_name: str, value: int | str, *, acting_user: UserProfile | None
+) -> tuple[int | None, bool]:
parsed_value = parse_message_time_limit_setting(
value,
Realm.MESSAGE_TIME_LIMIT_SETTING_SPECIAL_VALUES_MAP,
@@ -254,7 +254,7 @@ def get_realm_authentication_methods_for_page_params_api(
from zproject.backends import AUTH_BACKEND_NAME_MAP
- result_dict: dict[str, dict[str, Union[str, bool]]] = {
+ result_dict: dict[str, dict[str, str | bool]] = {
backend_name: {"enabled": enabled, "available": True}
for backend_name, enabled in authentication_methods.items()
}
@@ -335,7 +335,7 @@ def validate_plan_for_authentication_methods(
def do_set_realm_authentication_methods(
- realm: Realm, authentication_methods: dict[str, bool], *, acting_user: Optional[UserProfile]
+ realm: Realm, authentication_methods: dict[str, bool], *, acting_user: UserProfile | None
) -> None:
old_value = realm.authentication_methods_dict()
with transaction.atomic():
@@ -381,10 +381,10 @@ def do_set_realm_stream(
"signup_announcements_stream",
"zulip_update_announcements_stream",
],
- stream: Optional[Stream],
+ stream: Stream | None,
stream_id: int,
*,
- acting_user: Optional[UserProfile],
+ acting_user: UserProfile | None,
) -> None:
# We could calculate more of these variables from `field`, but
# it's probably more readable to not do so.
@@ -429,7 +429,7 @@ def do_set_realm_stream(
def do_set_realm_new_stream_announcements_stream(
- realm: Realm, stream: Optional[Stream], stream_id: int, *, acting_user: Optional[UserProfile]
+ realm: Realm, stream: Stream | None, stream_id: int, *, acting_user: UserProfile | None
) -> None:
do_set_realm_stream(
realm, "new_stream_announcements_stream", stream, stream_id, acting_user=acting_user
@@ -437,7 +437,7 @@ def do_set_realm_new_stream_announcements_stream(
def do_set_realm_signup_announcements_stream(
- realm: Realm, stream: Optional[Stream], stream_id: int, *, acting_user: Optional[UserProfile]
+ realm: Realm, stream: Stream | None, stream_id: int, *, acting_user: UserProfile | None
) -> None:
do_set_realm_stream(
realm, "signup_announcements_stream", stream, stream_id, acting_user=acting_user
@@ -445,7 +445,7 @@ def do_set_realm_signup_announcements_stream(
def do_set_realm_zulip_update_announcements_stream(
- realm: Realm, stream: Optional[Stream], stream_id: int, *, acting_user: Optional[UserProfile]
+ realm: Realm, stream: Stream | None, stream_id: int, *, acting_user: UserProfile | None
) -> None:
do_set_realm_stream(
realm, "zulip_update_announcements_stream", stream, stream_id, acting_user=acting_user
@@ -457,7 +457,7 @@ def do_set_realm_user_default_setting(
name: str,
value: Any,
*,
- acting_user: Optional[UserProfile],
+ acting_user: UserProfile | None,
) -> None:
old_value = getattr(realm_user_default, name)
realm = realm_user_default.realm
@@ -502,7 +502,7 @@ RealmDeactivationReasonType = Literal[
def do_deactivate_realm(
realm: Realm,
*,
- acting_user: Optional[UserProfile],
+ acting_user: UserProfile | None,
deactivation_reason: RealmDeactivationReasonType,
email_owners: bool,
) -> None:
@@ -620,7 +620,7 @@ def do_delete_all_realm_attachments(realm: Realm, *, batch_size: int = 1000) ->
obj_class._default_manager.filter(realm=realm).delete()
-def do_scrub_realm(realm: Realm, *, acting_user: Optional[UserProfile]) -> None:
+def do_scrub_realm(realm: Realm, *, acting_user: UserProfile | None) -> None:
if settings.BILLING_ENABLED:
billing_session = RealmBillingSession(user=acting_user, realm=realm)
billing_session.downgrade_now_without_creating_additional_invoices()
@@ -679,7 +679,7 @@ def do_scrub_realm(realm: Realm, *, acting_user: Optional[UserProfile]) -> None:
def do_change_realm_org_type(
realm: Realm,
org_type: int,
- acting_user: Optional[UserProfile],
+ acting_user: UserProfile | None,
) -> None:
old_value = realm.org_type
realm.org_type = org_type
@@ -699,7 +699,7 @@ def do_change_realm_org_type(
@transaction.atomic(savepoint=False)
def do_change_realm_plan_type(
- realm: Realm, plan_type: int, *, acting_user: Optional[UserProfile]
+ realm: Realm, plan_type: int, *, acting_user: UserProfile | None
) -> None:
from zproject.backends import AUTH_BACKEND_NAME_MAP
@@ -785,7 +785,7 @@ def do_change_realm_plan_type(
send_event_on_commit(realm, event, active_user_ids(realm.id))
-def do_send_realm_reactivation_email(realm: Realm, *, acting_user: Optional[UserProfile]) -> None:
+def do_send_realm_reactivation_email(realm: Realm, *, acting_user: UserProfile | None) -> None:
obj = RealmReactivationStatus.objects.create(realm=realm)
url = create_confirmation_link(obj, Confirmation.REALM_REACTIVATION)
@@ -812,7 +812,7 @@ def do_send_realm_reactivation_email(realm: Realm, *, acting_user: Optional[User
)
-def do_send_realm_deactivation_email(realm: Realm, acting_user: Optional[UserProfile]) -> None:
+def do_send_realm_deactivation_email(realm: Realm, acting_user: UserProfile | None) -> None:
shared_context: dict[str, Any] = {
"realm_name": realm.name,
}
diff --git a/zerver/actions/scheduled_messages.py b/zerver/actions/scheduled_messages.py
index b5243c9a094..093d66d555a 100644
--- a/zerver/actions/scheduled_messages.py
+++ b/zerver/actions/scheduled_messages.py
@@ -1,6 +1,6 @@
import logging
from datetime import datetime, timedelta
-from typing import Optional, Sequence
+from typing import Sequence
from django.conf import settings
from django.db import transaction
@@ -34,13 +34,13 @@ def check_schedule_message(
client: Client,
recipient_type_name: str,
message_to: list[int],
- topic_name: Optional[str],
+ topic_name: str | None,
message_content: str,
deliver_at: datetime,
- realm: Optional[Realm] = None,
+ realm: Realm | None = None,
*,
- forwarder_user_profile: Optional[UserProfile] = None,
- read_by_sender: Optional[bool] = None,
+ forwarder_user_profile: UserProfile | None = None,
+ read_by_sender: bool | None = None,
) -> int:
addressee = Addressee.legacy_build(sender, recipient_type_name, message_to, topic_name)
send_request = check_message(
@@ -130,11 +130,11 @@ def edit_scheduled_message(
sender: UserProfile,
client: Client,
scheduled_message_id: int,
- recipient_type_name: Optional[str],
- message_to: Optional[str],
- topic_name: Optional[str],
- message_content: Optional[str],
- deliver_at: Optional[datetime],
+ recipient_type_name: str | None,
+ message_to: str | None,
+ topic_name: str | None,
+ message_content: str | None,
+ deliver_at: datetime | None,
realm: Realm,
) -> None:
with transaction.atomic():
diff --git a/zerver/actions/streams.py b/zerver/actions/streams.py
index 414aeec8a07..17752c4e10c 100644
--- a/zerver/actions/streams.py
+++ b/zerver/actions/streams.py
@@ -1,6 +1,6 @@
import hashlib
from collections import defaultdict
-from typing import Any, Collection, Iterable, Mapping, Optional
+from typing import Any, Collection, Iterable, Mapping
from django.conf import settings
from django.db import transaction
@@ -111,7 +111,7 @@ def send_user_remove_events_on_stream_deactivation(
@transaction.atomic(savepoint=False)
-def do_deactivate_stream(stream: Stream, *, acting_user: Optional[UserProfile]) -> None:
+def do_deactivate_stream(stream: Stream, *, acting_user: UserProfile | None) -> None:
# If the stream is already deactivated, this is a no-op
if stream.deactivated is True:
raise JsonableError(_("Channel is already deactivated"))
@@ -233,9 +233,7 @@ def deactivated_streams_by_old_name(realm: Realm, stream_name: str) -> QuerySet[
@transaction.atomic(savepoint=False)
-def do_unarchive_stream(
- stream: Stream, new_name: str, *, acting_user: Optional[UserProfile]
-) -> None:
+def do_unarchive_stream(stream: Stream, new_name: str, *, acting_user: UserProfile | None) -> None:
realm = stream.realm
if not stream.deactivated:
raise JsonableError(_("Channel is not currently deactivated"))
@@ -394,7 +392,7 @@ def merge_streams(
def get_subscriber_ids(
- stream: Stream, requesting_user: Optional[UserProfile] = None
+ stream: Stream, requesting_user: UserProfile | None = None
) -> ValuesQuerySet[Subscription, int]:
subscriptions_query = get_subscribers_query(stream, requesting_user)
return subscriptions_query.values_list("user_profile_id", flat=True)
@@ -480,7 +478,7 @@ def send_subscription_add_events(
@transaction.atomic(savepoint=False)
def bulk_add_subs_to_db_with_logging(
realm: Realm,
- acting_user: Optional[UserProfile],
+ acting_user: UserProfile | None,
subs_to_add: list[SubInfo],
subs_to_activate: list[SubInfo],
) -> None:
@@ -711,7 +709,7 @@ def bulk_add_subscriptions(
color_map: Mapping[str, str] = {},
from_user_creation: bool = False,
*,
- acting_user: Optional[UserProfile],
+ acting_user: UserProfile | None,
) -> SubT:
users = list(users)
user_ids = [user.id for user in users]
@@ -731,7 +729,7 @@ def bulk_add_subscriptions(
for stream in streams:
assert stream.recipient_id is not None
recipient_ids_set.add(stream.recipient_id)
- color: Optional[str] = color_map.get(stream.name, None)
+ color: str | None = color_map.get(stream.name, None)
if color is not None:
recipient_color_map[stream.recipient_id] = color
@@ -1006,7 +1004,7 @@ def bulk_remove_subscriptions(
users: Iterable[UserProfile],
streams: Iterable[Stream],
*,
- acting_user: Optional[UserProfile],
+ acting_user: UserProfile | None,
) -> SubAndRemovedT:
users = list(users)
streams = list(streams)
@@ -1110,7 +1108,7 @@ def do_change_subscription_property(
property_name: str,
value: Any,
*,
- acting_user: Optional[UserProfile],
+ acting_user: UserProfile | None,
) -> None:
database_property_name = property_name
database_value = value
@@ -1548,7 +1546,7 @@ def do_change_stream_description(
def send_change_stream_message_retention_days_notification(
- user_profile: UserProfile, stream: Stream, old_value: Optional[int], new_value: Optional[int]
+ user_profile: UserProfile, stream: Stream, old_value: int | None, new_value: int | None
) -> None:
sender = get_system_bot(settings.NOTIFICATION_BOT, user_profile.realm_id)
user_mention = silent_mention_syntax_for_user(user_profile)
@@ -1596,7 +1594,7 @@ def send_change_stream_message_retention_days_notification(
def do_change_stream_message_retention_days(
- stream: Stream, acting_user: UserProfile, message_retention_days: Optional[int] = None
+ stream: Stream, acting_user: UserProfile, message_retention_days: int | None = None
) -> None:
old_message_retention_days_value = stream.message_retention_days
@@ -1637,7 +1635,7 @@ def do_change_stream_group_based_setting(
setting_name: str,
user_group: UserGroup,
*,
- acting_user: Optional[UserProfile] = None,
+ acting_user: UserProfile | None = None,
) -> None:
old_user_group = getattr(stream, setting_name)
old_user_group_id = None
diff --git a/zerver/actions/uploads.py b/zerver/actions/uploads.py
index 9fb589172d8..514d478c6c4 100644
--- a/zerver/actions/uploads.py
+++ b/zerver/actions/uploads.py
@@ -1,5 +1,5 @@
import logging
-from typing import Any, Union
+from typing import Any
from zerver.lib.attachments import get_old_unclaimed_attachments, validate_attachment_request
from zerver.lib.markdown import MessageRenderingResult
@@ -21,7 +21,7 @@ def notify_attachment_update(
def do_claim_attachments(
- message: Union[Message, ScheduledMessage], potential_path_ids: list[str]
+ message: Message | ScheduledMessage, potential_path_ids: list[str]
) -> bool:
claimed = False
for path_id in potential_path_ids:
@@ -82,7 +82,7 @@ def do_delete_old_unclaimed_attachments(weeks_ago: int) -> None:
def check_attachment_reference_change(
- message: Union[Message, ScheduledMessage], rendering_result: MessageRenderingResult
+ message: Message | ScheduledMessage, rendering_result: MessageRenderingResult
) -> bool:
# For a unsaved message edit (message.* has been updated, but not
# saved to the database), adjusts Attachment data to correspond to
diff --git a/zerver/actions/user_groups.py b/zerver/actions/user_groups.py
index 4cff32f24db..31005991079 100644
--- a/zerver/actions/user_groups.py
+++ b/zerver/actions/user_groups.py
@@ -1,5 +1,5 @@
from datetime import datetime
-from typing import Mapping, Optional, Sequence, TypedDict, Union
+from typing import Mapping, Sequence, TypedDict
import django.db.utils
from django.db import transaction
@@ -40,7 +40,7 @@ def create_user_group_in_database(
members: list[UserProfile],
realm: Realm,
*,
- acting_user: Optional[UserProfile],
+ acting_user: UserProfile | None,
description: str = "",
group_settings_map: Mapping[str, UserGroup] = {},
is_system_group: bool = False,
@@ -92,7 +92,7 @@ def create_user_group_in_database(
@transaction.atomic(savepoint=False)
def update_users_in_full_members_system_group(
- realm: Realm, affected_user_ids: Sequence[int] = [], *, acting_user: Optional[UserProfile]
+ realm: Realm, affected_user_ids: Sequence[int] = [], *, acting_user: UserProfile | None
) -> None:
full_members_system_group = NamedUserGroup.objects.get(
realm=realm, name=SystemGroups.FULL_MEMBERS, is_system_group=True
@@ -191,7 +191,7 @@ def check_add_user_group(
description: str = "",
group_settings_map: Mapping[str, UserGroup] = {},
*,
- acting_user: Optional[UserProfile],
+ acting_user: UserProfile | None,
) -> NamedUserGroup:
try:
user_group = create_user_group_in_database(
@@ -209,7 +209,7 @@ def check_add_user_group(
def do_send_user_group_update_event(
- user_group: NamedUserGroup, data: dict[str, Union[str, int, AnonymousSettingGroupDict]]
+ user_group: NamedUserGroup, data: dict[str, str | int | AnonymousSettingGroupDict]
) -> None:
event = dict(type="user_group", op="update", group_id=user_group.id, data=data)
send_event(user_group.realm, event, active_user_ids(user_group.realm_id))
@@ -217,7 +217,7 @@ def do_send_user_group_update_event(
@transaction.atomic(savepoint=False)
def do_update_user_group_name(
- user_group: NamedUserGroup, name: str, *, acting_user: Optional[UserProfile]
+ user_group: NamedUserGroup, name: str, *, acting_user: UserProfile | None
) -> None:
try:
old_value = user_group.name
@@ -241,7 +241,7 @@ def do_update_user_group_name(
@transaction.atomic(savepoint=False)
def do_update_user_group_description(
- user_group: NamedUserGroup, description: str, *, acting_user: Optional[UserProfile]
+ user_group: NamedUserGroup, description: str, *, acting_user: UserProfile | None
) -> None:
old_value = user_group.description
user_group.description = description
@@ -272,7 +272,7 @@ def bulk_add_members_to_user_groups(
user_groups: list[NamedUserGroup],
user_profile_ids: list[int],
*,
- acting_user: Optional[UserProfile],
+ acting_user: UserProfile | None,
) -> None:
# All intended callers of this function involve a single user
# being added to one or more groups, or many users being added to
@@ -308,7 +308,7 @@ def bulk_remove_members_from_user_groups(
user_groups: list[NamedUserGroup],
user_profile_ids: list[int],
*,
- acting_user: Optional[UserProfile],
+ acting_user: UserProfile | None,
) -> None:
# All intended callers of this function involve a single user
# being added to one or more groups, or many users being added to
@@ -350,7 +350,7 @@ def add_subgroups_to_user_group(
user_group: NamedUserGroup,
subgroups: list[NamedUserGroup],
*,
- acting_user: Optional[UserProfile],
+ acting_user: UserProfile | None,
) -> None:
group_memberships = [
GroupGroupMembership(supergroup=user_group, subgroup=subgroup) for subgroup in subgroups
@@ -390,7 +390,7 @@ def remove_subgroups_from_user_group(
user_group: NamedUserGroup,
subgroups: list[NamedUserGroup],
*,
- acting_user: Optional[UserProfile],
+ acting_user: UserProfile | None,
) -> None:
GroupGroupMembership.objects.filter(supergroup=user_group, subgroup__in=subgroups).delete()
@@ -439,8 +439,8 @@ def do_change_user_group_permission_setting(
setting_name: str,
setting_value_group: UserGroup,
*,
- old_setting_api_value: Union[int, AnonymousSettingGroupDict],
- acting_user: Optional[UserProfile],
+ old_setting_api_value: int | AnonymousSettingGroupDict,
+ acting_user: UserProfile | None,
) -> None:
old_value = getattr(user_group, setting_name)
setattr(user_group, setting_name, setting_value_group)
@@ -475,7 +475,7 @@ def do_change_user_group_permission_setting(
},
)
- event_data_dict: dict[str, Union[str, int, AnonymousSettingGroupDict]] = {
+ event_data_dict: dict[str, str | int | AnonymousSettingGroupDict] = {
setting_name: new_setting_api_value
}
do_send_user_group_update_event(user_group, event_data_dict)
diff --git a/zerver/actions/user_settings.py b/zerver/actions/user_settings.py
index 77c218cd38c..c796af6bf76 100644
--- a/zerver/actions/user_settings.py
+++ b/zerver/actions/user_settings.py
@@ -1,5 +1,5 @@
from datetime import timedelta
-from typing import Iterable, Optional, Union
+from typing import Iterable
from django.conf import settings
from django.db import transaction
@@ -214,7 +214,7 @@ def do_change_password(user_profile: UserProfile, password: str, commit: bool =
def do_change_full_name(
- user_profile: UserProfile, full_name: str, acting_user: Optional[UserProfile]
+ user_profile: UserProfile, full_name: str, acting_user: UserProfile | None
) -> None:
old_name = user_profile.full_name
user_profile.full_name = full_name
@@ -243,7 +243,7 @@ def do_change_full_name(
def check_change_full_name(
- user_profile: UserProfile, full_name_raw: str, acting_user: Optional[UserProfile]
+ user_profile: UserProfile, full_name_raw: str, acting_user: UserProfile | None
) -> str:
"""Verifies that the user's proposed full name is valid. The caller
is responsible for checking check permissions. Returns the new
@@ -278,7 +278,7 @@ def check_change_bot_full_name(
@transaction.atomic(durable=True)
-def do_change_tos_version(user_profile: UserProfile, tos_version: Optional[str]) -> None:
+def do_change_tos_version(user_profile: UserProfile, tos_version: str | None) -> None:
user_profile.tos_version = tos_version
user_profile.save(update_fields=["tos_version"])
event_time = timezone_now()
@@ -377,7 +377,7 @@ def do_change_avatar_fields(
avatar_source: str,
skip_notify: bool = False,
*,
- acting_user: Optional[UserProfile],
+ acting_user: UserProfile | None,
) -> None:
user_profile.avatar_source = avatar_source
user_profile.avatar_version += 1
@@ -396,7 +396,7 @@ def do_change_avatar_fields(
notify_avatar_url_change(user_profile)
-def do_delete_avatar_image(user: UserProfile, *, acting_user: Optional[UserProfile]) -> None:
+def do_delete_avatar_image(user: UserProfile, *, acting_user: UserProfile | None) -> None:
old_version = user.avatar_version
do_change_avatar_fields(user, UserProfile.AVATAR_FROM_GRAVATAR, acting_user=acting_user)
delete_avatar_image(user, old_version)
@@ -422,9 +422,9 @@ def update_scheduled_email_notifications_time(
def do_change_user_setting(
user_profile: UserProfile,
setting_name: str,
- setting_value: Union[bool, str, int],
+ setting_value: bool | str | int,
*,
- acting_user: Optional[UserProfile],
+ acting_user: UserProfile | None,
) -> None:
old_value = getattr(user_profile, setting_name)
event_time = timezone_now()
diff --git a/zerver/actions/user_status.py b/zerver/actions/user_status.py
index dedaf26fd4e..4ec0a0e55cd 100644
--- a/zerver/actions/user_status.py
+++ b/zerver/actions/user_status.py
@@ -1,5 +1,3 @@
-from typing import Optional
-
from zerver.actions.user_settings import do_change_user_setting
from zerver.lib.user_status import update_user_status
from zerver.lib.users import get_user_ids_who_can_access_user
@@ -9,12 +7,12 @@ from zerver.tornado.django_api import send_event
def do_update_user_status(
user_profile: UserProfile,
- away: Optional[bool],
- status_text: Optional[str],
+ away: bool | None,
+ status_text: str | None,
client_id: int,
- emoji_name: Optional[str],
- emoji_code: Optional[str],
- reaction_type: Optional[str],
+ emoji_name: str | None,
+ emoji_code: str | None,
+ reaction_type: str | None,
) -> None:
# Deprecated way for clients to access the user's `presence_enabled`
# setting, with away != presence_enabled. Can be removed when clients
diff --git a/zerver/actions/user_topics.py b/zerver/actions/user_topics.py
index 811db688073..0e485f5f15b 100644
--- a/zerver/actions/user_topics.py
+++ b/zerver/actions/user_topics.py
@@ -1,5 +1,5 @@
from datetime import datetime
-from typing import Any, Optional
+from typing import Any
from django.db import transaction
from django.utils.timezone import now as timezone_now
@@ -20,7 +20,7 @@ def bulk_do_set_user_topic_visibility_policy(
topic_name: str,
*,
visibility_policy: int,
- last_updated: Optional[datetime] = None,
+ last_updated: datetime | None = None,
skip_muted_topics_event: bool = False,
) -> None:
if last_updated is None:
@@ -68,7 +68,7 @@ def do_set_user_topic_visibility_policy(
topic_name: str,
*,
visibility_policy: int,
- last_updated: Optional[datetime] = None,
+ last_updated: datetime | None = None,
skip_muted_topics_event: bool = False,
) -> None:
# For conciseness, this function should be used when a single
diff --git a/zerver/actions/users.py b/zerver/actions/users.py
index b36ff9c8cbe..faee21b25a6 100644
--- a/zerver/actions/users.py
+++ b/zerver/actions/users.py
@@ -1,7 +1,7 @@
import secrets
from collections import defaultdict
from email.headerregistry import Address
-from typing import Any, Optional
+from typing import Any
from django.conf import settings
from django.db import transaction
@@ -56,7 +56,7 @@ if settings.BILLING_ENABLED:
from corporate.lib.stripe import RealmBillingSession
-def do_delete_user(user_profile: UserProfile, *, acting_user: Optional[UserProfile]) -> None:
+def do_delete_user(user_profile: UserProfile, *, acting_user: UserProfile | None) -> None:
if user_profile.realm.is_zephyr_mirror_realm:
raise AssertionError("Deleting zephyr mirror users is not supported")
@@ -318,7 +318,7 @@ def send_events_for_user_deactivation(user_profile: UserProfile) -> None:
def do_deactivate_user(
- user_profile: UserProfile, _cascade: bool = True, *, acting_user: Optional[UserProfile]
+ user_profile: UserProfile, _cascade: bool = True, *, acting_user: UserProfile | None
) -> None:
if not user_profile.is_active:
return
@@ -433,7 +433,7 @@ def send_stream_events_for_role_update(
@transaction.atomic(savepoint=False)
def do_change_user_role(
- user_profile: UserProfile, value: int, *, acting_user: Optional[UserProfile]
+ user_profile: UserProfile, value: int, *, acting_user: UserProfile | None
) -> None:
# We want to both (a) take a lock on the UserProfile row, and (b)
# modify the passed-in UserProfile object, so that callers see the
diff --git a/zerver/actions/video_calls.py b/zerver/actions/video_calls.py
index ddf57f75b0a..d4c8603cd98 100644
--- a/zerver/actions/video_calls.py
+++ b/zerver/actions/video_calls.py
@@ -1,10 +1,8 @@
-from typing import Optional
-
from zerver.models import UserProfile
from zerver.tornado.django_api import send_event
-def do_set_zoom_token(user: UserProfile, token: Optional[dict[str, object]]) -> None:
+def do_set_zoom_token(user: UserProfile, token: dict[str, object] | None) -> None:
user.zoom_token = token
user.save(update_fields=["zoom_token"])
send_event(
diff --git a/zerver/apps.py b/zerver/apps.py
index 5ff2f301e4d..f9c1e8682b5 100644
--- a/zerver/apps.py
+++ b/zerver/apps.py
@@ -1,5 +1,5 @@
import logging
-from typing import Any, Optional
+from typing import Any
from django.apps import AppConfig
from django.conf import settings
@@ -8,7 +8,7 @@ from django.db.models.signals import post_migrate
from typing_extensions import override
-def flush_cache(sender: Optional[AppConfig], **kwargs: Any) -> None:
+def flush_cache(sender: AppConfig | None, **kwargs: Any) -> None:
logging.info("Clearing memcached cache after migrations")
cache.clear()
diff --git a/zerver/context_processors.py b/zerver/context_processors.py
index 304c435e844..27845ad6a1a 100644
--- a/zerver/context_processors.py
+++ b/zerver/context_processors.py
@@ -1,4 +1,4 @@
-from typing import Any, Mapping, Optional
+from typing import Any, Mapping
from urllib.parse import urljoin
from django.conf import settings
@@ -53,7 +53,7 @@ def common_context(user: UserProfile) -> dict[str, Any]:
}
-def get_realm_from_request(request: HttpRequest) -> Optional[Realm]:
+def get_realm_from_request(request: HttpRequest) -> Realm | None:
request_notes = RequestNotes.get_notes(request)
if request.user.is_authenticated:
return request.user.realm
diff --git a/zerver/data_import/import_util.py b/zerver/data_import/import_util.py
index 51ae37457ba..d5342e21a19 100644
--- a/zerver/data_import/import_util.py
+++ b/zerver/data_import/import_util.py
@@ -4,17 +4,7 @@ import random
import shutil
from collections import defaultdict
from concurrent.futures import ProcessPoolExecutor, as_completed
-from typing import (
- AbstractSet,
- Any,
- Callable,
- Iterable,
- Iterator,
- Mapping,
- Optional,
- Protocol,
- TypeVar,
-)
+from typing import AbstractSet, Any, Callable, Iterable, Iterator, Mapping, Protocol, TypeVar
import orjson
import requests
@@ -51,8 +41,8 @@ class SubscriberHandler:
def set_info(
self,
users: set[int],
- stream_id: Optional[int] = None,
- direct_message_group_id: Optional[int] = None,
+ stream_id: int | None = None,
+ direct_message_group_id: int | None = None,
) -> None:
if stream_id is not None:
self.stream_info[stream_id] = users
@@ -62,7 +52,7 @@ class SubscriberHandler:
raise AssertionError("stream_id or direct_message_group_id is required")
def get_users(
- self, stream_id: Optional[int] = None, direct_message_group_id: Optional[int] = None
+ self, stream_id: int | None = None, direct_message_group_id: int | None = None
) -> set[int]:
if stream_id is not None:
return self.stream_info[stream_id]
@@ -104,7 +94,7 @@ def build_user_profile(
short_name: str,
timezone: str,
is_bot: bool = False,
- bot_type: Optional[int] = None,
+ bot_type: int | None = None,
) -> ZerverFieldsT:
obj = UserProfile(
avatar_source=avatar_source,
@@ -494,7 +484,7 @@ def build_message(
date_sent: float,
message_id: int,
content: str,
- rendered_content: Optional[str],
+ rendered_content: str | None,
user_id: int,
recipient_id: int,
realm_id: int,
@@ -759,7 +749,7 @@ ExternalId = TypeVar("ExternalId")
def long_term_idle_helper(
message_iterator: Iterator[ZerverFieldsT],
- user_from_message: Callable[[ZerverFieldsT], Optional[ExternalId]],
+ user_from_message: Callable[[ZerverFieldsT], ExternalId | None],
timestamp_from_message: Callable[[ZerverFieldsT], float],
zulip_user_id_from_user: Callable[[ExternalId], int],
all_user_ids_iterator: Iterator[ExternalId],
diff --git a/zerver/data_import/slack.py b/zerver/data_import/slack.py
index fc8974c7989..1a7eb2ec824 100644
--- a/zerver/data_import/slack.py
+++ b/zerver/data_import/slack.py
@@ -9,7 +9,7 @@ import zipfile
from collections import defaultdict
from datetime import datetime, timezone
from email.headerregistry import Address
-from typing import Any, Iterator, Optional, TypeVar
+from typing import Any, Iterator, TypeVar
from urllib.parse import urlsplit
import orjson
@@ -1242,7 +1242,7 @@ def build_uploads(
uploads_list.append(upload)
-def get_message_sending_user(message: ZerverFieldsT) -> Optional[str]:
+def get_message_sending_user(message: ZerverFieldsT) -> str | None:
if "user" in message:
return message["user"]
if message.get("file"):
diff --git a/zerver/data_import/slack_message_conversion.py b/zerver/data_import/slack_message_conversion.py
index fbd5e2c7814..42edc417c9b 100644
--- a/zerver/data_import/slack_message_conversion.py
+++ b/zerver/data_import/slack_message_conversion.py
@@ -1,5 +1,5 @@
import re
-from typing import Any, Optional
+from typing import Any
from typing_extensions import TypeAlias
@@ -118,7 +118,7 @@ def convert_to_zulip_markdown(
def get_user_mentions(
token: str, users: list[ZerverFieldsT], slack_user_id_to_zulip_user_id: SlackToZulipUserIDT
-) -> tuple[str, Optional[int]]:
+) -> tuple[str, int | None]:
slack_usermention_match = re.search(SLACK_USERMENTION_REGEX, token, re.VERBOSE)
assert slack_usermention_match is not None
short_name = slack_usermention_match.group(4)
diff --git a/zerver/decorator.py b/zerver/decorator.py
index 0b3a9f5f6bd..ad574e66a55 100644
--- a/zerver/decorator.py
+++ b/zerver/decorator.py
@@ -3,7 +3,7 @@ import logging
from datetime import datetime
from functools import wraps
from io import BytesIO
-from typing import TYPE_CHECKING, Callable, Optional, Sequence, TypeVar, Union, cast, overload
+from typing import TYPE_CHECKING, Callable, Sequence, TypeVar, cast, overload
from urllib.parse import urlsplit
import django_otp
@@ -67,7 +67,7 @@ ReturnT = TypeVar("ReturnT")
def update_user_activity(
- request: HttpRequest, user_profile: UserProfile, query: Optional[str]
+ request: HttpRequest, user_profile: UserProfile, query: str | None
) -> None:
# update_active_status also pushes to RabbitMQ, and it seems
# redundant to log that here as well.
@@ -194,11 +194,11 @@ def require_billing_access(
def process_client(
request: HttpRequest,
- user: Union[UserProfile, AnonymousUser, None] = None,
+ user: UserProfile | AnonymousUser | None = None,
*,
is_browser_view: bool = False,
- client_name: Optional[str] = None,
- query: Optional[str] = None,
+ client_name: str | None = None,
+ query: str | None = None,
) -> None:
"""The optional user parameter requests that a UserActivity row be
created/updated to record this request.
@@ -228,10 +228,10 @@ def process_client(
def validate_api_key(
request: HttpRequest,
- role: Optional[str],
+ role: str | None,
api_key: str,
allow_webhook_access: bool = False,
- client_name: Optional[str] = None,
+ client_name: str | None = None,
) -> UserProfile:
# Remove whitespace to protect users from trivial errors.
api_key = api_key.strip()
@@ -271,7 +271,7 @@ def validate_account_and_subdomain(request: HttpRequest, user_profile: UserProfi
def access_user_by_api_key(
- request: HttpRequest, api_key: str, email: Optional[str] = None
+ request: HttpRequest, api_key: str, email: str | None = None
) -> UserProfile:
if not has_api_key_format(api_key):
raise InvalidAPIKeyFormatError
@@ -315,7 +315,7 @@ def log_exception_to_webhook_logger(request: HttpRequest, err: Exception) -> Non
webhook_logger.exception(err, stack_info=True, extra=extra)
-def full_webhook_client_name(raw_client_name: Optional[str] = None) -> Optional[str]:
+def full_webhook_client_name(raw_client_name: str | None = None) -> str | None:
if raw_client_name is None:
return None
return f"Zulip{raw_client_name}Webhook"
@@ -325,7 +325,7 @@ def full_webhook_client_name(raw_client_name: Optional[str] = None) -> Optional[
def webhook_view(
webhook_client_name: str,
notify_bot_owner_on_invalid_json: bool = True,
- all_event_types: Optional[Sequence[str]] = None,
+ all_event_types: Sequence[str] | None = None,
) -> Callable[[Callable[..., HttpResponse]], Callable[..., HttpResponse]]:
# Unfortunately, callback protocols are insufficient for this:
# https://mypy.readthedocs.io/en/stable/protocols.html#callback-protocols
@@ -378,7 +378,7 @@ def webhook_view(
def zulip_redirect_to_login(
request: HttpRequest,
- login_url: Optional[str] = None,
+ login_url: str | None = None,
redirect_field_name: str = REDIRECT_FIELD_NAME,
) -> HttpResponseRedirect:
path = request.build_absolute_uri()
@@ -405,7 +405,7 @@ def zulip_redirect_to_login(
# stock Django version.
def user_passes_test(
test_func: Callable[[HttpRequest], bool],
- login_url: Optional[str] = None,
+ login_url: str | None = None,
redirect_field_name: str = REDIRECT_FIELD_NAME,
) -> Callable[
[Callable[Concatenate[HttpRequest, ParamT], HttpResponse]],
@@ -543,16 +543,16 @@ def zulip_login_required(
Callable[Concatenate[HttpRequest, ParamT], HttpResponse],
]: ...
def zulip_login_required(
- function: Optional[Callable[Concatenate[HttpRequest, ParamT], HttpResponse]] = None,
+ function: Callable[Concatenate[HttpRequest, ParamT], HttpResponse] | None = None,
redirect_field_name: str = REDIRECT_FIELD_NAME,
login_url: str = settings.HOME_NOT_LOGGED_IN,
-) -> Union[
+) -> (
Callable[
[Callable[Concatenate[HttpRequest, ParamT], HttpResponse]],
Callable[Concatenate[HttpRequest, ParamT], HttpResponse],
- ],
- Callable[Concatenate[HttpRequest, ParamT], HttpResponse],
-]:
+ ]
+ | Callable[Concatenate[HttpRequest, ParamT], HttpResponse]
+):
actual_decorator = lambda function: user_passes_test(
logged_in_and_active,
login_url=login_url,
@@ -733,7 +733,7 @@ def get_basic_credentials(
# with that string as the basis for the client string.
def authenticated_rest_api_view(
*,
- webhook_client_name: Optional[str] = None,
+ webhook_client_name: str | None = None,
allow_webhook_access: bool = False,
skip_rate_limiting: bool = False,
beanstalk_email_decode: bool = False,
@@ -842,7 +842,7 @@ def process_as_post(
def public_json_view(
view_func: Callable[
- Concatenate[HttpRequest, Union[UserProfile, AnonymousUser], ParamT], HttpResponse
+ Concatenate[HttpRequest, UserProfile | AnonymousUser, ParamT], HttpResponse
],
skip_rate_limiting: bool = False,
) -> Callable[Concatenate[HttpRequest, ParamT], HttpResponse]:
@@ -989,7 +989,7 @@ def zulip_otp_required_if_logged_in(
to :setting:`OTP_LOGIN_URL`. Returns True if the user is not authenticated.
"""
- def test(user: Union[AbstractBaseUser, AnonymousUser]) -> bool:
+ def test(user: AbstractBaseUser | AnonymousUser) -> bool:
"""
:if_configured: If ``True``, an authenticated user with no confirmed
OTP devices will be allowed. Also, non-authenticated users will be
diff --git a/zerver/filters.py b/zerver/filters.py
index 7878587c7b8..73caf381401 100644
--- a/zerver/filters.py
+++ b/zerver/filters.py
@@ -1,4 +1,4 @@
-from typing import Any, Optional
+from typing import Any
from django.http import HttpRequest
from django.views.debug import SafeExceptionReporterFilter
@@ -7,7 +7,7 @@ from typing_extensions import override
class ZulipExceptionReporterFilter(SafeExceptionReporterFilter):
@override
- def get_post_parameters(self, request: Optional[HttpRequest]) -> dict[str, Any]:
+ def get_post_parameters(self, request: HttpRequest | None) -> dict[str, Any]:
post_data = SafeExceptionReporterFilter.get_post_parameters(self, request)
assert isinstance(post_data, dict)
filtered_post = post_data.copy()
diff --git a/zerver/forms.py b/zerver/forms.py
index f98070f66f8..9bf19c001f0 100644
--- a/zerver/forms.py
+++ b/zerver/forms.py
@@ -1,7 +1,7 @@
import logging
import re
from email.headerregistry import Address
-from typing import Any, Optional
+from typing import Any
import DNS
from django import forms
@@ -368,15 +368,15 @@ class ZulipPasswordResetForm(PasswordResetForm):
@override
def save(
self,
- domain_override: Optional[str] = None,
+ domain_override: str | None = None,
subject_template_name: str = "registration/password_reset_subject.txt",
email_template_name: str = "registration/password_reset_email.html",
use_https: bool = False,
token_generator: PasswordResetTokenGenerator = default_token_generator,
- from_email: Optional[str] = None,
- request: Optional[HttpRequest] = None,
- html_email_template_name: Optional[str] = None,
- extra_email_context: Optional[dict[str, Any]] = None,
+ from_email: str | None = None,
+ request: HttpRequest | None = None,
+ html_email_template_name: str | None = None,
+ extra_email_context: dict[str, Any] | None = None,
) -> None:
"""
If the email address has an account in the target realm,
@@ -592,7 +592,7 @@ class AuthenticationTokenForm(TwoFactorAuthenticationTokenForm):
class MultiEmailField(forms.Field):
@override
- def to_python(self, emails: Optional[str]) -> list[str]:
+ def to_python(self, emails: str | None) -> list[str]:
"""Normalize data to a list of strings."""
if not emails:
return []
diff --git a/zerver/lib/addressee.py b/zerver/lib/addressee.py
index 399a7dca879..700eb54a6a4 100644
--- a/zerver/lib/addressee.py
+++ b/zerver/lib/addressee.py
@@ -1,4 +1,4 @@
-from typing import Iterable, Optional, Sequence, Union, cast
+from typing import Iterable, Sequence, cast
from django.utils.translation import gettext as _
@@ -48,11 +48,11 @@ class Addressee:
def __init__(
self,
msg_type: str,
- user_profiles: Optional[Sequence[UserProfile]] = None,
- stream: Optional[Stream] = None,
- stream_name: Optional[str] = None,
- stream_id: Optional[int] = None,
- topic_name: Optional[str] = None,
+ user_profiles: Sequence[UserProfile] | None = None,
+ stream: Stream | None = None,
+ stream_name: str | None = None,
+ stream_id: int | None = None,
+ topic_name: str | None = None,
) -> None:
assert msg_type in ["stream", "private"]
if msg_type == "stream" and topic_name is None:
@@ -75,15 +75,15 @@ class Addressee:
assert self._user_profiles is not None
return self._user_profiles
- def stream(self) -> Optional[Stream]:
+ def stream(self) -> Stream | None:
assert self.is_stream()
return self._stream
- def stream_name(self) -> Optional[str]:
+ def stream_name(self) -> str | None:
assert self.is_stream()
return self._stream_name
- def stream_id(self) -> Optional[int]:
+ def stream_id(self) -> int | None:
assert self.is_stream()
return self._stream_id
@@ -96,9 +96,9 @@ class Addressee:
def legacy_build(
sender: UserProfile,
recipient_type_name: str,
- message_to: Union[Sequence[int], Sequence[str]],
- topic_name: Optional[str],
- realm: Optional[Realm] = None,
+ message_to: Sequence[int] | Sequence[str],
+ topic_name: str | None,
+ realm: Realm | None = None,
) -> "Addressee":
# For legacy reason message_to used to be either a list of
# emails or a list of streams. We haven't fixed all of our
diff --git a/zerver/lib/attachments.py b/zerver/lib/attachments.py
index 373468aa268..dadd400708d 100644
--- a/zerver/lib/attachments.py
+++ b/zerver/lib/attachments.py
@@ -1,5 +1,5 @@
from datetime import timedelta
-from typing import Any, Optional, Union
+from typing import Any
from django.conf import settings
from django.contrib.auth.models import AnonymousUser
@@ -52,7 +52,7 @@ def remove_attachment(user_profile: UserProfile, attachment: Attachment) -> None
def validate_attachment_request_for_spectator_access(
realm: Realm, attachment: Attachment
-) -> Optional[bool]:
+) -> bool | None:
if attachment.realm != realm:
return False
@@ -89,10 +89,10 @@ def validate_attachment_request_for_spectator_access(
def validate_attachment_request(
- maybe_user_profile: Union[UserProfile, AnonymousUser],
+ maybe_user_profile: UserProfile | AnonymousUser,
path_id: str,
- realm: Optional[Realm] = None,
-) -> Optional[bool]:
+ realm: Realm | None = None,
+) -> bool | None:
try:
attachment = Attachment.objects.get(path_id=path_id)
except Attachment.DoesNotExist:
diff --git a/zerver/lib/avatar.py b/zerver/lib/avatar.py
index 6abec2bd4c7..a53b163e5a9 100644
--- a/zerver/lib/avatar.py
+++ b/zerver/lib/avatar.py
@@ -1,4 +1,3 @@
-from typing import Optional
from urllib.parse import urljoin
from django.conf import settings
@@ -17,7 +16,7 @@ from zerver.models import UserProfile
def avatar_url(
user_profile: UserProfile, medium: bool = False, client_gravatar: bool = False
-) -> Optional[str]:
+) -> str | None:
return get_avatar_field(
user_id=user_profile.id,
realm_id=user_profile.realm_id,
@@ -37,7 +36,7 @@ def get_avatar_field(
avatar_version: int,
medium: bool,
client_gravatar: bool,
-) -> Optional[str]:
+) -> str | None:
"""
Most of the parameters to this function map to fields
by the same name in UserProfile (avatar_source, realm_id,
diff --git a/zerver/lib/bot_config.py b/zerver/lib/bot_config.py
index dceb0f0af50..e5c8cb66876 100644
--- a/zerver/lib/bot_config.py
+++ b/zerver/lib/bot_config.py
@@ -2,7 +2,6 @@ import configparser
import importlib
import os
from collections import defaultdict
-from typing import Optional
from django.conf import settings
from django.db.models import F, Sum
@@ -32,7 +31,7 @@ def get_bot_configs(bot_profile_ids: list[int]) -> dict[int, dict[str, str]]:
return entries_by_uid
-def get_bot_config_size(bot_profile: UserProfile, key: Optional[str] = None) -> int:
+def get_bot_config_size(bot_profile: UserProfile, key: str | None = None) -> int:
if key is None:
return (
BotConfigData.objects.filter(bot_profile=bot_profile)
diff --git a/zerver/lib/bot_lib.py b/zerver/lib/bot_lib.py
index b79c9dd0906..68d30291713 100644
--- a/zerver/lib/bot_lib.py
+++ b/zerver/lib/bot_lib.py
@@ -1,6 +1,6 @@
import importlib
import json
-from typing import Any, Callable, Optional
+from typing import Any, Callable
from django.conf import settings
from django.utils.translation import gettext as _
@@ -115,7 +115,7 @@ class EmbeddedBotHandler:
return {"id": message_id}
def send_reply(
- self, message: dict[str, Any], response: str, widget_content: Optional[str] = None
+ self, message: dict[str, Any], response: str, widget_content: str | None = None
) -> dict[str, Any]:
if message["type"] == "private":
result = self.send_message(
diff --git a/zerver/lib/bot_storage.py b/zerver/lib/bot_storage.py
index f218640d207..420f7768c9a 100644
--- a/zerver/lib/bot_storage.py
+++ b/zerver/lib/bot_storage.py
@@ -1,5 +1,3 @@
-from typing import Optional
-
from django.conf import settings
from django.db.models import F, Sum
from django.db.models.functions import Length
@@ -18,7 +16,7 @@ def get_bot_storage(bot_profile: UserProfile, key: str) -> str:
raise StateError("Key does not exist.")
-def get_bot_storage_size(bot_profile: UserProfile, key: Optional[str] = None) -> int:
+def get_bot_storage_size(bot_profile: UserProfile, key: str | None = None) -> int:
if key is None:
return (
BotStorageData.objects.filter(bot_profile=bot_profile)
diff --git a/zerver/lib/bulk_create.py b/zerver/lib/bulk_create.py
index c1204277213..8ddc1991bec 100644
--- a/zerver/lib/bulk_create.py
+++ b/zerver/lib/bulk_create.py
@@ -1,4 +1,4 @@
-from typing import Any, Collection, Iterable, Optional, Union
+from typing import Any, Collection, Iterable
from django.db.models import Model, QuerySet
from django.utils.timezone import now as timezone_now
@@ -23,9 +23,9 @@ from zerver.models.groups import SystemGroups
def bulk_create_users(
realm: Realm,
users_raw: set[tuple[str, str, bool]],
- bot_type: Optional[int] = None,
- bot_owner: Optional[UserProfile] = None,
- tos_version: Optional[str] = None,
+ bot_type: int | None = None,
+ bot_owner: UserProfile | None = None,
+ tos_version: str | None = None,
timezone: str = "",
) -> None:
"""
@@ -163,10 +163,11 @@ def bulk_create_users(
def bulk_set_users_or_streams_recipient_fields(
model: type[Model],
- objects: Union[
- Collection[UserProfile], QuerySet[UserProfile], Collection[Stream], QuerySet[Stream]
- ],
- recipients: Optional[Iterable[Recipient]] = None,
+ objects: Collection[UserProfile]
+ | QuerySet[UserProfile]
+ | Collection[Stream]
+ | QuerySet[Stream],
+ recipients: Iterable[Recipient] | None = None,
) -> None:
assert model in [UserProfile, Stream]
for obj in objects:
@@ -247,7 +248,7 @@ def bulk_create_streams(realm: Realm, stream_dict: dict[str, dict[str, Any]]) ->
def create_users(
- realm: Realm, name_list: Iterable[tuple[str, str]], bot_type: Optional[int] = None
+ realm: Realm, name_list: Iterable[tuple[str, str]], bot_type: int | None = None
) -> None:
user_set = set()
for full_name, email in name_list:
diff --git a/zerver/lib/cache.py b/zerver/lib/cache.py
index 6db393734cd..99861a433ab 100644
--- a/zerver/lib/cache.py
+++ b/zerver/lib/cache.py
@@ -8,7 +8,7 @@ import sys
import time
import traceback
from functools import _lru_cache_wrapper, lru_cache, wraps
-from typing import TYPE_CHECKING, Any, Callable, Generic, Iterable, Optional, Sequence, TypeVar
+from typing import TYPE_CHECKING, Any, Callable, Generic, Iterable, Sequence, TypeVar
from django.conf import settings
from django.core.cache import caches
@@ -104,7 +104,7 @@ def bounce_key_prefix_for_testing(test_name: str) -> None:
KEY_PREFIX = hashlib.sha1(KEY_PREFIX.encode()).hexdigest() + ":"
-def get_cache_backend(cache_name: Optional[str]) -> BaseCache:
+def get_cache_backend(cache_name: str | None) -> BaseCache:
if cache_name is None:
cache_name = "default"
return caches[cache_name]
@@ -112,8 +112,8 @@ def get_cache_backend(cache_name: Optional[str]) -> BaseCache:
def cache_with_key(
keyfunc: Callable[ParamT, str],
- cache_name: Optional[str] = None,
- timeout: Optional[int] = None,
+ cache_name: str | None = None,
+ timeout: int | None = None,
) -> Callable[[Callable[ParamT, ReturnT]], Callable[ParamT, ReturnT]]:
"""Decorator which applies Django caching to a function.
@@ -186,7 +186,7 @@ def validate_cache_key(key: str) -> None:
def cache_set(
- key: str, val: Any, cache_name: Optional[str] = None, timeout: Optional[int] = None
+ key: str, val: Any, cache_name: str | None = None, timeout: int | None = None
) -> None:
final_key = KEY_PREFIX + key
validate_cache_key(final_key)
@@ -197,7 +197,7 @@ def cache_set(
remote_cache_stats_finish()
-def cache_get(key: str, cache_name: Optional[str] = None) -> Any:
+def cache_get(key: str, cache_name: str | None = None) -> Any:
final_key = KEY_PREFIX + key
validate_cache_key(final_key)
@@ -208,7 +208,7 @@ def cache_get(key: str, cache_name: Optional[str] = None) -> Any:
return ret
-def cache_get_many(keys: list[str], cache_name: Optional[str] = None) -> dict[str, Any]:
+def cache_get_many(keys: list[str], cache_name: str | None = None) -> dict[str, Any]:
keys = [KEY_PREFIX + key for key in keys]
for key in keys:
validate_cache_key(key)
@@ -218,7 +218,7 @@ def cache_get_many(keys: list[str], cache_name: Optional[str] = None) -> dict[st
return {key[len(KEY_PREFIX) :]: value for key, value in ret.items()}
-def safe_cache_get_many(keys: list[str], cache_name: Optional[str] = None) -> dict[str, Any]:
+def safe_cache_get_many(keys: list[str], cache_name: str | None = None) -> dict[str, Any]:
"""Variant of cache_get_many that drops any keys that fail
validation, rather than throwing an exception visible to the
caller."""
@@ -236,7 +236,7 @@ def safe_cache_get_many(keys: list[str], cache_name: Optional[str] = None) -> di
def cache_set_many(
- items: dict[str, Any], cache_name: Optional[str] = None, timeout: Optional[int] = None
+ items: dict[str, Any], cache_name: str | None = None, timeout: int | None = None
) -> None:
new_items = {}
for key in items:
@@ -250,7 +250,7 @@ def cache_set_many(
def safe_cache_set_many(
- items: dict[str, Any], cache_name: Optional[str] = None, timeout: Optional[int] = None
+ items: dict[str, Any], cache_name: str | None = None, timeout: int | None = None
) -> None:
"""Variant of cache_set_many that drops saving any keys that fail
validation, rather than throwing an exception visible to the
@@ -270,7 +270,7 @@ def safe_cache_set_many(
return cache_set_many(good_items, cache_name, timeout)
-def cache_delete(key: str, cache_name: Optional[str] = None) -> None:
+def cache_delete(key: str, cache_name: str | None = None) -> None:
final_key = KEY_PREFIX + key
validate_cache_key(final_key)
@@ -279,7 +279,7 @@ def cache_delete(key: str, cache_name: Optional[str] = None) -> None:
remote_cache_stats_finish()
-def cache_delete_many(items: Iterable[str], cache_name: Optional[str] = None) -> None:
+def cache_delete_many(items: Iterable[str], cache_name: str | None = None) -> None:
keys = [KEY_PREFIX + item for item in items]
for key in keys:
validate_cache_key(key)
@@ -536,7 +536,7 @@ def delete_display_recipient_cache(user_profile: "UserProfile") -> None:
cache_delete_many(keys)
-def changed(update_fields: Optional[Sequence[str]], fields: list[str]) -> bool:
+def changed(update_fields: Sequence[str] | None, fields: list[str]) -> bool:
if update_fields is None:
# adds/deletes should invalidate the cache
return True
@@ -550,7 +550,7 @@ def changed(update_fields: Optional[Sequence[str]], fields: list[str]) -> bool:
def flush_user_profile(
*,
instance: "UserProfile",
- update_fields: Optional[Sequence[str]] = None,
+ update_fields: Sequence[str] | None = None,
**kwargs: object,
) -> None:
user_profile = instance
@@ -588,7 +588,7 @@ def flush_muting_users_cache(*, instance: "MutedUser", **kwargs: object) -> None
def flush_realm(
*,
instance: "Realm",
- update_fields: Optional[Sequence[str]] = None,
+ update_fields: Sequence[str] | None = None,
from_deletion: bool = False,
**kwargs: object,
) -> None:
@@ -635,7 +635,7 @@ def realm_text_description_cache_key(realm: "Realm") -> str:
def flush_stream(
*,
instance: "Stream",
- update_fields: Optional[Sequence[str]] = None,
+ update_fields: Sequence[str] | None = None,
**kwargs: object,
) -> None:
from zerver.models import UserProfile
@@ -667,7 +667,7 @@ def to_dict_cache_key_id(message_id: int) -> str:
return f"message_dict:{message_id}"
-def to_dict_cache_key(message: "Message", realm_id: Optional[int] = None) -> str:
+def to_dict_cache_key(message: "Message", realm_id: int | None = None) -> str:
return to_dict_cache_key_id(message.id)
diff --git a/zerver/lib/ccache.py b/zerver/lib/ccache.py
index e79d3cb719a..966962cdf0c 100644
--- a/zerver/lib/ccache.py
+++ b/zerver/lib/ccache.py
@@ -1,6 +1,6 @@
import base64
import struct
-from typing import Any, Optional
+from typing import Any
# This file is adapted from samples/shellinabox/ssh-krb-wrapper in
# https://github.com/davidben/webathena, which has the following
@@ -101,7 +101,7 @@ def der_encode_octet_string(val: bytes) -> bytes:
return der_encode_tlv(0x04, val)
-def der_encode_sequence(tlvs: list[Optional[bytes]], tagged: bool = True) -> bytes:
+def der_encode_sequence(tlvs: list[bytes | None], tagged: bool = True) -> bytes:
body = []
for i, tlv in enumerate(tlvs):
# Missing optional elements represented as None.
diff --git a/zerver/lib/compatibility.py b/zerver/lib/compatibility.py
index f0571f0682f..2eb7f6ee5ea 100644
--- a/zerver/lib/compatibility.py
+++ b/zerver/lib/compatibility.py
@@ -1,7 +1,6 @@
import os
import re
from datetime import datetime, timedelta, timezone
-from typing import Optional
from django.conf import settings
from django.utils.timezone import now as timezone_now
@@ -21,7 +20,7 @@ else:
LAST_SERVER_UPGRADE_TIME = timezone_now()
-def is_outdated_server(user_profile: Optional[UserProfile]) -> bool:
+def is_outdated_server(user_profile: UserProfile | None) -> bool:
# Release tarballs are unpacked via `tar -xf`, which means the
# `mtime` on files in them is preserved from when the release
# tarball was built. Checking this allows us to catch cases where
@@ -51,7 +50,7 @@ def pop_numerals(ver: str) -> tuple[list[int], str]:
return numbers, rest
-def version_lt(ver1: str, ver2: str) -> Optional[bool]:
+def version_lt(ver1: str, ver2: str) -> bool | None:
"""
Compare two Zulip-style version strings.
@@ -93,7 +92,7 @@ def version_lt(ver1: str, ver2: str) -> Optional[bool]:
return None
-def find_mobile_os(user_agent: str) -> Optional[str]:
+def find_mobile_os(user_agent: str) -> str | None:
if re.search(r"\b Android \b", user_agent, re.IGNORECASE | re.VERBOSE):
return "android"
if re.search(r"\b(?: iOS | iPhone\ OS )\b", user_agent, re.IGNORECASE | re.VERBOSE):
@@ -129,14 +128,14 @@ def is_outdated_desktop_app(user_agent_str: str) -> tuple[bool, bool, bool]:
return (False, False, False)
-def is_unsupported_browser(user_agent: str) -> tuple[bool, Optional[str]]:
+def is_unsupported_browser(user_agent: str) -> tuple[bool, str | None]:
browser_name = get_device_browser(user_agent)
if browser_name == "Internet Explorer":
return (True, browser_name)
return (False, browser_name)
-def is_pronouns_field_type_supported(user_agent_str: Optional[str]) -> bool:
+def is_pronouns_field_type_supported(user_agent_str: str | None) -> bool:
# In order to avoid users having a bad experience with these
# custom profile fields disappearing after applying migration
# 0421_migrate_pronouns_custom_profile_fields, we provide this
diff --git a/zerver/lib/context_managers.py b/zerver/lib/context_managers.py
index 8728d87dd28..31c55c74e4c 100644
--- a/zerver/lib/context_managers.py
+++ b/zerver/lib/context_managers.py
@@ -4,11 +4,11 @@ Context managers, i.e. things you can use with the 'with' statement.
import fcntl
from contextlib import contextmanager
-from typing import IO, Any, Iterator, Union
+from typing import IO, Any, Iterator
@contextmanager
-def flock(lockfile: Union[int, IO[Any]], shared: bool = False) -> Iterator[None]:
+def flock(lockfile: int | IO[Any], shared: bool = False) -> Iterator[None]:
"""Lock a file object using flock(2) for the duration of a 'with' statement.
If shared is True, use a LOCK_SH lock, otherwise LOCK_EX."""
diff --git a/zerver/lib/create_user.py b/zerver/lib/create_user.py
index 9cf97892d64..f3ea7979b30 100644
--- a/zerver/lib/create_user.py
+++ b/zerver/lib/create_user.py
@@ -1,6 +1,5 @@
from datetime import datetime
from email.headerregistry import Address
-from typing import Optional, Union
from django.contrib.auth.models import UserManager
from django.utils.timezone import now as timezone_now
@@ -22,7 +21,7 @@ from zerver.models.realms import get_fake_email_domain
def copy_default_settings(
- settings_source: Union[UserProfile, RealmUserDefault], target_profile: UserProfile
+ settings_source: UserProfile | RealmUserDefault, target_profile: UserProfile
) -> None:
# Important note: Code run from here to configure the user's
# settings should not call send_event, as that would cause clients
@@ -84,18 +83,18 @@ def get_display_email_address(user_profile: UserProfile) -> str:
def create_user_profile(
realm: Realm,
email: str,
- password: Optional[str],
+ password: str | None,
active: bool,
- bot_type: Optional[int],
+ bot_type: int | None,
full_name: str,
- bot_owner: Optional[UserProfile],
+ bot_owner: UserProfile | None,
is_mirror_dummy: bool,
- tos_version: Optional[str],
+ tos_version: str | None,
timezone: str,
default_language: str,
tutorial_status: str = UserProfile.TUTORIAL_WAITING,
- force_id: Optional[int] = None,
- force_date_joined: Optional[datetime] = None,
+ force_id: int | None = None,
+ force_date_joined: datetime | None = None,
*,
email_address_visibility: int,
) -> UserProfile:
@@ -140,27 +139,27 @@ def create_user_profile(
def create_user(
email: str,
- password: Optional[str],
+ password: str | None,
realm: Realm,
full_name: str,
active: bool = True,
- role: Optional[int] = None,
- bot_type: Optional[int] = None,
- bot_owner: Optional[UserProfile] = None,
- tos_version: Optional[str] = None,
+ role: int | None = None,
+ bot_type: int | None = None,
+ bot_owner: UserProfile | None = None,
+ tos_version: str | None = None,
timezone: str = "",
avatar_source: str = UserProfile.AVATAR_FROM_GRAVATAR,
is_mirror_dummy: bool = False,
- default_language: Optional[str] = None,
- default_sending_stream: Optional[Stream] = None,
- default_events_register_stream: Optional[Stream] = None,
- default_all_public_streams: Optional[bool] = None,
- source_profile: Optional[UserProfile] = None,
- force_id: Optional[int] = None,
- force_date_joined: Optional[datetime] = None,
+ default_language: str | None = None,
+ default_sending_stream: Stream | None = None,
+ default_events_register_stream: Stream | None = None,
+ default_all_public_streams: bool | None = None,
+ source_profile: UserProfile | None = None,
+ force_id: int | None = None,
+ force_date_joined: datetime | None = None,
create_personal_recipient: bool = True,
- enable_marketing_emails: Optional[bool] = None,
- email_address_visibility: Optional[int] = None,
+ enable_marketing_emails: bool | None = None,
+ email_address_visibility: int | None = None,
) -> UserProfile:
realm_user_default = RealmUserDefault.objects.get(realm=realm)
if bot_type is None:
diff --git a/zerver/lib/data_types.py b/zerver/lib/data_types.py
index afd86742b08..7f9f8ea26b8 100644
--- a/zerver/lib/data_types.py
+++ b/zerver/lib/data_types.py
@@ -11,7 +11,7 @@ easily with the native Python type system.
from contextlib import suppress
from dataclasses import dataclass
-from typing import Any, Callable, Optional, Sequence
+from typing import Any, Callable, Sequence
from django.core.exceptions import ValidationError
from django.core.validators import URLValidator
@@ -111,7 +111,7 @@ class NumberType:
"""A Union[float, int]; needed to align with the `number` type in
OpenAPI, because isinstance(4, float) == False"""
- def check_data(self, var_name: str, val: Optional[Any]) -> None:
+ def check_data(self, var_name: str, val: Any | None) -> None:
if isinstance(val, (int, float)):
return
raise AssertionError(f"{var_name} is not a number")
@@ -123,7 +123,7 @@ class NumberType:
class ListType:
"""List with every object having the declared sub_type."""
- def __init__(self, sub_type: Any, length: Optional[int] = None) -> None:
+ def __init__(self, sub_type: Any, length: int | None = None) -> None:
self.sub_type = sub_type
self.length = length
@@ -165,7 +165,7 @@ class StringDictType:
class OptionalType:
sub_type: Any
- def check_data(self, var_name: str, val: Optional[Any]) -> None:
+ def check_data(self, var_name: str, val: Any | None) -> None:
if val is None:
return
check_data(self.sub_type, var_name, val)
diff --git a/zerver/lib/db.py b/zerver/lib/db.py
index 9f193e4806f..bfea3b4b61e 100644
--- a/zerver/lib/db.py
+++ b/zerver/lib/db.py
@@ -1,13 +1,13 @@
import time
-from typing import Any, Callable, Iterable, Mapping, Sequence, TypeVar, Union
+from typing import Any, Callable, Iterable, Mapping, Sequence, TypeVar
from psycopg2.extensions import connection, cursor
from psycopg2.sql import Composable
from typing_extensions import TypeAlias, override
CursorObj = TypeVar("CursorObj", bound=cursor)
-Query: TypeAlias = Union[str, bytes, Composable]
-Params: TypeAlias = Union[Sequence[object], Mapping[str, object], None]
+Query: TypeAlias = str | bytes | Composable
+Params: TypeAlias = Sequence[object] | Mapping[str, object] | None
ParamsT = TypeVar("ParamsT")
diff --git a/zerver/lib/debug.py b/zerver/lib/debug.py
index 367f42c3edb..1ff1200ea11 100644
--- a/zerver/lib/debug.py
+++ b/zerver/lib/debug.py
@@ -8,7 +8,6 @@ import threading
import traceback
import tracemalloc
from types import FrameType
-from typing import Optional
from django.conf import settings
from django.utils.timezone import now as timezone_now
@@ -21,7 +20,7 @@ logger = logging.getLogger("zulip.debug")
# (that link also points to code for an interactive remote debugger
# setup, which we might want if we move Tornado to run in a daemon
# rather than via screen).
-def interactive_debug(sig: int, frame: Optional[FrameType]) -> None:
+def interactive_debug(sig: int, frame: FrameType | None) -> None:
"""Interrupt running process, and provide a python prompt for
interactive debugging."""
d = {"_frame": frame} # Allow access to frame object.
@@ -74,7 +73,7 @@ def tracemalloc_listen_sock(sock: socket.socket) -> None:
tracemalloc_dump()
-listener_pid: Optional[int] = None
+listener_pid: int | None = None
def tracemalloc_listen() -> None:
diff --git a/zerver/lib/dev_ldap_directory.py b/zerver/lib/dev_ldap_directory.py
index f4e24f5e052..b0d0148f47b 100644
--- a/zerver/lib/dev_ldap_directory.py
+++ b/zerver/lib/dev_ldap_directory.py
@@ -2,7 +2,7 @@ import glob
import logging
import os
from email.headerregistry import Address
-from typing import Any, Optional
+from typing import Any
from django.conf import settings
@@ -60,7 +60,7 @@ def generate_dev_ldap_dir(mode: str, num_users: int = 8) -> dict[str, dict[str,
def init_fakeldap(
- directory: Optional[dict[str, dict[str, list[str]]]] = None,
+ directory: dict[str, dict[str, list[str]]] | None = None,
) -> None: # nocoverage
# We only use this in development. Importing mock inside
# this function is an import time optimization, which
diff --git a/zerver/lib/digest.py b/zerver/lib/digest.py
index 86cd15c8f0d..bf31dfa7622 100644
--- a/zerver/lib/digest.py
+++ b/zerver/lib/digest.py
@@ -3,7 +3,7 @@ import heapq
import logging
from collections import defaultdict
from datetime import datetime, timedelta, timezone
-from typing import Any, Collection, Iterator, Optional
+from typing import Any, Collection, Iterator
from django.conf import settings
from django.db import transaction
@@ -151,8 +151,8 @@ def _enqueue_emails_for_realm(realm: Realm, cutoff: datetime) -> None:
)
-last_realm_id: Optional[int] = None
-last_cutoff: Optional[float] = None
+last_realm_id: int | None = None
+last_cutoff: float | None = None
def maybe_clear_recent_topics_cache(realm_id: int, cutoff: float) -> None:
diff --git a/zerver/lib/display_recipient.py b/zerver/lib/display_recipient.py
index 2316bfb7379..a9d4d1b78b8 100644
--- a/zerver/lib/display_recipient.py
+++ b/zerver/lib/display_recipient.py
@@ -29,14 +29,14 @@ class TinyStreamResult(TypedDict):
def get_display_recipient_cache_key(
- recipient_id: int, recipient_type: int, recipient_type_id: Optional[int]
+ recipient_id: int, recipient_type: int, recipient_type_id: int | None
) -> str:
return display_recipient_cache_key(recipient_id)
@cache_with_key(get_display_recipient_cache_key, timeout=3600 * 24 * 7)
def get_display_recipient_remote_cache(
- recipient_id: int, recipient_type: int, recipient_type_id: Optional[int]
+ recipient_id: int, recipient_type: int, recipient_type_id: int | None
) -> list[UserDisplayRecipient]:
"""
This returns an appropriate object describing the recipient of a
@@ -208,7 +208,7 @@ def bulk_fetch_display_recipients(
@return_same_value_during_entire_request
def get_display_recipient_by_id(
- recipient_id: int, recipient_type: int, recipient_type_id: Optional[int]
+ recipient_id: int, recipient_type: int, recipient_type_id: int | None
) -> list[UserDisplayRecipient]:
"""
returns: an object describing the recipient (using a cache).
diff --git a/zerver/lib/domains.py b/zerver/lib/domains.py
index 6ec4cd57a9c..4980bcf6b87 100644
--- a/zerver/lib/domains.py
+++ b/zerver/lib/domains.py
@@ -1,11 +1,10 @@
import re
-from typing import Optional
from django.core.exceptions import ValidationError
from django.utils.translation import gettext as _
-def validate_domain(domain: Optional[str]) -> None:
+def validate_domain(domain: str | None) -> None:
if domain is None or len(domain) == 0:
raise ValidationError(_("Domain can't be empty."))
if "." not in domain:
diff --git a/zerver/lib/drafts.py b/zerver/lib/drafts.py
index 81e4745d07e..e97417c99a4 100644
--- a/zerver/lib/drafts.py
+++ b/zerver/lib/drafts.py
@@ -1,6 +1,6 @@
import time
from functools import wraps
-from typing import Any, Callable, Literal, Union
+from typing import Any, Callable, Literal
from django.core.exceptions import ValidationError
from django.http import HttpRequest, HttpResponse
@@ -28,7 +28,7 @@ class DraftData(BaseModel):
to: list[int]
topic: str
content: Annotated[str, RequiredStringConstraint()]
- timestamp: Union[int, float, None] = None
+ timestamp: int | float | None = None
def further_validated_draft_dict(
diff --git a/zerver/lib/email_mirror.py b/zerver/lib/email_mirror.py
index b1f228e84d8..fd52ed7c72f 100644
--- a/zerver/lib/email_mirror.py
+++ b/zerver/lib/email_mirror.py
@@ -3,7 +3,7 @@ import re
import secrets
from email.headerregistry import Address, AddressHeader
from email.message import EmailMessage
-from typing import Match, Optional
+from typing import Match
from django.conf import settings
from django.utils.translation import gettext as _
@@ -64,7 +64,7 @@ def redact_email_address(error_message: str) -> str:
return re.sub(rf"\b(\S*?)(@{re.escape(domain)})", redact, error_message)
-def log_error(email_message: EmailMessage, error_message: str, to: Optional[str]) -> None:
+def log_error(email_message: EmailMessage, error_message: str, to: str | None) -> None:
recipient = to or "No recipient found"
error_message = "Sender: {}\nTo: {}\n{}".format(
email_message.get("From"), recipient, error_message
@@ -90,7 +90,7 @@ def is_missed_message_address(address: str) -> bool:
return is_mm_32_format(msg_string)
-def is_mm_32_format(msg_string: Optional[str]) -> bool:
+def is_mm_32_format(msg_string: str | None) -> bool:
"""
Missed message strings are formatted with a little "mm" prefix
followed by a randomly generated 32-character string.
@@ -223,7 +223,7 @@ def send_mm_reply_to_stream(
)
-def get_message_part_by_type(message: EmailMessage, content_type: str) -> Optional[str]:
+def get_message_part_by_type(message: EmailMessage, content_type: str) -> str | None:
charsets = message.get_charsets()
for idx, part in enumerate(message.walk()):
@@ -276,7 +276,7 @@ def extract_body(
talon_initialized = False
-def extract_plaintext_body(message: EmailMessage, include_quotes: bool = False) -> Optional[str]:
+def extract_plaintext_body(message: EmailMessage, include_quotes: bool = False) -> str | None:
import talon_core
global talon_initialized
@@ -294,7 +294,7 @@ def extract_plaintext_body(message: EmailMessage, include_quotes: bool = False)
return None
-def extract_html_body(message: EmailMessage, include_quotes: bool = False) -> Optional[str]:
+def extract_html_body(message: EmailMessage, include_quotes: bool = False) -> str | None:
import talon_core
global talon_initialized
@@ -474,8 +474,8 @@ def process_missed_message(to: str, message: EmailMessage) -> None:
)
-def process_message(message: EmailMessage, rcpt_to: Optional[str] = None) -> None:
- to: Optional[str] = None
+def process_message(message: EmailMessage, rcpt_to: str | None = None) -> None:
+ to: str | None = None
try:
if rcpt_to is not None:
diff --git a/zerver/lib/email_notifications.py b/zerver/lib/email_notifications.py
index e947169fd8a..226ba575e16 100644
--- a/zerver/lib/email_notifications.py
+++ b/zerver/lib/email_notifications.py
@@ -9,7 +9,7 @@ from collections import defaultdict
from dataclasses import dataclass
from datetime import timedelta
from email.headerregistry import Address
-from typing import Any, Optional, Union
+from typing import Any
import lxml.html
import zoneinfo
@@ -157,7 +157,7 @@ def fix_spoilers_in_text(content: str, language: str) -> str:
m = FENCE_RE.match(line)
if m:
fence = m.group("fence")
- lang: Optional[str] = m.group("lang")
+ lang: str | None = m.group("lang")
if lang == "spoiler":
open_fence = fence
output.append(line)
@@ -186,7 +186,7 @@ def add_quote_prefix_in_text(content: str) -> str:
def build_message_list(
user: UserProfile,
messages: list[Message],
- stream_id_map: Optional[dict[int, Stream]] = None, # only needs id, name
+ stream_id_map: dict[int, Stream] | None = None, # only needs id, name
) -> list[dict[str, Any]]:
"""
Builds the message list object for the message notification email template.
@@ -222,7 +222,7 @@ def build_message_list(
message_soup.insert(0, sender_name_soup)
return message_plain, str(message_soup)
- def build_message_payload(message: Message, sender: Optional[str] = None) -> dict[str, str]:
+ def build_message_payload(message: Message, sender: str | None = None) -> dict[str, str]:
plain = message.content
plain = fix_plaintext_image_urls(plain)
# There's a small chance of colliding with non-Zulip URLs containing
@@ -592,7 +592,7 @@ def do_send_missedmessage_events_reply_in_zulip(
@dataclass
class MissedMessageData:
trigger: str
- mentioned_user_group_id: Optional[int] = None
+ mentioned_user_group_id: int | None = None
def handle_missedmessage_emails(
@@ -629,7 +629,7 @@ def handle_missedmessage_emails(
# We bucket messages by tuples that identify similar messages.
# For streams it's recipient_id and topic.
# For direct messages it's recipient id and sender.
- messages_by_bucket: dict[tuple[int, Union[int, str]], list[Message]] = defaultdict(list)
+ messages_by_bucket: dict[tuple[int, int | str], list[Message]] = defaultdict(list)
for msg in messages:
if msg.recipient.type == Recipient.PERSONAL:
# For direct messages group using (recipient, sender).
@@ -649,7 +649,7 @@ def handle_missedmessage_emails(
msg_list.extend(filtered_context_messages)
# Sort emails by least recently-active discussion.
- bucket_tups: list[tuple[tuple[int, Union[int, str]], int]] = []
+ bucket_tups: list[tuple[tuple[int, int | str], int]] = []
for bucket_tup, msg_list in messages_by_bucket.items():
max_message_id = max(msg_list, key=lambda msg: msg.id).id
bucket_tups.append((bucket_tup, max_message_id))
@@ -761,7 +761,7 @@ def get_org_type_zulip_guide(realm: Realm) -> tuple[Any, str]:
return (None, "")
-def welcome_sender_information() -> tuple[Optional[str], str]:
+def welcome_sender_information() -> tuple[str | None, str]:
if settings.WELCOME_EMAIL_SENDER is not None:
from_name = settings.WELCOME_EMAIL_SENDER["name"]
from_address = settings.WELCOME_EMAIL_SENDER["email"]
diff --git a/zerver/lib/email_validation.py b/zerver/lib/email_validation.py
index 9eb347117cf..88ad3392428 100644
--- a/zerver/lib/email_validation.py
+++ b/zerver/lib/email_validation.py
@@ -1,6 +1,6 @@
from email.errors import HeaderParseError
from email.headerregistry import Address
-from typing import Callable, Optional
+from typing import Callable
from django.core import validators
from django.core.exceptions import ValidationError
@@ -97,7 +97,7 @@ def email_allowed_for_realm(email: str, realm: Realm) -> None:
def validate_email_is_valid(
email: str,
validate_email_allowed_in_realm: Callable[[str], None],
-) -> Optional[str]:
+) -> str | None:
try:
validators.validate_email(email)
except ValidationError:
diff --git a/zerver/lib/event_schema.py b/zerver/lib/event_schema.py
index e8eb161b840..328c51fe9cb 100644
--- a/zerver/lib/event_schema.py
+++ b/zerver/lib/event_schema.py
@@ -27,7 +27,7 @@
# See check_delete_message and check_presence for examples of this
# paradigm.
-from typing import Sequence, Union
+from typing import Sequence
from zerver.lib.data_types import (
DictType,
@@ -1636,7 +1636,7 @@ _check_update_global_notifications = make_checker(update_global_notifications_ev
def check_update_global_notifications(
var_name: str,
event: dict[str, object],
- desired_val: Union[bool, int, str],
+ desired_val: bool | int | str,
) -> None:
"""
See UserProfile.notification_settings_legacy for
diff --git a/zerver/lib/events.py b/zerver/lib/events.py
index d92fa130f56..5f837917f75 100644
--- a/zerver/lib/events.py
+++ b/zerver/lib/events.py
@@ -3,7 +3,7 @@
import copy
import logging
import time
-from typing import Any, Callable, Collection, Iterable, Mapping, Optional, Sequence
+from typing import Any, Callable, Collection, Iterable, Mapping, Sequence
from django.conf import settings
from django.utils.translation import gettext as _
@@ -122,19 +122,19 @@ def always_want(msg_type: str) -> bool:
def fetch_initial_state_data(
- user_profile: Optional[UserProfile],
+ user_profile: UserProfile | None,
*,
realm: Realm,
- event_types: Optional[Iterable[str]] = None,
- queue_id: Optional[str] = "",
+ event_types: Iterable[str] | None = None,
+ queue_id: str | None = "",
client_gravatar: bool = False,
user_avatar_url_field_optional: bool = False,
user_settings_object: bool = False,
slim_presence: bool = False,
- presence_last_update_id_fetched_by_client: Optional[int] = None,
+ presence_last_update_id_fetched_by_client: int | None = None,
include_subscribers: bool = True,
include_streams: bool = True,
- spectator_requested_language: Optional[str] = None,
+ spectator_requested_language: str | None = None,
pronouns_field_type_supported: bool = True,
linkifier_url_template: bool = False,
user_list_incomplete: bool = False,
@@ -758,7 +758,7 @@ def apply_events(
*,
state: dict[str, Any],
events: Iterable[dict[str, Any]],
- fetch_event_types: Optional[Collection[str]],
+ fetch_event_types: Collection[str] | None,
client_gravatar: bool,
slim_presence: bool,
include_subscribers: bool,
@@ -1628,22 +1628,22 @@ def apply_event(
def do_events_register(
- user_profile: Optional[UserProfile],
+ user_profile: UserProfile | None,
realm: Realm,
user_client: Client,
apply_markdown: bool = True,
client_gravatar: bool = False,
slim_presence: bool = False,
- presence_last_update_id_fetched_by_client: Optional[int] = None,
- event_types: Optional[Sequence[str]] = None,
+ presence_last_update_id_fetched_by_client: int | None = None,
+ event_types: Sequence[str] | None = None,
queue_lifespan_secs: int = 0,
all_public_streams: bool = False,
include_subscribers: bool = True,
include_streams: bool = True,
client_capabilities: Mapping[str, bool] = {},
narrow: Collection[NarrowTerm] = [],
- fetch_event_types: Optional[Collection[str]] = None,
- spectator_requested_language: Optional[str] = None,
+ fetch_event_types: Collection[str] | None = None,
+ spectator_requested_language: str | None = None,
pronouns_field_type_supported: bool = True,
) -> dict[str, Any]:
# Technically we don't need to check this here because
@@ -1662,7 +1662,7 @@ def do_events_register(
user_list_incomplete = client_capabilities.get("user_list_incomplete", False)
if fetch_event_types is not None:
- event_types_set: Optional[set[str]] = set(fetch_event_types)
+ event_types_set: set[str] | None = set(fetch_event_types)
elif event_types is not None:
event_types_set = set(event_types)
else:
@@ -1771,7 +1771,7 @@ def do_events_register(
def post_process_state(
- user_profile: Optional[UserProfile], ret: dict[str, Any], notification_settings_null: bool
+ user_profile: UserProfile | None, ret: dict[str, Any], notification_settings_null: bool
) -> None:
"""
NOTE:
diff --git a/zerver/lib/exceptions.py b/zerver/lib/exceptions.py
index 04bd3f8a8cc..a457aac22bd 100644
--- a/zerver/lib/exceptions.py
+++ b/zerver/lib/exceptions.py
@@ -1,5 +1,5 @@
from enum import Enum, auto
-from typing import Any, Optional, Union
+from typing import Any
from django.core.exceptions import ValidationError
from django.utils.translation import gettext as _
@@ -101,7 +101,7 @@ class JsonableError(Exception):
# like 403 or 404.
http_status_code: int = 400
- def __init__(self, msg: Union[str, StrPromise]) -> None:
+ def __init__(self, msg: str | StrPromise) -> None:
# `_msg` is an implementation detail of `JsonableError` itself.
self._msg = msg
@@ -147,7 +147,7 @@ class UnauthorizedError(JsonableError):
code: ErrorCode = ErrorCode.UNAUTHORIZED
http_status_code: int = 401
- def __init__(self, msg: Optional[str] = None, www_authenticate: Optional[str] = None) -> None:
+ def __init__(self, msg: str | None = None, www_authenticate: str | None = None) -> None:
if msg is None:
msg = _("Not logged in: API authentication or user session required")
super().__init__(msg)
@@ -235,7 +235,7 @@ class RateLimitedError(JsonableError):
code = ErrorCode.RATE_LIMIT_HIT
http_status_code = 429
- def __init__(self, secs_to_freedom: Optional[float] = None) -> None:
+ def __init__(self, secs_to_freedom: float | None = None) -> None:
self.secs_to_freedom = secs_to_freedom
@staticmethod
@@ -420,7 +420,7 @@ class UnsupportedWebhookEventTypeError(WebhookError):
http_status_code = 200
data_fields = ["webhook_name", "event_type"]
- def __init__(self, event_type: Optional[str]) -> None:
+ def __init__(self, event_type: str | None) -> None:
super().__init__()
self.event_type = event_type
diff --git a/zerver/lib/export.py b/zerver/lib/export.py
index c5562041d43..dd064e61250 100644
--- a/zerver/lib/export.py
+++ b/zerver/lib/export.py
@@ -409,7 +409,7 @@ def write_records_json_file(output_dir: str, records: list[dict[str, Any]]) -> N
logging.info("Finished writing %s", output_file)
-def make_raw(query: Any, exclude: Optional[list[Field]] = None) -> list[Record]:
+def make_raw(query: Any, exclude: list[Field] | None = None) -> list[Record]:
"""
Takes a Django query and returns a JSONable list
of dictionaries corresponding to the database rows.
@@ -463,20 +463,20 @@ class Config:
def __init__(
self,
- table: Optional[str] = None,
- model: Optional[Any] = None,
+ table: str | None = None,
+ model: Any | None = None,
normal_parent: Optional["Config"] = None,
virtual_parent: Optional["Config"] = None,
- filter_args: Optional[FilterArgs] = None,
- custom_fetch: Optional[CustomFetch] = None,
- custom_tables: Optional[list[TableName]] = None,
- concat_and_destroy: Optional[list[TableName]] = None,
- id_source: Optional[IdSource] = None,
- source_filter: Optional[SourceFilter] = None,
- include_rows: Optional[Field] = None,
+ filter_args: FilterArgs | None = None,
+ custom_fetch: CustomFetch | None = None,
+ custom_tables: list[TableName] | None = None,
+ concat_and_destroy: list[TableName] | None = None,
+ id_source: IdSource | None = None,
+ source_filter: SourceFilter | None = None,
+ include_rows: Field | None = None,
use_all: bool = False,
is_seeded: bool = False,
- exclude: Optional[list[Field]] = None,
+ exclude: list[Field] | None = None,
) -> None:
assert table or custom_tables
self.table = table
@@ -510,7 +510,7 @@ class Config:
)
if normal_parent is not None:
- self.parent: Optional[Config] = normal_parent
+ self.parent: Config | None = normal_parent
else:
self.parent = None
@@ -557,8 +557,8 @@ class Config:
def export_from_config(
response: TableData,
config: Config,
- seed_object: Optional[Any] = None,
- context: Optional[Context] = None,
+ seed_object: Any | None = None,
+ context: Context | None = None,
) -> None:
table = config.table
parent = config.parent
@@ -1202,7 +1202,7 @@ def fetch_usermessages(
message_ids: set[int],
user_profile_ids: set[int],
message_filename: Path,
- consent_message_id: Optional[int] = None,
+ consent_message_id: int | None = None,
) -> list[Record]:
# UserMessage export security rule: You can export UserMessages
# for the messages you exported for the users in your realm.
@@ -1225,7 +1225,7 @@ def fetch_usermessages(
def export_usermessages_batch(
- input_path: Path, output_path: Path, consent_message_id: Optional[int] = None
+ input_path: Path, output_path: Path, consent_message_id: int | None = None
) -> None:
"""As part of the system for doing parallel exports, this runs on one
batch of Message objects and adds the corresponding UserMessage
@@ -1258,9 +1258,9 @@ def export_partial_message_files(
realm: Realm,
response: TableData,
chunk_size: int = MESSAGE_BATCH_CHUNK_SIZE,
- output_dir: Optional[Path] = None,
+ output_dir: Path | None = None,
public_only: bool = False,
- consent_message_id: Optional[int] = None,
+ consent_message_id: int | None = None,
) -> set[int]:
if output_dir is None:
output_dir = tempfile.mkdtemp(prefix="zulip-export")
@@ -1462,8 +1462,8 @@ def write_message_partials(
def export_uploads_and_avatars(
realm: Realm,
*,
- attachments: Optional[list[Attachment]] = None,
- user: Optional[UserProfile],
+ attachments: list[Attachment] | None = None,
+ user: UserProfile | None,
output_dir: Path,
) -> None:
uploads_output_dir = os.path.join(output_dir, "uploads")
@@ -1667,7 +1667,7 @@ def export_files_from_s3(
object_prefix: str,
output_dir: Path,
user_ids: set[int],
- valid_hashes: Optional[set[str]],
+ valid_hashes: set[str] | None,
) -> None:
processing_uploads = flavor == "upload"
processing_emoji = flavor == "emoji"
@@ -1677,7 +1677,7 @@ def export_files_from_s3(
logging.info("Downloading %s files from %s", flavor, bucket_name)
- email_gateway_bot: Optional[UserProfile] = None
+ email_gateway_bot: UserProfile | None = None
if handle_system_bots and settings.EMAIL_GATEWAY_BOT is not None:
internal_realm = get_realm(settings.SYSTEM_BOT_REALM)
@@ -1914,7 +1914,7 @@ def do_write_stats_file_for_realm_export(output_dir: Path) -> None:
def get_exportable_scheduled_message_ids(
- realm: Realm, public_only: bool = False, consent_message_id: Optional[int] = None
+ realm: Realm, public_only: bool = False, consent_message_id: int | None = None
) -> set[int]:
"""
Scheduled messages are private to the sender, so which ones we export depends on the
@@ -1939,10 +1939,10 @@ def do_export_realm(
realm: Realm,
output_dir: Path,
threads: int,
- exportable_user_ids: Optional[set[int]] = None,
+ exportable_user_ids: set[int] | None = None,
public_only: bool = False,
- consent_message_id: Optional[int] = None,
- export_as_active: Optional[bool] = None,
+ consent_message_id: int | None = None,
+ export_as_active: bool | None = None,
) -> str:
response: TableData = {}
@@ -2076,7 +2076,7 @@ def create_soft_link(source: Path, in_progress: bool = True) -> None:
def launch_user_message_subprocesses(
- threads: int, output_dir: Path, consent_message_id: Optional[int] = None
+ threads: int, output_dir: Path, consent_message_id: int | None = None
) -> None:
logging.info("Launching %d PARALLEL subprocesses to export UserMessage rows", threads)
pids = {}
@@ -2402,10 +2402,10 @@ def export_realm_wrapper(
threads: int,
upload: bool,
public_only: bool,
- percent_callback: Optional[Callable[[Any], None]] = None,
- consent_message_id: Optional[int] = None,
- export_as_active: Optional[bool] = None,
-) -> Optional[str]:
+ percent_callback: Callable[[Any], None] | None = None,
+ consent_message_id: int | None = None,
+ export_as_active: bool | None = None,
+) -> str | None:
tarball_path = do_export_realm(
realm=realm,
output_dir=output_dir,
diff --git a/zerver/lib/home.py b/zerver/lib/home.py
index 5e91f41ef9f..8d29e75fd30 100644
--- a/zerver/lib/home.py
+++ b/zerver/lib/home.py
@@ -1,7 +1,6 @@
import calendar
import time
from dataclasses import dataclass
-from typing import Optional
from django.conf import settings
from django.http import HttpRequest
@@ -39,7 +38,7 @@ class UserPermissionInfo:
show_webathena: bool
-def get_furthest_read_time(user_profile: Optional[UserProfile]) -> Optional[float]:
+def get_furthest_read_time(user_profile: UserProfile | None) -> float | None:
if user_profile is None:
return time.time()
@@ -50,7 +49,7 @@ def get_furthest_read_time(user_profile: Optional[UserProfile]) -> Optional[floa
return calendar.timegm(user_activity.last_visit.utctimetuple())
-def get_bot_types(user_profile: Optional[UserProfile]) -> list[dict[str, object]]:
+def get_bot_types(user_profile: UserProfile | None) -> list[dict[str, object]]:
bot_types: list[dict[str, object]] = []
if user_profile is None:
return bot_types
@@ -75,7 +74,7 @@ def promote_sponsoring_zulip_in_realm(realm: Realm) -> bool:
return realm.plan_type in [Realm.PLAN_TYPE_STANDARD_FREE, Realm.PLAN_TYPE_SELF_HOSTED]
-def get_billing_info(user_profile: Optional[UserProfile]) -> BillingInfo:
+def get_billing_info(user_profile: UserProfile | None) -> BillingInfo:
# See https://zulip.com/help/roles-and-permissions for clarity.
show_billing = False
show_plans = False
@@ -114,7 +113,7 @@ def get_billing_info(user_profile: Optional[UserProfile]) -> BillingInfo:
)
-def get_user_permission_info(user_profile: Optional[UserProfile]) -> UserPermissionInfo:
+def get_user_permission_info(user_profile: UserProfile | None) -> UserPermissionInfo:
if user_profile is not None:
return UserPermissionInfo(
color_scheme=user_profile.color_scheme,
@@ -135,12 +134,12 @@ def get_user_permission_info(user_profile: Optional[UserProfile]) -> UserPermiss
def build_page_params_for_home_page_load(
request: HttpRequest,
- user_profile: Optional[UserProfile],
+ user_profile: UserProfile | None,
realm: Realm,
insecure_desktop_app: bool,
narrow: list[NarrowTerm],
- narrow_stream: Optional[Stream],
- narrow_topic_name: Optional[str],
+ narrow_stream: Stream | None,
+ narrow_topic_name: str | None,
needs_tutorial: bool,
) -> tuple[int, dict[str, object]]:
"""
diff --git a/zerver/lib/html_diff.py b/zerver/lib/html_diff.py
index e60ad85409a..f3b518deb2a 100644
--- a/zerver/lib/html_diff.py
+++ b/zerver/lib/html_diff.py
@@ -1,10 +1,8 @@
-from typing import Optional
-
import lxml.html
from lxml.html.diff import htmldiff
-def highlight_html_differences(s1: str, s2: str, msg_id: Optional[int] = None) -> str:
+def highlight_html_differences(s1: str, s2: str, msg_id: int | None = None) -> str:
retval = htmldiff(s1, s2)
fragment = lxml.html.fragment_fromstring(retval, create_parent=True)
diff --git a/zerver/lib/html_to_text.py b/zerver/lib/html_to_text.py
index 8e328ccdb63..af5cd6e4560 100644
--- a/zerver/lib/html_to_text.py
+++ b/zerver/lib/html_to_text.py
@@ -1,4 +1,4 @@
-from typing import Mapping, Union
+from typing import Mapping
from bs4 import BeautifulSoup
from django.utils.html import escape
@@ -6,7 +6,7 @@ from django.utils.html import escape
from zerver.lib.cache import cache_with_key, open_graph_description_cache_key
-def html_to_text(content: Union[str, bytes], tags: Mapping[str, str] = {"p": " | "}) -> str:
+def html_to_text(content: str | bytes, tags: Mapping[str, str] = {"p": " | "}) -> str:
bs = BeautifulSoup(content, features="lxml")
# Skip any admonition (warning) blocks, since they're
# usually something about users needing to be an
diff --git a/zerver/lib/i18n.py b/zerver/lib/i18n.py
index 4c22ffca58f..abdb44d73c5 100644
--- a/zerver/lib/i18n.py
+++ b/zerver/lib/i18n.py
@@ -3,7 +3,7 @@
import logging
import os
from functools import lru_cache
-from typing import Any, Optional
+from typing import Any
import orjson
from django.conf import settings
@@ -52,7 +52,7 @@ def get_language_translation_data(language: str) -> dict[str, str]:
def get_and_set_request_language(
- request: HttpRequest, user_configured_language: str, testing_url_language: Optional[str] = None
+ request: HttpRequest, user_configured_language: str, testing_url_language: str | None = None
) -> str:
# We pick a language for the user as follows:
# * First priority is the language in the URL, for debugging.
@@ -71,7 +71,7 @@ def get_and_set_request_language(
return request_language
-def get_browser_language_code(request: HttpRequest) -> Optional[str]:
+def get_browser_language_code(request: HttpRequest) -> str | None:
accept_lang_header = request.headers.get("Accept-Language")
if accept_lang_header is None:
return None
@@ -85,7 +85,7 @@ def get_browser_language_code(request: HttpRequest) -> Optional[str]:
return None
-def get_default_language_for_new_user(realm: Realm, *, request: Optional[HttpRequest]) -> str:
+def get_default_language_for_new_user(realm: Realm, *, request: HttpRequest | None) -> str:
if request is None:
# Users created via the API or LDAP will not have a
# browser/request associated with them, and should just use
diff --git a/zerver/lib/import_realm.py b/zerver/lib/import_realm.py
index 3acb3425b1e..5882f4bc976 100644
--- a/zerver/lib/import_realm.py
+++ b/zerver/lib/import_realm.py
@@ -4,7 +4,7 @@ import os
import shutil
from concurrent.futures import ProcessPoolExecutor, as_completed
from datetime import datetime, timezone
-from typing import Any, Optional
+from typing import Any
import bmemcached
import orjson
@@ -734,7 +734,7 @@ def bulk_import_user_message_data(data: TableData, dump_file_id: int) -> None:
logging.info("Successfully imported %s from %s[%s].", model, table, dump_file_id)
-def bulk_import_model(data: TableData, model: Any, dump_file_id: Optional[str] = None) -> None:
+def bulk_import_model(data: TableData, model: Any, dump_file_id: str | None = None) -> None:
table = get_db_table(model)
# TODO, deprecate dump_file_id
model.objects.bulk_create(model(**item) for item in data[table])
@@ -824,7 +824,7 @@ def import_uploads(
realm: Realm,
import_dir: Path,
processes: int,
- default_user_profile_id: Optional[int] = None,
+ default_user_profile_id: int | None = None,
processing_avatars: bool = False,
processing_emojis: bool = False,
processing_realm_icons: bool = False,
@@ -1126,7 +1126,7 @@ def do_import_realm(import_dir: Path, subdomain: str, processes: int = 1) -> Rea
# We expect Zulip server exports to contain these system groups,
# this logic here is needed to handle the imports from other services.
- role_system_groups_dict: Optional[dict[int, NamedUserGroup]] = None
+ role_system_groups_dict: dict[int, NamedUserGroup] | None = None
if "zerver_usergroup" not in data:
role_system_groups_dict = create_system_user_groups_for_realm(realm)
diff --git a/zerver/lib/initial_password.py b/zerver/lib/initial_password.py
index 15449380d26..b734763e0c3 100644
--- a/zerver/lib/initial_password.py
+++ b/zerver/lib/initial_password.py
@@ -1,11 +1,10 @@
import base64
import hashlib
-from typing import Optional
from django.conf import settings
-def initial_password(email: str) -> Optional[str]:
+def initial_password(email: str) -> str | None:
"""Given an email address, returns the initial password for that account, as
created by populate_db."""
diff --git a/zerver/lib/integrations.py b/zerver/lib/integrations.py
index e06bda685cc..6dbabae1692 100644
--- a/zerver/lib/integrations.py
+++ b/zerver/lib/integrations.py
@@ -1,6 +1,6 @@
import os
from dataclasses import dataclass, field
-from typing import Any, Callable, Optional, Sequence
+from typing import Any, Callable, Sequence
from django.contrib.staticfiles.storage import staticfiles_storage
from django.urls import URLResolver, path
@@ -32,7 +32,7 @@ Over time, we expect this registry to grow additional convenience
features for writing and configuring integrations efficiently.
"""
-OptionValidator: TypeAlias = Callable[[str, str], Optional[str]]
+OptionValidator: TypeAlias = Callable[[str, str], str | None]
META_CATEGORY: dict[str, StrPromise] = {
"meta-integration": gettext_lazy("Integration frameworks"),
@@ -67,11 +67,11 @@ class Integration:
name: str,
client_name: str,
categories: list[str],
- logo: Optional[str] = None,
- secondary_line_text: Optional[str] = None,
- display_name: Optional[str] = None,
- doc: Optional[str] = None,
- stream_name: Optional[str] = None,
+ logo: str | None = None,
+ secondary_line_text: str | None = None,
+ display_name: str | None = None,
+ doc: str | None = None,
+ stream_name: str | None = None,
legacy: bool = False,
config_options: Sequence[tuple[str, str, OptionValidator]] = [],
) -> None:
@@ -112,7 +112,7 @@ class Integration:
def is_enabled(self) -> bool:
return True
- def get_logo_path(self) -> Optional[str]:
+ def get_logo_path(self) -> str | None:
logo_file_path_svg = self.DEFAULT_LOGO_STATIC_PATH_SVG.format(name=self.name)
logo_file_path_png = self.DEFAULT_LOGO_STATIC_PATH_PNG.format(name=self.name)
if os.path.isfile(static_path(logo_file_path_svg)):
@@ -122,14 +122,14 @@ class Integration:
return None
- def get_bot_avatar_path(self) -> Optional[str]:
+ def get_bot_avatar_path(self) -> str | None:
if self.logo_path is not None:
name = os.path.splitext(os.path.basename(self.logo_path))[0]
return self.DEFAULT_BOT_AVATAR_PATH.format(name=name)
return None
- def get_logo_url(self) -> Optional[str]:
+ def get_logo_url(self) -> str | None:
if self.logo_path is not None:
return staticfiles_storage.url(self.logo_path)
@@ -146,10 +146,10 @@ class BotIntegration(Integration):
self,
name: str,
categories: list[str],
- logo: Optional[str] = None,
- secondary_line_text: Optional[str] = None,
- display_name: Optional[str] = None,
- doc: Optional[str] = None,
+ logo: str | None = None,
+ secondary_line_text: str | None = None,
+ display_name: str | None = None,
+ doc: str | None = None,
) -> None:
super().__init__(
name,
@@ -187,17 +187,17 @@ class WebhookIntegration(Integration):
self,
name: str,
categories: list[str],
- client_name: Optional[str] = None,
- logo: Optional[str] = None,
- secondary_line_text: Optional[str] = None,
- function: Optional[str] = None,
- url: Optional[str] = None,
- display_name: Optional[str] = None,
- doc: Optional[str] = None,
- stream_name: Optional[str] = None,
+ client_name: str | None = None,
+ logo: str | None = None,
+ secondary_line_text: str | None = None,
+ function: str | None = None,
+ url: str | None = None,
+ display_name: str | None = None,
+ doc: str | None = None,
+ stream_name: str | None = None,
legacy: bool = False,
config_options: Sequence[tuple[str, str, OptionValidator]] = [],
- dir_name: Optional[str] = None,
+ dir_name: str | None = None,
) -> None:
if client_name is None:
client_name = self.DEFAULT_CLIENT_NAME.format(name=name.title())
@@ -253,8 +253,8 @@ def split_fixture_path(path: str) -> tuple[str, str]:
class BaseScreenshotConfig:
fixture_name: str
image_name: str = "001.png"
- image_dir: Optional[str] = None
- bot_name: Optional[str] = None
+ image_dir: str | None = None
+ bot_name: str | None = None
@dataclass
@@ -287,10 +287,10 @@ class HubotIntegration(Integration):
self,
name: str,
categories: list[str],
- display_name: Optional[str] = None,
- logo: Optional[str] = None,
- logo_alt: Optional[str] = None,
- git_url: Optional[str] = None,
+ display_name: str | None = None,
+ logo: str | None = None,
+ logo_alt: str | None = None,
+ git_url: str | None = None,
legacy: bool = False,
) -> None:
if logo_alt is None:
@@ -847,7 +847,7 @@ DOC_SCREENSHOT_CONFIG: dict[str, list[BaseScreenshotConfig]] = {
}
-def get_all_event_types_for_integration(integration: Integration) -> Optional[list[str]]:
+def get_all_event_types_for_integration(integration: Integration) -> list[str] | None:
integration = INTEGRATIONS[integration.name]
if isinstance(integration, WebhookIntegration):
if integration.name == "githubsponsors":
diff --git a/zerver/lib/invites.py b/zerver/lib/invites.py
index 95a9ff0e301..5d266ae9cdb 100644
--- a/zerver/lib/invites.py
+++ b/zerver/lib/invites.py
@@ -1,5 +1,3 @@
-from typing import Optional
-
from django.db.models import Q
from django.utils.timezone import now as timezone_now
@@ -10,7 +8,7 @@ from zerver.tornado.django_api import send_event_on_commit
def notify_invites_changed(
- realm: Realm, *, changed_invite_referrer: Optional[UserProfile] = None
+ realm: Realm, *, changed_invite_referrer: UserProfile | None = None
) -> None:
event = dict(type="invites_changed")
admin_ids = [user.id for user in realm.get_admin_users_and_bots()]
diff --git a/zerver/lib/logging_util.py b/zerver/lib/logging_util.py
index c839d16d244..da59387b3bb 100644
--- a/zerver/lib/logging_util.py
+++ b/zerver/lib/logging_util.py
@@ -6,7 +6,6 @@ import traceback
from contextlib import suppress
from datetime import datetime, timedelta, timezone
from logging import Logger
-from typing import Optional, Union
import orjson
from django.conf import settings
@@ -120,7 +119,7 @@ class RequireReallyDeployed(logging.Filter):
return settings.PRODUCTION
-def find_log_caller_module(record: logging.LogRecord) -> Optional[str]:
+def find_log_caller_module(record: logging.LogRecord) -> str | None:
"""Find the module name corresponding to where this record was logged.
Sadly `record.module` is just the innermost component of the full
@@ -224,7 +223,7 @@ class ZulipWebhookFormatter(ZulipFormatter):
@override
def format(self, record: logging.LogRecord) -> str:
- request: Optional[HttpRequest] = getattr(record, "request", None)
+ request: HttpRequest | None = getattr(record, "request", None)
if request is None:
record.user = None
record.client = None
@@ -235,7 +234,7 @@ class ZulipWebhookFormatter(ZulipFormatter):
return super().format(record)
if request.content_type == "application/json":
- payload: Union[str, bytes] = request.body
+ payload: str | bytes = request.body
else:
payload = request.POST["payload"]
diff --git a/zerver/lib/management.py b/zerver/lib/management.py
index 738ff378331..832c582cfc6 100644
--- a/zerver/lib/management.py
+++ b/zerver/lib/management.py
@@ -5,7 +5,7 @@ import sys
from argparse import ArgumentParser, BooleanOptionalAction, RawTextHelpFormatter, _ActionsContainer
from dataclasses import dataclass
from functools import reduce, wraps
-from typing import Any, Optional, Protocol
+from typing import Any, Protocol
from django.conf import settings
from django.core import validators
@@ -70,7 +70,7 @@ def abort_unless_locked(handle_func: HandleMethod) -> HandleMethod:
class CreateUserParameters:
email: str
full_name: str
- password: Optional[str]
+ password: str | None
class ZulipBaseCommand(BaseCommand):
@@ -97,7 +97,7 @@ class ZulipBaseCommand(BaseCommand):
super().execute(*args, **options)
def add_realm_args(
- self, parser: ArgumentParser, *, required: bool = False, help: Optional[str] = None
+ self, parser: ArgumentParser, *, required: bool = False, help: str | None = None
) -> None:
if help is None:
help = """The numeric or string ID (subdomain) of the Zulip organization to modify.
@@ -140,7 +140,7 @@ server via `ps -ef` or reading bash history. Prefer
parser.add_argument("-a", "--all-users", action="store_true", help=all_users_help)
- def get_realm(self, options: dict[str, Any]) -> Optional[Realm]:
+ def get_realm(self, options: dict[str, Any]) -> Realm | None:
val = options["realm_id"]
if val is None:
return None
@@ -160,8 +160,8 @@ server via `ps -ef` or reading bash history. Prefer
def get_users(
self,
options: dict[str, Any],
- realm: Optional[Realm],
- is_bot: Optional[bool] = None,
+ realm: Realm | None,
+ is_bot: bool | None = None,
include_deactivated: bool = False,
) -> QuerySet[UserProfile]:
if "all_users" in options:
@@ -205,7 +205,7 @@ server via `ps -ef` or reading bash history. Prefer
# Return the single query, for ease of composing.
return user_profiles
- def get_user(self, email: str, realm: Optional[Realm]) -> UserProfile:
+ def get_user(self, email: str, realm: Realm | None) -> UserProfile:
# If a realm is specified, try to find the user there, and
# throw an error if they don't exist.
if realm is not None:
@@ -258,7 +258,7 @@ server via `ps -ef` or reading bash history. Prefer
if options["password_file"] is not None:
with open(options["password_file"]) as f:
- password: Optional[str] = f.read().strip()
+ password: str | None = f.read().strip()
elif options["password"] is not None:
logging.warning(
"Passing password on the command line is insecure; prefer --password-file."
diff --git a/zerver/lib/markdown/__init__.py b/zerver/lib/markdown/__init__.py
index 20592c2b842..4708b629cb5 100644
--- a/zerver/lib/markdown/__init__.py
+++ b/zerver/lib/markdown/__init__.py
@@ -10,7 +10,7 @@ from collections import deque
from dataclasses import dataclass
from datetime import datetime, timezone
from functools import lru_cache
-from typing import Any, Callable, Generic, Match, Optional, Pattern, TypedDict, TypeVar, Union, cast
+from typing import Any, Callable, Generic, Match, Optional, Pattern, TypedDict, TypeVar, cast
from urllib.parse import parse_qs, quote, urlencode, urljoin, urlsplit, urlunsplit
from xml.etree.ElementTree import Element, SubElement
@@ -96,9 +96,9 @@ allowed_schemes = ("http", "https", "ftp", "file", *html_safelisted_schemes)
class LinkInfo(TypedDict):
parent: Element
- title: Optional[str]
- index: Optional[int]
- remove: Optional[Element]
+ title: str | None
+ index: int | None
+ remove: Element | None
@dataclass
@@ -118,7 +118,7 @@ class MessageRenderingResult:
class DbData:
mention_data: MentionData
realm_url: str
- realm_alert_words_automaton: Optional[ahocorasick.Automaton]
+ realm_alert_words_automaton: ahocorasick.Automaton | None
active_realm_emoji: dict[str, EmojiInfo]
sent_by_bot: bool
stream_names: dict[str, int]
@@ -130,7 +130,7 @@ class DbData:
version = 1
_T = TypeVar("_T")
-ElementStringNone: TypeAlias = Union[Element, Optional[str]]
+ElementStringNone: TypeAlias = Element | str | None
EMOJI_REGEX = r"(?P<syntax>:[\w\-\+]+:)"
@@ -253,7 +253,7 @@ def clear_state_for_testing() -> None:
markdown_logger = logging.getLogger()
-def rewrite_local_links_to_relative(db_data: Optional[DbData], link: str) -> str:
+def rewrite_local_links_to_relative(db_data: DbData | None, link: str) -> str:
"""If the link points to a local destination (e.g. #narrow/...),
generate a relative link that will open it in the current window.
"""
@@ -267,7 +267,7 @@ def rewrite_local_links_to_relative(db_data: Optional[DbData], link: str) -> str
def url_embed_preview_enabled(
- message: Optional[Message] = None, realm: Optional[Realm] = None, no_previews: bool = False
+ message: Message | None = None, realm: Realm | None = None, no_previews: bool = False
) -> bool:
if not settings.INLINE_URL_EMBED_PREVIEW:
return False
@@ -288,7 +288,7 @@ def url_embed_preview_enabled(
def image_preview_enabled(
- message: Optional[Message] = None, realm: Optional[Realm] = None, no_previews: bool = False
+ message: Message | None = None, realm: Realm | None = None, no_previews: bool = False
) -> bool:
if not settings.INLINE_IMAGE_PREVIEW:
return False
@@ -315,7 +315,7 @@ def list_of_tlds() -> list[str]:
def walk_tree(
- root: Element, processor: Callable[[Element], Optional[_T]], stop_after_first: bool = False
+ root: Element, processor: Callable[[Element], _T | None], stop_after_first: bool = False
) -> list[_T]:
results = []
queue = deque([root])
@@ -336,7 +336,7 @@ def walk_tree(
@dataclass
class ElementFamily:
- grandparent: Optional[Element]
+ grandparent: Element | None
parent: Element
child: Element
in_blockquote: bool
@@ -365,7 +365,7 @@ class ElementPair:
def walk_tree_with_family(
root: Element,
- processor: Callable[[Element], Optional[_T]],
+ processor: Callable[[Element], _T | None],
) -> list[ResultWithFamily[_T]]:
results = []
@@ -378,7 +378,7 @@ def walk_tree_with_family(
if result is not None:
if currElementPair.parent is not None:
grandparent_element = currElementPair.parent
- grandparent: Optional[Element] = grandparent_element.value
+ grandparent: Element | None = grandparent_element.value
else:
grandparent = None
family = ElementFamily(
@@ -398,7 +398,7 @@ def walk_tree_with_family(
return results
-def has_blockquote_ancestor(element_pair: Optional[ElementPair]) -> bool:
+def has_blockquote_ancestor(element_pair: ElementPair | None) -> bool:
if element_pair is None:
return False
elif element_pair.value.tag == "blockquote":
@@ -408,7 +408,7 @@ def has_blockquote_ancestor(element_pair: Optional[ElementPair]) -> bool:
@cache_with_key(lambda tweet_id: tweet_id, cache_name="database")
-def fetch_tweet_data(tweet_id: str) -> Optional[dict[str, Any]]:
+def fetch_tweet_data(tweet_id: str) -> dict[str, Any] | None:
# Twitter removed support for the v1 API that this integration
# used. Given that, there's no point wasting time trying to make
# network requests to Twitter. But we leave this function, because
@@ -423,8 +423,8 @@ class OpenGraphSession(OutgoingSession):
super().__init__(role="markdown", timeout=1)
-def fetch_open_graph_image(url: str) -> Optional[dict[str, Any]]:
- og: dict[str, Optional[str]] = {"image": None, "title": None, "desc": None}
+def fetch_open_graph_image(url: str) -> dict[str, Any] | None:
+ og: dict[str, str | None] = {"image": None, "title": None, "desc": None}
try:
with OpenGraphSession().get(
@@ -466,7 +466,7 @@ def fetch_open_graph_image(url: str) -> Optional[dict[str, Any]]:
return None if og["image"] is None else og
-def get_tweet_id(url: str) -> Optional[str]:
+def get_tweet_id(url: str) -> str | None:
parsed_url = urlsplit(url)
if not (parsed_url.netloc == "twitter.com" or parsed_url.netloc.endswith(".twitter.com")):
return None
@@ -555,7 +555,7 @@ class BacktickInlineProcessor(markdown.inlinepatterns.BacktickInlineProcessor):
@override
def handleMatch( # type: ignore[override] # https://github.com/python/mypy/issues/10197
self, m: Match[str], data: str
- ) -> tuple[Union[Element, str, None], Optional[int], Optional[int]]:
+ ) -> tuple[Element | str | None, int | None, int | None]:
# Let upstream's implementation do its job as it is, we'll
# just replace the text to not strip the group because it
# makes it impossible to put leading/trailing whitespace in
@@ -586,11 +586,11 @@ class InlineInterestingLinkProcessor(markdown.treeprocessors.Treeprocessor):
root: Element,
image_url: str,
link: str,
- title: Optional[str] = None,
- desc: Optional[str] = None,
+ title: str | None = None,
+ desc: str | None = None,
class_attr: str = "message_inline_image",
- data_id: Optional[str] = None,
- insertion_index: Optional[int] = None,
+ data_id: str | None = None,
+ insertion_index: int | None = None,
already_thumbnailed: bool = False,
) -> None:
desc = desc if desc is not None else ""
@@ -724,7 +724,7 @@ class InlineInterestingLinkProcessor(markdown.treeprocessors.Treeprocessor):
return any(parsed_url.path.lower().endswith(ext) for ext in IMAGE_EXTENSIONS)
- def corrected_image_source(self, url: str) -> Optional[str]:
+ def corrected_image_source(self, url: str) -> str | None:
# This function adjusts any URLs from linx.li and
# wikipedia.org to point to the actual image URL. It's
# structurally very similar to dropbox_image, and possibly
@@ -742,7 +742,7 @@ class InlineInterestingLinkProcessor(markdown.treeprocessors.Treeprocessor):
return "https://linx.li/s" + parsed_url.path
return None
- def dropbox_image(self, url: str) -> Optional[dict[str, Any]]:
+ def dropbox_image(self, url: str) -> dict[str, Any] | None:
# TODO: The returned Dict could possibly be a TypedDict in future.
parsed_url = urlsplit(url)
if parsed_url.netloc == "dropbox.com" or parsed_url.netloc.endswith(".dropbox.com"):
@@ -785,7 +785,7 @@ class InlineInterestingLinkProcessor(markdown.treeprocessors.Treeprocessor):
return image_info
return None
- def youtube_id(self, url: str) -> Optional[str]:
+ def youtube_id(self, url: str) -> str | None:
if not self.zmd.image_preview_enabled:
return None
@@ -813,19 +813,19 @@ class InlineInterestingLinkProcessor(markdown.treeprocessors.Treeprocessor):
return id
return None
- def youtube_title(self, extracted_data: UrlEmbedData) -> Optional[str]:
+ def youtube_title(self, extracted_data: UrlEmbedData) -> str | None:
if extracted_data.title is not None:
return f"YouTube - {extracted_data.title}"
return None
- def youtube_image(self, url: str) -> Optional[str]:
+ def youtube_image(self, url: str) -> str | None:
yt_id = self.youtube_id(url)
if yt_id is not None:
return f"https://i.ytimg.com/vi/{yt_id}/default.jpg"
return None
- def vimeo_id(self, url: str) -> Optional[str]:
+ def vimeo_id(self, url: str) -> str | None:
if not self.zmd.image_preview_enabled:
return None
# (http|https)?:\/\/(www\.)?vimeo.com\/(?:channels\/(?:\w+\/)?|groups\/([^\/]*)\/videos\/|)(\d+)(?:|\/\?)
@@ -841,7 +841,7 @@ class InlineInterestingLinkProcessor(markdown.treeprocessors.Treeprocessor):
return None
return match.group(5)
- def vimeo_title(self, extracted_data: UrlEmbedData) -> Optional[str]:
+ def vimeo_title(self, extracted_data: UrlEmbedData) -> str | None:
if extracted_data.title is not None:
return f"Vimeo - {extracted_data.title}"
return None
@@ -943,7 +943,7 @@ class InlineInterestingLinkProcessor(markdown.treeprocessors.Treeprocessor):
else:
current_node.tail = text
- db_data: Optional[DbData] = self.zmd.zulip_db_data
+ db_data: DbData | None = self.zmd.zulip_db_data
current_index = 0
for item in to_process:
# The text we want to link starts in already linked text skip it
@@ -965,7 +965,7 @@ class InlineInterestingLinkProcessor(markdown.treeprocessors.Treeprocessor):
set_text(text[current_index:])
return p
- def twitter_link(self, url: str) -> Optional[Element]:
+ def twitter_link(self, url: str) -> Element | None:
tweet_id = get_tweet_id(url)
if tweet_id is None:
@@ -1033,7 +1033,7 @@ class InlineInterestingLinkProcessor(markdown.treeprocessors.Treeprocessor):
markdown_logger.warning("Error building Twitter link", exc_info=True)
return None
- def get_url_data(self, e: Element) -> Optional[tuple[str, Optional[str]]]:
+ def get_url_data(self, e: Element) -> tuple[str, str | None] | None:
if e.tag == "a":
url = e.get("href")
assert url is not None
@@ -1043,7 +1043,7 @@ class InlineInterestingLinkProcessor(markdown.treeprocessors.Treeprocessor):
def get_inlining_information(
self,
root: Element,
- found_url: ResultWithFamily[tuple[str, Optional[str]]],
+ found_url: ResultWithFamily[tuple[str, str | None]],
) -> LinkInfo:
grandparent = found_url.family.grandparent
parent = found_url.family.parent
@@ -1092,7 +1092,7 @@ class InlineInterestingLinkProcessor(markdown.treeprocessors.Treeprocessor):
def handle_image_inlining(
self,
root: Element,
- found_url: ResultWithFamily[tuple[str, Optional[str]]],
+ found_url: ResultWithFamily[tuple[str, str | None]],
) -> None:
info = self.get_inlining_information(root, found_url)
(url, text) = found_url.result
@@ -1110,7 +1110,7 @@ class InlineInterestingLinkProcessor(markdown.treeprocessors.Treeprocessor):
def handle_tweet_inlining(
self,
root: Element,
- found_url: ResultWithFamily[tuple[str, Optional[str]]],
+ found_url: ResultWithFamily[tuple[str, str | None]],
twitter_data: Element,
) -> None:
info = self.get_inlining_information(root, found_url)
@@ -1127,7 +1127,7 @@ class InlineInterestingLinkProcessor(markdown.treeprocessors.Treeprocessor):
def handle_youtube_url_inlining(
self,
root: Element,
- found_url: ResultWithFamily[tuple[str, Optional[str]]],
+ found_url: ResultWithFamily[tuple[str, str | None]],
yt_image: str,
) -> None:
info = self.get_inlining_information(root, found_url)
@@ -1191,9 +1191,9 @@ class InlineInterestingLinkProcessor(markdown.treeprocessors.Treeprocessor):
self,
root: Element,
url: str,
- title: Optional[str],
+ title: str | None,
class_attr: str = "message_inline_image message_inline_video",
- insertion_index: Optional[int] = None,
+ insertion_index: int | None = None,
) -> None:
if insertion_index is not None:
div = Element("div")
@@ -1213,7 +1213,7 @@ class InlineInterestingLinkProcessor(markdown.treeprocessors.Treeprocessor):
video.set("preload", "metadata")
def handle_video_inlining(
- self, root: Element, found_url: ResultWithFamily[tuple[str, Optional[str]]]
+ self, root: Element, found_url: ResultWithFamily[tuple[str, str | None]]
) -> None:
info = self.get_inlining_information(root, found_url)
url = found_url.result[0]
@@ -1335,7 +1335,7 @@ class InlineInterestingLinkProcessor(markdown.treeprocessors.Treeprocessor):
# is enabled, but URL previews are a beta feature and YouTube
# previews are pretty stable.
- db_data: Optional[DbData] = self.zmd.zulip_db_data
+ db_data: DbData | None = self.zmd.zulip_db_data
if db_data and db_data.sent_by_bot:
continue
@@ -1382,7 +1382,7 @@ class CompiledInlineProcessor(markdown.inlinepatterns.InlineProcessor):
class Timestamp(markdown.inlinepatterns.Pattern):
@override
- def handleMatch(self, match: Match[str]) -> Optional[Element]:
+ def handleMatch(self, match: Match[str]) -> Element | None:
time_input_string = match.group("time")
try:
timestamp = dateutil.parser.parse(time_input_string, tzinfos=common_timezones)
@@ -1473,8 +1473,8 @@ class EmoticonTranslation(markdown.inlinepatterns.Pattern):
self.zmd = zmd
@override
- def handleMatch(self, match: Match[str]) -> Optional[Element]:
- db_data: Optional[DbData] = self.zmd.zulip_db_data
+ def handleMatch(self, match: Match[str]) -> Element | None:
+ db_data: DbData | None = self.zmd.zulip_db_data
if db_data is None or not db_data.translate_emoticons:
return None
@@ -1491,7 +1491,7 @@ class UnicodeEmoji(CompiledInlineProcessor):
@override
def handleMatch( # type: ignore[override] # https://github.com/python/mypy/issues/10197
self, match: Match[str], data: str
- ) -> tuple[Union[Element, str, None], Optional[int], Optional[int]]:
+ ) -> tuple[Element | str | None, int | None, int | None]:
orig_syntax = match.group("syntax")
# We want to avoid turning things like arrows (↔) and keycaps (numbers
@@ -1515,12 +1515,12 @@ class Emoji(markdown.inlinepatterns.Pattern):
self.zmd = zmd
@override
- def handleMatch(self, match: Match[str]) -> Optional[Union[str, Element]]:
+ def handleMatch(self, match: Match[str]) -> str | Element | None:
orig_syntax = match.group("syntax")
name = orig_syntax[1:-1]
active_realm_emoji: dict[str, EmojiInfo] = {}
- db_data: Optional[DbData] = self.zmd.zulip_db_data
+ db_data: DbData | None = self.zmd.zulip_db_data
if db_data is not None:
active_realm_emoji = db_data.active_realm_emoji
@@ -1544,7 +1544,7 @@ def content_has_emoji_syntax(content: str) -> bool:
class Tex(markdown.inlinepatterns.Pattern):
@override
- def handleMatch(self, match: Match[str]) -> Union[str, Element]:
+ def handleMatch(self, match: Match[str]) -> str | Element:
rendered = render_tex(match.group("body"), is_inline=True)
if rendered is not None:
return self.md.htmlStash.store(rendered)
@@ -1555,7 +1555,7 @@ class Tex(markdown.inlinepatterns.Pattern):
return span
-def sanitize_url(url: str) -> Optional[str]:
+def sanitize_url(url: str) -> str | None:
"""
Sanitize a URL against XSS attacks.
See the docstring on markdown.inlinepatterns.LinkPattern.sanitize_url.
@@ -1604,9 +1604,7 @@ def sanitize_url(url: str) -> Optional[str]:
return urlunsplit((scheme, netloc, path, query, fragment))
-def url_to_a(
- db_data: Optional[DbData], url: str, text: Optional[str] = None
-) -> Union[Element, str]:
+def url_to_a(db_data: DbData | None, url: str, text: str | None = None) -> Element | str:
a = Element("a")
href = sanitize_url(url)
@@ -1637,7 +1635,7 @@ class AutoLink(CompiledPattern):
@override
def handleMatch(self, match: Match[str]) -> ElementStringNone:
url = match.group("url")
- db_data: Optional[DbData] = self.zmd.zulip_db_data
+ db_data: DbData | None = self.zmd.zulip_db_data
return url_to_a(db_data, url)
@@ -1759,7 +1757,7 @@ class MarkdownListPreprocessor(markdown.preprocessors.Preprocessor):
m = FENCE_RE.match(lines[i])
if m:
fence_str = m.group("fence")
- lang: Optional[str] = m.group("lang")
+ lang: str | None = m.group("lang")
is_code = lang not in ("quote", "quoted")
matches_last_fence = (
fence_str == open_fences[-1].fence_str if open_fences else False
@@ -1839,8 +1837,8 @@ class LinkifierPattern(CompiledInlineProcessor):
@override
def handleMatch( # type: ignore[override] # https://github.com/python/mypy/issues/10197
self, m: Match[str], data: str
- ) -> tuple[Union[Element, str, None], Optional[int], Optional[int]]:
- db_data: Optional[DbData] = self.zmd.zulip_db_data
+ ) -> tuple[Element | str | None, int | None, int | None]:
+ db_data: DbData | None = self.zmd.zulip_db_data
url = url_to_a(
db_data,
self.prepared_url_template.expand(**m.groupdict()),
@@ -1860,10 +1858,10 @@ class UserMentionPattern(CompiledInlineProcessor):
@override
def handleMatch( # type: ignore[override] # https://github.com/python/mypy/issues/10197
self, m: Match[str], data: str
- ) -> tuple[Union[Element, str, None], Optional[int], Optional[int]]:
+ ) -> tuple[Element | str | None, int | None, int | None]:
name = m.group("match")
silent = m.group("silent") == "_"
- db_data: Optional[DbData] = self.zmd.zulip_db_data
+ db_data: DbData | None = self.zmd.zulip_db_data
if db_data is not None:
topic_wildcard = mention.user_mention_matches_topic_wildcard(name)
stream_wildcard = mention.user_mention_matches_stream_wildcard(name)
@@ -1926,10 +1924,10 @@ class UserGroupMentionPattern(CompiledInlineProcessor):
@override
def handleMatch( # type: ignore[override] # https://github.com/python/mypy/issues/10197
self, m: Match[str], data: str
- ) -> tuple[Union[Element, str, None], Optional[int], Optional[int]]:
+ ) -> tuple[Element | str | None, int | None, int | None]:
name = m.group("match")
silent = m.group("silent") == "_"
- db_data: Optional[DbData] = self.zmd.zulip_db_data
+ db_data: DbData | None = self.zmd.zulip_db_data
if db_data is not None:
user_group = db_data.mention_data.get_user_group(name)
@@ -1957,8 +1955,8 @@ class UserGroupMentionPattern(CompiledInlineProcessor):
class StreamPattern(CompiledInlineProcessor):
- def find_stream_id(self, name: str) -> Optional[int]:
- db_data: Optional[DbData] = self.zmd.zulip_db_data
+ def find_stream_id(self, name: str) -> int | None:
+ db_data: DbData | None = self.zmd.zulip_db_data
if db_data is None:
return None
stream_id = db_data.stream_names.get(name)
@@ -1967,7 +1965,7 @@ class StreamPattern(CompiledInlineProcessor):
@override
def handleMatch( # type: ignore[override] # https://github.com/python/mypy/issues/10197
self, m: Match[str], data: str
- ) -> tuple[Union[Element, str, None], Optional[int], Optional[int]]:
+ ) -> tuple[Element | str | None, int | None, int | None]:
name = m.group("stream_name")
stream_id = self.find_stream_id(name)
@@ -1989,8 +1987,8 @@ class StreamPattern(CompiledInlineProcessor):
class StreamTopicPattern(CompiledInlineProcessor):
- def find_stream_id(self, name: str) -> Optional[int]:
- db_data: Optional[DbData] = self.zmd.zulip_db_data
+ def find_stream_id(self, name: str) -> int | None:
+ db_data: DbData | None = self.zmd.zulip_db_data
if db_data is None:
return None
stream_id = db_data.stream_names.get(name)
@@ -1999,7 +1997,7 @@ class StreamTopicPattern(CompiledInlineProcessor):
@override
def handleMatch( # type: ignore[override] # https://github.com/python/mypy/issues/10197
self, m: Match[str], data: str
- ) -> tuple[Union[Element, str, None], Optional[int], Optional[int]]:
+ ) -> tuple[Element | str | None, int | None, int | None]:
stream_name = m.group("stream_name")
topic_name = m.group("topic_name")
@@ -2063,7 +2061,7 @@ class AlertWordNotificationProcessor(markdown.preprocessors.Preprocessor):
@override
def run(self, lines: list[str]) -> list[str]:
- db_data: Optional[DbData] = self.zmd.zulip_db_data
+ db_data: DbData | None = self.zmd.zulip_db_data
if db_data is not None:
# We check for alert words here, the set of which are
# dependent on which users may see this message.
@@ -2091,7 +2089,7 @@ class LinkInlineProcessor(markdown.inlinepatterns.LinkInlineProcessor):
super().__init__(pattern, zmd)
self.zmd = zmd
- def zulip_specific_link_changes(self, el: Element) -> Union[None, Element]:
+ def zulip_specific_link_changes(self, el: Element) -> None | Element:
href = el.get("href")
assert href is not None
@@ -2101,7 +2099,7 @@ class LinkInlineProcessor(markdown.inlinepatterns.LinkInlineProcessor):
return None # no-op; the link is not processed.
# Rewrite local links to be relative
- db_data: Optional[DbData] = self.zmd.zulip_db_data
+ db_data: DbData | None = self.zmd.zulip_db_data
href = rewrite_local_links_to_relative(db_data, href)
# Make changes to <a> tag attributes
@@ -2120,7 +2118,7 @@ class LinkInlineProcessor(markdown.inlinepatterns.LinkInlineProcessor):
@override
def handleMatch( # type: ignore[override] # https://github.com/python/mypy/issues/10197
self, m: Match[str], data: str
- ) -> tuple[Union[Element, str, None], Optional[int], Optional[int]]:
+ ) -> tuple[Element | str | None, int | None, int | None]:
ret = super().handleMatch(m, data)
if ret[0] is not None:
el, match_start, index = ret
@@ -2148,13 +2146,13 @@ ZEPHYR_MIRROR_MARKDOWN_KEY = -2
class ZulipMarkdown(markdown.Markdown):
- zulip_message: Optional[Message]
- zulip_realm: Optional[Realm]
- zulip_db_data: Optional[DbData]
+ zulip_message: Message | None
+ zulip_realm: Realm | None
+ zulip_db_data: DbData | None
zulip_rendering_result: MessageRenderingResult
image_preview_enabled: bool
url_embed_preview_enabled: bool
- url_embed_data: Optional[dict[str, Optional[UrlEmbedData]]]
+ url_embed_data: dict[str, UrlEmbedData | None] | None
def __init__(
self,
@@ -2412,7 +2410,7 @@ class TopicLinkMatch:
url: str
text: str
index: int
- precedence: Optional[int]
+ precedence: int | None
# Security note: We don't do any HTML escaping in this
@@ -2556,13 +2554,13 @@ def privacy_clean_markdown(content: str) -> str:
def do_convert(
content: str,
- realm_alert_words_automaton: Optional[ahocorasick.Automaton] = None,
- message: Optional[Message] = None,
- message_realm: Optional[Realm] = None,
+ realm_alert_words_automaton: ahocorasick.Automaton | None = None,
+ message: Message | None = None,
+ message_realm: Realm | None = None,
sent_by_bot: bool = False,
translate_emoticons: bool = False,
- url_embed_data: Optional[dict[str, Optional[UrlEmbedData]]] = None,
- mention_data: Optional[MentionData] = None,
+ url_embed_data: dict[str, UrlEmbedData | None] | None = None,
+ mention_data: MentionData | None = None,
email_gateway: bool = False,
no_previews: bool = False,
) -> MessageRenderingResult:
@@ -2717,13 +2715,13 @@ def markdown_stats_finish() -> None:
def markdown_convert(
content: str,
- realm_alert_words_automaton: Optional[ahocorasick.Automaton] = None,
- message: Optional[Message] = None,
- message_realm: Optional[Realm] = None,
+ realm_alert_words_automaton: ahocorasick.Automaton | None = None,
+ message: Message | None = None,
+ message_realm: Realm | None = None,
sent_by_bot: bool = False,
translate_emoticons: bool = False,
- url_embed_data: Optional[dict[str, Optional[UrlEmbedData]]] = None,
- mention_data: Optional[MentionData] = None,
+ url_embed_data: dict[str, UrlEmbedData | None] | None = None,
+ mention_data: MentionData | None = None,
email_gateway: bool = False,
no_previews: bool = False,
) -> MessageRenderingResult:
@@ -2747,10 +2745,10 @@ def markdown_convert(
def render_message_markdown(
message: Message,
content: str,
- realm: Optional[Realm] = None,
- realm_alert_words_automaton: Optional[ahocorasick.Automaton] = None,
- url_embed_data: Optional[dict[str, Optional[UrlEmbedData]]] = None,
- mention_data: Optional[MentionData] = None,
+ realm: Realm | None = None,
+ realm_alert_words_automaton: ahocorasick.Automaton | None = None,
+ url_embed_data: dict[str, UrlEmbedData | None] | None = None,
+ mention_data: MentionData | None = None,
email_gateway: bool = False,
) -> MessageRenderingResult:
"""
diff --git a/zerver/lib/markdown/api_return_values_table_generator.py b/zerver/lib/markdown/api_return_values_table_generator.py
index c8205317c1f..2d792c61ca1 100644
--- a/zerver/lib/markdown/api_return_values_table_generator.py
+++ b/zerver/lib/markdown/api_return_values_table_generator.py
@@ -3,7 +3,7 @@ import json
import re
from collections import OrderedDict
from dataclasses import dataclass
-from typing import Any, Mapping, Optional
+from typing import Any, Mapping
import markdown
from markdown.extensions import Extension
@@ -52,7 +52,7 @@ class EventData:
description: str
properties: dict[str, Any]
example: str
- op_type: Optional[str] = None
+ op_type: str | None = None
class MarkdownReturnValuesTableGenerator(Extension):
@@ -105,7 +105,7 @@ class APIReturnValuesTablePreprocessor(Preprocessor):
return lines
def render_desc(
- self, description: str, spacing: int, data_type: str, return_value: Optional[str] = None
+ self, description: str, spacing: int, data_type: str, return_value: str | None = None
) -> str:
description = description.replace("\n", "\n" + ((spacing + 4) * " "))
if return_value is None:
@@ -304,8 +304,8 @@ class APIReturnValuesTablePreprocessor(Preprocessor):
for event in events_dict["oneOf"]:
# The op property doesn't have a description, so it must be removed
# before any calls to self.render_table, which expects a description.
- op: Optional[dict[str, Any]] = event["properties"].pop("op", None)
- op_type: Optional[str] = None
+ op: dict[str, Any] | None = event["properties"].pop("op", None)
+ op_type: str | None = None
if op is not None:
op_type = op["enum"][0]
event_data = EventData(
diff --git a/zerver/lib/markdown/fenced_code.py b/zerver/lib/markdown/fenced_code.py
index 1802185a976..c82200f3279 100644
--- a/zerver/lib/markdown/fenced_code.py
+++ b/zerver/lib/markdown/fenced_code.py
@@ -77,7 +77,7 @@ Dependencies:
"""
import re
-from typing import Any, Callable, Iterable, Mapping, MutableSequence, Optional, Sequence
+from typing import Any, Callable, Iterable, Mapping, MutableSequence, Sequence
import lxml.html
from django.utils.html import escape
@@ -141,7 +141,7 @@ Missing required -X argument in curl command:
raise MarkdownRenderingError(error_msg.format(command=line.strip()))
-CODE_VALIDATORS: dict[Optional[str], Callable[[list[str]], None]] = {
+CODE_VALIDATORS: dict[str | None, Callable[[list[str]], None]] = {
"curl": validate_curl_content,
}
@@ -175,7 +175,7 @@ class ZulipBaseHandler:
self,
processor: "FencedBlockPreprocessor",
output: MutableSequence[str],
- fence: Optional[str] = None,
+ fence: str | None = None,
process_contents: bool = False,
) -> None:
self.processor = processor
@@ -220,10 +220,10 @@ def generic_handler(
processor: "FencedBlockPreprocessor",
output: MutableSequence[str],
fence: str,
- lang: Optional[str],
- header: Optional[str],
+ lang: str | None,
+ header: str | None,
run_content_validators: bool = False,
- default_language: Optional[str] = None,
+ default_language: str | None = None,
) -> ZulipBaseHandler:
if lang is not None:
lang = lang.lower()
@@ -242,13 +242,13 @@ def check_for_new_fence(
output: MutableSequence[str],
line: str,
run_content_validators: bool = False,
- default_language: Optional[str] = None,
+ default_language: str | None = None,
) -> None:
m = FENCE_RE.match(line)
if m:
fence = m.group("fence")
- lang: Optional[str] = m.group("lang")
- header: Optional[str] = m.group("header")
+ lang: str | None = m.group("lang")
+ header: str | None = m.group("header")
if not lang and default_language:
lang = default_language
handler = generic_handler(
@@ -265,7 +265,7 @@ class OuterHandler(ZulipBaseHandler):
processor: "FencedBlockPreprocessor",
output: MutableSequence[str],
run_content_validators: bool = False,
- default_language: Optional[str] = None,
+ default_language: str | None = None,
) -> None:
self.run_content_validators = run_content_validators
self.default_language = default_language
@@ -284,7 +284,7 @@ class CodeHandler(ZulipBaseHandler):
processor: "FencedBlockPreprocessor",
output: MutableSequence[str],
fence: str,
- lang: Optional[str],
+ lang: str | None,
run_content_validators: bool = False,
) -> None:
self.lang = lang
@@ -310,7 +310,7 @@ class QuoteHandler(ZulipBaseHandler):
processor: "FencedBlockPreprocessor",
output: MutableSequence[str],
fence: str,
- default_language: Optional[str] = None,
+ default_language: str | None = None,
) -> None:
self.default_language = default_language
super().__init__(processor, output, fence, process_contents=True)
@@ -335,7 +335,7 @@ class SpoilerHandler(ZulipBaseHandler):
processor: "FencedBlockPreprocessor",
output: MutableSequence[str],
fence: str,
- spoiler_header: Optional[str],
+ spoiler_header: str | None,
) -> None:
self.spoiler_header = spoiler_header
super().__init__(processor, output, fence, process_contents=True)
@@ -452,7 +452,7 @@ class FencedBlockPreprocessor(Preprocessor):
output.append("")
return output
- def format_code(self, lang: Optional[str], text: str) -> str:
+ def format_code(self, lang: str | None, text: str) -> str:
if lang:
langclass = LANG_TAG.format(lang)
else:
@@ -529,7 +529,7 @@ class FencedBlockPreprocessor(Preprocessor):
quoted_paragraphs.append("\n".join("> " + line for line in lines))
return "\n".join(quoted_paragraphs)
- def format_spoiler(self, header: Optional[str], text: str) -> str:
+ def format_spoiler(self, header: str | None, text: str) -> str:
output = []
header_div_open_html = '<div class="spoiler-block"><div class="spoiler-header">'
end_header_start_content_html = '</div><div class="spoiler-content" aria-hidden="true">'
diff --git a/zerver/lib/markdown/nested_code_blocks.py b/zerver/lib/markdown/nested_code_blocks.py
index 7d3f9682072..69c97183925 100644
--- a/zerver/lib/markdown/nested_code_blocks.py
+++ b/zerver/lib/markdown/nested_code_blocks.py
@@ -1,4 +1,4 @@
-from typing import Any, Mapping, Optional
+from typing import Any, Mapping
from xml.etree.ElementTree import Element, SubElement
import markdown
@@ -32,15 +32,15 @@ class NestedCodeBlocksRendererTreeProcessor(markdown.treeprocessors.Treeprocesso
codehilite_block = self.get_codehilite_block(text)
self.replace_element(block.family.grandparent, codehilite_block, block.family.parent)
- def get_code_tags(self, e: Element) -> Optional[tuple[str, Optional[str]]]:
+ def get_code_tags(self, e: Element) -> tuple[str, str | None] | None:
if e.tag == "code":
return (e.tag, e.text)
return None
def get_nested_code_blocks(
self,
- code_tags: list[ResultWithFamily[tuple[str, Optional[str]]]],
- ) -> list[ResultWithFamily[tuple[str, Optional[str]]]]:
+ code_tags: list[ResultWithFamily[tuple[str, str | None]]],
+ ) -> list[ResultWithFamily[tuple[str, str | None]]]:
nested_code_blocks = []
for code_tag in code_tags:
parent: Any = code_tag.family.parent
@@ -60,7 +60,7 @@ class NestedCodeBlocksRendererTreeProcessor(markdown.treeprocessors.Treeprocesso
return nested_code_blocks
- def get_codehilite_block(self, code_block_text: Optional[str]) -> Element:
+ def get_codehilite_block(self, code_block_text: str | None) -> Element:
div = Element("div")
div.set("class", "codehilite")
pre = SubElement(div, "pre")
@@ -69,7 +69,7 @@ class NestedCodeBlocksRendererTreeProcessor(markdown.treeprocessors.Treeprocesso
def replace_element(
self,
- parent: Optional[Element],
+ parent: Element | None,
replacement: Element,
element_to_replace: Element,
) -> None:
diff --git a/zerver/lib/markdown/tabbed_sections.py b/zerver/lib/markdown/tabbed_sections.py
index da9ee750251..706379a8da3 100644
--- a/zerver/lib/markdown/tabbed_sections.py
+++ b/zerver/lib/markdown/tabbed_sections.py
@@ -1,5 +1,5 @@
import re
-from typing import Any, Mapping, Optional
+from typing import Any, Mapping
import markdown
from markdown.extensions import Extension
@@ -201,7 +201,7 @@ class TabbedSectionsPreprocessor(Preprocessor):
return NAV_BAR_TEMPLATE.format(tabs="\n".join(li_elements))
- def parse_tabs(self, lines: list[str]) -> Optional[dict[str, Any]]:
+ def parse_tabs(self, lines: list[str]) -> dict[str, Any] | None:
block: dict[str, Any] = {}
for index, line in enumerate(lines):
start_match = START_TABBED_SECTION_REGEX.search(line)
diff --git a/zerver/lib/mention.py b/zerver/lib/mention.py
index 5517bc70016..a55593456c3 100644
--- a/zerver/lib/mention.py
+++ b/zerver/lib/mention.py
@@ -1,7 +1,7 @@
import functools
import re
from dataclasses import dataclass
-from typing import Match, Optional
+from typing import Match
from django.conf import settings
from django.db.models import Q
@@ -34,8 +34,8 @@ class FullNameInfo:
@dataclass
class UserFilter:
- id: Optional[int]
- full_name: Optional[str]
+ id: int | None
+ full_name: str | None
def Q(self) -> Q:
if self.full_name is not None and self.id is not None:
@@ -50,7 +50,7 @@ class UserFilter:
@dataclass
class MentionText:
- text: Optional[str]
+ text: str | None
is_topic_wildcard: bool
is_stream_wildcard: bool
@@ -76,7 +76,7 @@ class MentionBackend:
self.stream_cache: dict[str, int] = {}
def get_full_name_info_list(
- self, user_filters: list[UserFilter], message_sender: Optional[UserProfile]
+ self, user_filters: list[UserFilter], message_sender: UserProfile | None
) -> list[FullNameInfo]:
result: list[FullNameInfo] = []
unseen_user_filters: list[UserFilter] = []
@@ -215,7 +215,7 @@ def possible_user_group_mentions(content: str) -> set[str]:
def get_possible_mentions_info(
- mention_backend: MentionBackend, mention_texts: set[str], message_sender: Optional[UserProfile]
+ mention_backend: MentionBackend, mention_texts: set[str], message_sender: UserProfile | None
) -> list[FullNameInfo]:
if not mention_texts:
return []
@@ -244,7 +244,7 @@ def get_possible_mentions_info(
class MentionData:
def __init__(
- self, mention_backend: MentionBackend, content: str, message_sender: Optional[UserProfile]
+ self, mention_backend: MentionBackend, content: str, message_sender: UserProfile | None
) -> None:
self.mention_backend = mention_backend
realm_id = mention_backend.realm_id
@@ -275,13 +275,13 @@ class MentionData:
self.user_group_name_info[group.name.lower()] = group
self.user_group_members[group.id] = [m.id for m in group.direct_members.all()]
- def get_user_by_name(self, name: str) -> Optional[FullNameInfo]:
+ def get_user_by_name(self, name: str) -> FullNameInfo | None:
# warning: get_user_by_name is not dependable if two
# users of the same full name are mentioned. Use
# get_user_by_id where possible.
return self.full_name_info.get(name.lower(), None)
- def get_user_by_id(self, id: int) -> Optional[FullNameInfo]:
+ def get_user_by_id(self, id: int) -> FullNameInfo | None:
return self.user_id_info.get(id, None)
def get_user_ids(self) -> set[int]:
@@ -293,7 +293,7 @@ class MentionData:
"""
return set(self.user_id_info.keys())
- def get_user_group(self, name: str) -> Optional[NamedUserGroup]:
+ def get_user_group(self, name: str) -> NamedUserGroup | None:
return self.user_group_name_info.get(name.lower(), None)
def get_group_members(self, user_group_id: int) -> list[int]:
diff --git a/zerver/lib/message.py b/zerver/lib/message.py
index 168dd76e96e..b5457fd65dc 100644
--- a/zerver/lib/message.py
+++ b/zerver/lib/message.py
@@ -1,7 +1,7 @@
import re
from dataclasses import dataclass, field
from datetime import datetime, timedelta
-from typing import Any, Callable, Collection, Mapping, Optional, Sequence, TypedDict, Union
+from typing import Any, Callable, Collection, Mapping, Sequence, TypedDict
from django.conf import settings
from django.db import connection
@@ -113,10 +113,10 @@ class UnreadMessagesResult(TypedDict):
class SendMessageRequest:
message: Message
rendering_result: MessageRenderingResult
- stream: Optional[Stream]
- sender_muted_stream: Optional[bool]
- local_id: Optional[str]
- sender_queue_id: Optional[str]
+ stream: Stream | None
+ sender_muted_stream: bool | None
+ local_id: str | None
+ sender_queue_id: str | None
realm: Realm
mention_data: MentionData
mentioned_user_groups_map: dict[int, int]
@@ -162,15 +162,15 @@ class SendMessageRequest:
# A topic participant is anyone who either sent or reacted to messages in the topic.
topic_participant_user_ids: set[int]
links_for_embed: set[str]
- widget_content: Optional[dict[str, Any]]
+ widget_content: dict[str, Any] | None
submessages: list[dict[str, Any]] = field(default_factory=list)
- deliver_at: Optional[datetime] = None
- delivery_type: Optional[str] = None
- limit_unread_user_ids: Optional[set[int]] = None
- service_queue_events: Optional[dict[str, list[dict[str, Any]]]] = None
+ deliver_at: datetime | None = None
+ delivery_type: str | None = None
+ limit_unread_user_ids: set[int] | None = None
+ service_queue_events: dict[str, list[dict[str, Any]]] | None = None
disable_external_notifications: bool = False
- automatic_new_visibility_policy: Optional[int] = None
- recipients_for_user_creation_events: Optional[dict[UserProfile, set[int]]] = None
+ automatic_new_visibility_policy: int | None = None
+ recipients_for_user_creation_events: dict[UserProfile, set[int]] | None = None
# We won't try to fetch more unread message IDs from the database than
@@ -206,7 +206,7 @@ def messages_for_ids(
apply_markdown: bool,
client_gravatar: bool,
allow_edit_history: bool,
- user_profile: Optional[UserProfile],
+ user_profile: UserProfile | None,
realm: Realm,
) -> list[dict[str, Any]]:
id_fetcher = lambda row: row["id"]
@@ -294,7 +294,7 @@ def access_message_and_usermessage(
user_profile: UserProfile,
message_id: int,
lock_message: bool = False,
-) -> tuple[Message, Optional[UserMessage]]:
+) -> tuple[Message, UserMessage | None]:
"""As access_message, but also returns the usermessage, if any."""
try:
base_query = Message.objects.select_related(*Message.DEFAULT_SELECT_RELATED)
@@ -361,8 +361,8 @@ def has_message_access(
message: Message,
*,
has_user_message: Callable[[], bool],
- stream: Optional[Stream] = None,
- is_subscribed: Optional[bool] = None,
+ stream: Stream | None = None,
+ is_subscribed: bool | None = None,
) -> bool:
"""
Returns whether a user has access to a given message.
@@ -411,7 +411,7 @@ def bulk_access_messages(
user_profile: UserProfile,
messages: Collection[Message] | QuerySet[Message],
*,
- stream: Optional[Stream] = None,
+ stream: Stream | None = 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
@@ -563,7 +563,7 @@ def get_starred_message_ids(user_profile: UserProfile) -> list[int]:
def get_raw_unread_data(
- user_profile: UserProfile, message_ids: Optional[list[int]] = None
+ user_profile: UserProfile, message_ids: list[int] | None = None
) -> RawUnreadMessagesResult:
excluded_recipient_ids = get_inactive_recipient_ids(user_profile)
first_visible_message_id = get_first_visible_message_id(user_profile.realm)
@@ -605,7 +605,7 @@ def get_raw_unread_data(
def extract_unread_data_from_um_rows(
- rows: list[dict[str, Any]], user_profile: Optional[UserProfile]
+ rows: list[dict[str, Any]], user_profile: UserProfile | None
) -> RawUnreadMessagesResult:
pm_dict: dict[int, RawUnreadDirectMessageDict] = {}
stream_dict: dict[int, RawUnreadStreamDict] = {}
@@ -1232,11 +1232,11 @@ def check_user_group_mention_allowed(sender: UserProfile, user_group_ids: list[i
def parse_message_time_limit_setting(
- value: Union[int, str],
- special_values_map: Mapping[str, Optional[int]],
+ value: int | str,
+ special_values_map: Mapping[str, int | None],
*,
setting_name: str,
-) -> Optional[int]:
+) -> int | None:
if isinstance(value, str) and value in special_values_map:
return special_values_map[value]
if isinstance(value, str) or value <= 0:
@@ -1247,8 +1247,8 @@ def parse_message_time_limit_setting(
def visibility_policy_for_participation(
sender: UserProfile,
- is_stream_muted: Optional[bool],
-) -> Optional[int]:
+ is_stream_muted: bool | None,
+) -> int | None:
"""
This function determines the visibility policy to set when a user
participates in a topic, depending on the 'automatically_follow_topics_policy'
@@ -1272,8 +1272,8 @@ def visibility_policy_for_participation(
def visibility_policy_for_send(
sender: UserProfile,
- is_stream_muted: Optional[bool],
-) -> Optional[int]:
+ is_stream_muted: bool | None,
+) -> int | None:
if (
sender.automatically_follow_topics_policy
== UserProfile.AUTOMATICALLY_CHANGE_VISIBILITY_POLICY_ON_SEND
@@ -1294,9 +1294,9 @@ def visibility_policy_for_send_message(
sender: UserProfile,
message: Message,
stream: Stream,
- is_stream_muted: Optional[bool],
+ is_stream_muted: bool | None,
current_visibility_policy: int,
-) -> Optional[int]:
+) -> int | None:
"""
This function determines the visibility policy to set when a message
is sent to a topic, depending on the 'automatically_follow_topics_policy'
@@ -1348,7 +1348,7 @@ def visibility_policy_for_send_message(
return visibility_policy
# Now we need to check if the user initiated the topic.
- old_accessible_messages_in_topic: Union[QuerySet[Message], QuerySet[UserMessage]]
+ old_accessible_messages_in_topic: QuerySet[Message] | QuerySet[UserMessage]
if can_access_stream_history(sender, stream):
old_accessible_messages_in_topic = messages_for_topic(
realm_id=sender.realm_id,
diff --git a/zerver/lib/message_cache.py b/zerver/lib/message_cache.py
index c286e2a1551..9e7ec709320 100644
--- a/zerver/lib/message_cache.py
+++ b/zerver/lib/message_cache.py
@@ -2,7 +2,7 @@ import copy
import zlib
from datetime import datetime
from email.headerregistry import Address
-from typing import Any, Iterable, Optional, TypedDict
+from typing import Any, Iterable, TypedDict
import orjson
@@ -73,12 +73,12 @@ def stringify_message_dict(message_dict: dict[str, Any]) -> bytes:
@cache_with_key(to_dict_cache_key, timeout=3600 * 24)
-def message_to_encoded_cache(message: Message, realm_id: Optional[int] = None) -> bytes:
+def message_to_encoded_cache(message: Message, realm_id: int | None = None) -> bytes:
return MessageDict.messages_to_encoded_cache([message], realm_id)[message.id]
def update_message_cache(
- changed_messages: Iterable[Message], realm_id: Optional[int] = None
+ changed_messages: Iterable[Message], realm_id: int | None = None
) -> list[int]:
"""Updates the message as stored in the to_dict cache (for serving
messages)."""
@@ -151,7 +151,7 @@ class MessageDict:
"""
@staticmethod
- def wide_dict(message: Message, realm_id: Optional[int] = None) -> dict[str, Any]:
+ def wide_dict(message: Message, realm_id: int | None = None) -> dict[str, Any]:
"""
The next two lines get the cacheable field related
to our message object, with the side effect of
@@ -273,7 +273,7 @@ class MessageDict:
@staticmethod
def messages_to_encoded_cache(
- messages: Iterable[Message], realm_id: Optional[int] = None
+ messages: Iterable[Message], realm_id: int | None = None
) -> dict[int, bytes]:
messages_dict = MessageDict.messages_to_encoded_cache_helper(messages, realm_id)
encoded_messages = {msg["id"]: stringify_message_dict(msg) for msg in messages_dict}
@@ -281,7 +281,7 @@ class MessageDict:
@staticmethod
def messages_to_encoded_cache_helper(
- messages: Iterable[Message], realm_id: Optional[int] = None
+ messages: Iterable[Message], realm_id: int | None = None
) -> list[dict[str, Any]]:
# Near duplicate of the build_message_dict + get_raw_db_rows
# code path that accepts already fetched Message objects
@@ -374,13 +374,13 @@ class MessageDict:
@staticmethod
def build_message_dict(
message_id: int,
- last_edit_time: Optional[datetime],
- edit_history_json: Optional[str],
+ last_edit_time: datetime | None,
+ edit_history_json: str | None,
content: str,
topic_name: str,
date_sent: datetime,
- rendered_content: Optional[str],
- rendered_content_version: Optional[int],
+ rendered_content: str | None,
+ rendered_content_version: int | None,
sender_id: int,
sender_realm_id: int,
sending_client_name: str,
diff --git a/zerver/lib/muted_users.py b/zerver/lib/muted_users.py
index d02a5539bcd..4fe2eb5353a 100644
--- a/zerver/lib/muted_users.py
+++ b/zerver/lib/muted_users.py
@@ -1,5 +1,4 @@
from datetime import datetime
-from typing import Optional
from zerver.lib.cache import cache_with_key, get_muting_users_cache_key
from zerver.lib.timestamp import datetime_to_timestamp
@@ -29,7 +28,7 @@ def add_user_mute(user_profile: UserProfile, muted_user: UserProfile, date_muted
)
-def get_mute_object(user_profile: UserProfile, muted_user: UserProfile) -> Optional[MutedUser]:
+def get_mute_object(user_profile: UserProfile, muted_user: UserProfile) -> MutedUser | None:
try:
return MutedUser.objects.get(user_profile=user_profile, muted_user=muted_user)
except MutedUser.DoesNotExist:
diff --git a/zerver/lib/narrow.py b/zerver/lib/narrow.py
index d4bf39b02b3..7643fbcdbd4 100644
--- a/zerver/lib/narrow.py
+++ b/zerver/lib/narrow.py
@@ -1,6 +1,6 @@
import re
from dataclasses import dataclass
-from typing import Any, Callable, Generic, Iterable, Optional, Sequence, TypeVar, Union
+from typing import Any, Callable, Generic, Iterable, Sequence, TypeVar
from django.conf import settings
from django.contrib.auth.models import AnonymousUser
@@ -88,7 +88,7 @@ class NarrowParameter(BaseModel):
@model_validator(mode="before")
@classmethod
- def convert_term(cls, elem: Union[dict[str, Any], list[str]]) -> dict[str, Any]:
+ def convert_term(cls, elem: dict[str, Any] | list[str]) -> dict[str, Any]:
# We have to support a legacy tuple format.
if isinstance(elem, list):
if len(elem) != 2 or any(not isinstance(x, str) for x in elem):
@@ -164,7 +164,7 @@ def is_spectator_compatible(narrow: Iterable[NarrowParameter]) -> bool:
return True
-def is_web_public_narrow(narrow: Optional[Iterable[NarrowParameter]]) -> bool:
+def is_web_public_narrow(narrow: Iterable[NarrowParameter] | None) -> bool:
if narrow is None:
return False
@@ -258,7 +258,7 @@ class NarrowBuilder:
def __init__(
self,
- user_profile: Optional[UserProfile],
+ user_profile: UserProfile | None,
msg_id_column: ColumnElement[Integer],
realm: Realm,
is_web_public_query: bool = False,
@@ -435,7 +435,7 @@ class NarrowBuilder:
return "".join(s)
def by_channel(
- self, query: Select, operand: Union[str, int], maybe_negate: ConditionTransform
+ self, query: Select, operand: str | int, maybe_negate: ConditionTransform
) -> Select:
self.check_not_both_channel_and_dm_narrow(is_channel_narrow=True)
@@ -545,7 +545,7 @@ class NarrowBuilder:
return query.where(maybe_negate(cond))
def by_sender(
- self, query: Select, operand: Union[str, int], maybe_negate: ConditionTransform
+ self, query: Select, operand: str | int, maybe_negate: ConditionTransform
) -> Select:
try:
if isinstance(operand, str):
@@ -561,16 +561,14 @@ class NarrowBuilder:
def by_near(self, query: Select, operand: str, maybe_negate: ConditionTransform) -> Select:
return query
- def by_id(
- self, query: Select, operand: Union[int, str], maybe_negate: ConditionTransform
- ) -> Select:
+ def by_id(self, query: Select, operand: int | str, maybe_negate: ConditionTransform) -> Select:
if not str(operand).isdigit() or int(operand) > Message.MAX_POSSIBLE_MESSAGE_ID:
raise BadNarrowOperatorError("Invalid message ID")
cond = self.msg_id_column == literal(operand)
return query.where(maybe_negate(cond))
def by_dm(
- self, query: Select, operand: Union[str, Iterable[int]], maybe_negate: ConditionTransform
+ self, query: Select, operand: str | Iterable[int], maybe_negate: ConditionTransform
) -> Select:
# This operator does not support is_web_public_query.
assert not self.is_web_public_query
@@ -675,7 +673,7 @@ class NarrowBuilder:
return set(self_recipient_ids) & set(narrow_recipient_ids)
def by_dm_including(
- self, query: Select, operand: Union[str, int], maybe_negate: ConditionTransform
+ self, query: Select, operand: str | int, maybe_negate: ConditionTransform
) -> Select:
# This operator does not support is_web_public_query.
assert not self.is_web_public_query
@@ -728,7 +726,7 @@ class NarrowBuilder:
return query.where(maybe_negate(cond))
def by_group_pm_with(
- self, query: Select, operand: Union[str, int], maybe_negate: ConditionTransform
+ self, query: Select, operand: str | int, maybe_negate: ConditionTransform
) -> Select:
# This operator does not support is_web_public_query.
assert not self.is_web_public_query
@@ -810,8 +808,8 @@ class NarrowBuilder:
def ok_to_include_history(
- narrow: Optional[list[NarrowParameter]],
- user_profile: Optional[UserProfile],
+ narrow: list[NarrowParameter] | None,
+ user_profile: UserProfile | None,
is_web_public_query: bool,
) -> bool:
# There are occasions where we need to find Message rows that
@@ -839,7 +837,7 @@ def ok_to_include_history(
if narrow is not None:
for term in narrow:
if term.operator in channel_operators and not term.negated:
- operand: Union[str, int] = term.operand
+ operand: str | int = term.operand
if isinstance(operand, str):
include_history = can_access_stream_history_by_name(user_profile, operand)
else:
@@ -862,8 +860,8 @@ def ok_to_include_history(
def get_channel_from_narrow_access_unchecked(
- narrow: Optional[list[NarrowParameter]], realm: Realm
-) -> Optional[Stream]:
+ narrow: list[NarrowParameter] | None, realm: Realm
+) -> Stream | None:
if narrow is not None:
for term in narrow:
if term.operator in channel_operators:
@@ -948,7 +946,7 @@ def update_narrow_terms_containing_with_operator(
def exclude_muting_conditions(
- user_profile: UserProfile, narrow: Optional[list[NarrowParameter]]
+ user_profile: UserProfile, narrow: list[NarrowParameter] | None
) -> list[ClauseElement]:
conditions: list[ClauseElement] = []
channel_id = None
@@ -993,7 +991,7 @@ def exclude_muting_conditions(
def get_base_query_for_search(
- realm_id: int, user_profile: Optional[UserProfile], need_message: bool, need_user_message: bool
+ realm_id: int, user_profile: UserProfile | None, need_message: bool, need_user_message: bool
) -> tuple[Select, ColumnElement[Integer]]:
# Handle the simple case where user_message isn't involved first.
if not need_user_message:
@@ -1038,10 +1036,10 @@ def get_base_query_for_search(
def add_narrow_conditions(
- user_profile: Optional[UserProfile],
+ user_profile: UserProfile | None,
inner_msg_id_col: ColumnElement[Integer],
query: Select,
- narrow: Optional[list[NarrowParameter]],
+ narrow: list[NarrowParameter] | None,
is_web_public_query: bool,
realm: Realm,
) -> tuple[Select, bool]:
@@ -1077,8 +1075,8 @@ def add_narrow_conditions(
def find_first_unread_anchor(
sa_conn: Connection,
- user_profile: Optional[UserProfile],
- narrow: Optional[list[NarrowParameter]],
+ user_profile: UserProfile | None,
+ narrow: list[NarrowParameter] | None,
) -> int:
# For anonymous web users, all messages are treated as read, and so
# always return LARGER_THAN_MAX_MESSAGE_ID.
@@ -1131,7 +1129,7 @@ def find_first_unread_anchor(
return anchor
-def parse_anchor_value(anchor_val: Optional[str], use_first_unread_anchor: bool) -> Optional[int]:
+def parse_anchor_value(anchor_val: str | None, use_first_unread_anchor: bool) -> int | None:
"""Given the anchor and use_first_unread_anchor parameters passed by
the client, computes what anchor value the client requested,
handling backwards-compatibility and the various string-valued
@@ -1339,11 +1337,11 @@ class FetchedMessages(LimitedMessages[Row]):
def fetch_messages(
*,
- narrow: Optional[list[NarrowParameter]],
- user_profile: Optional[UserProfile],
+ narrow: list[NarrowParameter] | None,
+ user_profile: UserProfile | None,
realm: Realm,
is_web_public_query: bool,
- anchor: Optional[int],
+ anchor: int | None,
include_anchor: bool,
num_before: int,
num_after: int,
diff --git a/zerver/lib/narrow_helpers.py b/zerver/lib/narrow_helpers.py
index 67278886e23..49e1d2fb9ed 100644
--- a/zerver/lib/narrow_helpers.py
+++ b/zerver/lib/narrow_helpers.py
@@ -20,7 +20,7 @@ from users:
import os
from dataclasses import dataclass
-from typing import Collection, Optional, Sequence
+from typing import Collection, Sequence
from django.conf import settings
@@ -40,7 +40,7 @@ def narrow_dataclasses_from_tuples(tups: Collection[Sequence[str]]) -> Collectio
return [NarrowTerm(operator=tup[0], operand=tup[1]) for tup in tups]
-stop_words_list: Optional[list[str]] = None
+stop_words_list: list[str] | None = None
def read_stop_words() -> list[str]:
diff --git a/zerver/lib/notification_data.py b/zerver/lib/notification_data.py
index 5a1f6be1008..d35df0be4f3 100644
--- a/zerver/lib/notification_data.py
+++ b/zerver/lib/notification_data.py
@@ -1,6 +1,6 @@
import math
from dataclasses import dataclass
-from typing import Any, Collection, Optional
+from typing import Any, Collection
from zerver.lib.mention import MentionData
from zerver.lib.user_groups import get_user_group_member_ids
@@ -199,7 +199,7 @@ class UserMessageNotificationsData:
def is_push_notifiable(self, acting_user_id: int, idle: bool) -> bool:
return self.get_push_notification_trigger(acting_user_id, idle) is not None
- def get_push_notification_trigger(self, acting_user_id: int, idle: bool) -> Optional[str]:
+ def get_push_notification_trigger(self, acting_user_id: int, idle: bool) -> str | None:
if not idle and not self.online_push_enabled:
return None
@@ -231,7 +231,7 @@ class UserMessageNotificationsData:
def is_email_notifiable(self, acting_user_id: int, idle: bool) -> bool:
return self.get_email_notification_trigger(acting_user_id, idle) is not None
- def get_email_notification_trigger(self, acting_user_id: int, idle: bool) -> Optional[str]:
+ def get_email_notification_trigger(self, acting_user_id: int, idle: bool) -> str | None:
if not idle:
return None
@@ -264,7 +264,7 @@ class UserMessageNotificationsData:
def user_allows_notifications_in_StreamTopic(
stream_is_muted: bool,
visibility_policy: int,
- stream_specific_setting: Optional[bool],
+ stream_specific_setting: bool | None,
global_setting: bool,
) -> bool:
"""
@@ -322,7 +322,7 @@ class MentionedUserGroup:
def get_mentioned_user_group(
messages: list[dict[str, Any]], user_profile: UserProfile
-) -> Optional[MentionedUserGroup]:
+) -> MentionedUserGroup | None:
"""Returns the user group name to display in the email notification
if user group(s) are mentioned.
diff --git a/zerver/lib/outgoing_http.py b/zerver/lib/outgoing_http.py
index 9e25df50dc1..b3899a79fe8 100644
--- a/zerver/lib/outgoing_http.py
+++ b/zerver/lib/outgoing_http.py
@@ -1,4 +1,4 @@
-from typing import Any, Optional, Union
+from typing import Any
import requests
from typing_extensions import override
@@ -10,11 +10,11 @@ class OutgoingSession(requests.Session):
self,
role: str,
timeout: float,
- headers: Optional[dict[str, str]] = None,
- max_retries: Optional[Union[int, Retry]] = None,
+ headers: dict[str, str] | None = None,
+ max_retries: int | Retry | None = None,
) -> None:
super().__init__()
- retry: Optional[Retry] = Retry(total=0)
+ retry: Retry | None = Retry(total=0)
if max_retries is not None:
if isinstance(max_retries, Retry):
retry = max_retries
@@ -31,7 +31,7 @@ class OutgoingHTTPAdapter(requests.adapters.HTTPAdapter):
role: str
timeout: float
- def __init__(self, role: str, timeout: float, max_retries: Optional[Retry]) -> None:
+ def __init__(self, role: str, timeout: float, max_retries: Retry | None) -> None:
self.role = role
self.timeout = timeout
super().__init__(max_retries=max_retries)
diff --git a/zerver/lib/outgoing_webhook.py b/zerver/lib/outgoing_webhook.py
index 58b7c95c595..0de4d5f089b 100644
--- a/zerver/lib/outgoing_webhook.py
+++ b/zerver/lib/outgoing_webhook.py
@@ -3,7 +3,7 @@ import json
import logging
from contextlib import suppress
from time import perf_counter
-from typing import Any, AnyStr, Optional
+from typing import Any, AnyStr
import requests
from django.conf import settings
@@ -37,21 +37,17 @@ class OutgoingWebhookServiceInterface(metaclass=abc.ABCMeta):
)
@abc.abstractmethod
- def make_request(
- self, base_url: str, event: dict[str, Any], realm: Realm
- ) -> Optional[Response]:
+ def make_request(self, base_url: str, event: dict[str, Any], realm: Realm) -> Response | None:
raise NotImplementedError
@abc.abstractmethod
- def process_success(self, response_json: dict[str, Any]) -> Optional[dict[str, Any]]:
+ def process_success(self, response_json: dict[str, Any]) -> dict[str, Any] | None:
raise NotImplementedError
class GenericOutgoingWebhookService(OutgoingWebhookServiceInterface):
@override
- def make_request(
- self, base_url: str, event: dict[str, Any], realm: Realm
- ) -> Optional[Response]:
+ def make_request(self, base_url: str, event: dict[str, Any], realm: Realm) -> Response | None:
"""
We send a simple version of the message to outgoing
webhooks, since most of them really only need
@@ -80,7 +76,7 @@ class GenericOutgoingWebhookService(OutgoingWebhookServiceInterface):
return self.session.post(base_url, json=request_data)
@override
- def process_success(self, response_json: dict[str, Any]) -> Optional[dict[str, Any]]:
+ def process_success(self, response_json: dict[str, Any]) -> dict[str, Any] | None:
if response_json.get("response_not_required", False):
return None
@@ -102,9 +98,7 @@ class GenericOutgoingWebhookService(OutgoingWebhookServiceInterface):
class SlackOutgoingWebhookService(OutgoingWebhookServiceInterface):
@override
- def make_request(
- self, base_url: str, event: dict[str, Any], realm: Realm
- ) -> Optional[Response]:
+ def make_request(self, base_url: str, event: dict[str, Any], realm: Realm) -> Response | None:
if event["message"]["type"] == "private":
failure_message = "Slack outgoing webhooks don't support direct messages."
fail_with_message(event, failure_message)
@@ -142,7 +136,7 @@ class SlackOutgoingWebhookService(OutgoingWebhookServiceInterface):
return self.session.post(base_url, data=request_data)
@override
- def process_success(self, response_json: dict[str, Any]) -> Optional[dict[str, Any]]:
+ def process_success(self, response_json: dict[str, Any]) -> dict[str, Any] | None:
if "text" in response_json:
content = response_json["text"]
success_data = dict(content=content)
@@ -194,7 +188,7 @@ def send_response_message(
recipient_type_name = message_info["type"]
display_recipient = message_info["display_recipient"]
try:
- topic_name: Optional[str] = get_topic_from_message_info(message_info)
+ topic_name: str | None = get_topic_from_message_info(message_info)
except KeyError:
topic_name = None
@@ -251,10 +245,10 @@ def get_message_url(event: dict[str, Any]) -> str:
def notify_bot_owner(
event: dict[str, Any],
- status_code: Optional[int] = None,
- response_content: Optional[AnyStr] = None,
- failure_message: Optional[str] = None,
- exception: Optional[Exception] = None,
+ status_code: int | None = None,
+ response_content: AnyStr | None = None,
+ failure_message: str | None = None,
+ exception: Exception | None = None,
) -> None:
message_url = get_message_url(event)
bot_id = event["user_profile_id"]
@@ -290,7 +284,7 @@ def notify_bot_owner(
send_response_message(bot_id=bot_id, message_info=message_info, response_data=response_data)
-def request_retry(event: dict[str, Any], failure_message: Optional[str] = None) -> None:
+def request_retry(event: dict[str, Any], failure_message: str | None = None) -> None:
def failure_processor(event: dict[str, Any]) -> None:
"""
The name of the argument is 'event' on purpose. This argument will hide
@@ -347,7 +341,7 @@ def do_rest_call(
base_url: str,
event: dict[str, Any],
service_handler: OutgoingWebhookServiceInterface,
-) -> Optional[Response]:
+) -> Response | None:
"""Returns response of call if no exception occurs."""
try:
start_time = perf_counter()
diff --git a/zerver/lib/presence.py b/zerver/lib/presence.py
index 532efc8aaa6..426328359b8 100644
--- a/zerver/lib/presence.py
+++ b/zerver/lib/presence.py
@@ -1,7 +1,7 @@
import time
from collections import defaultdict
from datetime import datetime, timedelta
-from typing import Any, Mapping, Optional, Sequence
+from typing import Any, Mapping, Sequence
from django.conf import settings
from django.utils.timezone import now as timezone_now
@@ -45,7 +45,7 @@ def get_presence_dicts_for_rows(
def user_presence_datetime_with_date_joined_default(
- dt: Optional[datetime], date_joined: datetime
+ dt: datetime | None, date_joined: datetime
) -> datetime:
"""
Our data models support UserPresence objects not having None
@@ -149,8 +149,8 @@ def get_presence_for_user(
def get_presence_dict_by_realm(
realm: Realm,
slim_presence: bool = False,
- last_update_id_fetched_by_client: Optional[int] = None,
- requesting_user_profile: Optional[UserProfile] = None,
+ last_update_id_fetched_by_client: int | None = None,
+ requesting_user_profile: UserProfile | None = None,
) -> tuple[dict[str, dict[str, Any]], int]:
two_weeks_ago = timezone_now() - timedelta(weeks=2)
kwargs: dict[str, object] = dict()
@@ -188,7 +188,7 @@ def get_presence_dict_by_realm(
)
# Get max last_update_id from the list.
if presence_rows:
- last_update_id_fetched_by_server: Optional[int] = max(
+ last_update_id_fetched_by_server: int | None = max(
row["last_update_id"] for row in presence_rows
)
elif last_update_id_fetched_by_client is not None:
@@ -211,7 +211,7 @@ def get_presence_dict_by_realm(
def get_presences_for_realm(
realm: Realm,
slim_presence: bool,
- last_update_id_fetched_by_client: Optional[int],
+ last_update_id_fetched_by_client: int | None,
requesting_user_profile: UserProfile,
) -> tuple[dict[str, dict[str, dict[str, Any]]], int]:
if realm.presence_disabled:
@@ -229,7 +229,7 @@ def get_presences_for_realm(
def get_presence_response(
requesting_user_profile: UserProfile,
slim_presence: bool,
- last_update_id_fetched_by_client: Optional[int] = None,
+ last_update_id_fetched_by_client: int | None = None,
) -> dict[str, Any]:
realm = requesting_user_profile.realm
server_timestamp = time.time()
diff --git a/zerver/lib/push_notifications.py b/zerver/lib/push_notifications.py
index dc35b2ab359..55fb1b632d5 100644
--- a/zerver/lib/push_notifications.py
+++ b/zerver/lib/push_notifications.py
@@ -102,7 +102,7 @@ class UserPushIdentityCompat:
may be represented either by an id or uuid.
"""
- def __init__(self, user_id: Optional[int] = None, user_uuid: Optional[str] = None) -> None:
+ def __init__(self, user_id: int | None = None, user_uuid: str | None = None) -> None:
assert user_id is not None or user_uuid is not None
self.user_id = user_id
self.user_uuid = user_uuid
@@ -157,7 +157,7 @@ def has_apns_credentials() -> bool:
@cache
-def get_apns_context() -> Optional[APNsContext]:
+def get_apns_context() -> APNsContext | None:
# We lazily do this import as part of optimizing Zulip's base
# import time.
import aioapns
@@ -286,7 +286,7 @@ def send_apple_push_notification(
devices = [device for device in devices if device.ios_app_id is not None]
async def send_all_notifications() -> (
- Iterable[tuple[DeviceToken, Union[aioapns.common.NotificationResult, BaseException]]]
+ Iterable[tuple[DeviceToken, aioapns.common.NotificationResult | BaseException]]
):
requests = [
aioapns.NotificationRequest(
@@ -643,7 +643,7 @@ def send_notifications_to_bouncer(
def add_push_device_token(
- user_profile: UserProfile, token_str: str, kind: int, ios_app_id: Optional[str] = None
+ user_profile: UserProfile, token_str: str, kind: int, ios_app_id: str | None = None
) -> None:
logger.info(
"Registering push device: %d %r %d %r", user_profile.id, token_str, kind, ios_app_id
@@ -961,8 +961,8 @@ def get_base_payload(user_profile: UserProfile) -> dict[str, Any]:
def get_message_payload(
user_profile: UserProfile,
message: Message,
- mentioned_user_group_id: Optional[int] = None,
- mentioned_user_group_name: Optional[str] = None,
+ mentioned_user_group_id: int | None = None,
+ mentioned_user_group_name: str | None = None,
can_access_sender: bool = True,
) -> dict[str, Any]:
"""Common fields for `message` payloads, for all platforms."""
@@ -1020,7 +1020,7 @@ def get_apns_alert_subtitle(
message: Message,
trigger: str,
user_profile: UserProfile,
- mentioned_user_group_name: Optional[str] = None,
+ mentioned_user_group_name: str | None = None,
can_access_sender: bool = True,
) -> str:
"""
@@ -1056,7 +1056,7 @@ def get_apns_alert_subtitle(
def get_apns_badge_count(
- user_profile: UserProfile, read_messages_ids: Optional[Sequence[int]] = []
+ user_profile: UserProfile, read_messages_ids: Sequence[int] | None = []
) -> int:
# NOTE: We have temporarily set get_apns_badge_count to always
# return 0 until we can debug a likely mobile app side issue with
@@ -1065,7 +1065,7 @@ def get_apns_badge_count(
def get_apns_badge_count_future(
- user_profile: UserProfile, read_messages_ids: Optional[Sequence[int]] = []
+ user_profile: UserProfile, read_messages_ids: Sequence[int] | None = []
) -> int:
# Future implementation of get_apns_badge_count; unused but
# we expect to use this once we resolve client-side bugs.
@@ -1087,8 +1087,8 @@ def get_message_payload_apns(
user_profile: UserProfile,
message: Message,
trigger: str,
- mentioned_user_group_id: Optional[int] = None,
- mentioned_user_group_name: Optional[str] = None,
+ mentioned_user_group_id: int | None = None,
+ mentioned_user_group_name: str | None = None,
can_access_sender: bool = True,
) -> dict[str, Any]:
"""A `message` payload for iOS, via APNs."""
@@ -1120,8 +1120,8 @@ def get_message_payload_apns(
def get_message_payload_gcm(
user_profile: UserProfile,
message: Message,
- mentioned_user_group_id: Optional[int] = None,
- mentioned_user_group_name: Optional[str] = None,
+ mentioned_user_group_id: int | None = None,
+ mentioned_user_group_name: str | None = None,
can_access_sender: bool = True,
) -> tuple[dict[str, Any], dict[str, Any]]:
"""A `message` payload + options, for Android via FCM."""
diff --git a/zerver/lib/queue.py b/zerver/lib/queue.py
index a23b39c3f21..ea128014859 100644
--- a/zerver/lib/queue.py
+++ b/zerver/lib/queue.py
@@ -5,7 +5,7 @@ import threading
import time
from abc import ABCMeta, abstractmethod
from collections import defaultdict
-from typing import Any, Callable, Generic, Mapping, Optional, TypeVar, Union
+from typing import Any, Callable, Generic, Mapping, TypeVar
import orjson
import pika
@@ -35,12 +35,12 @@ class QueueClient(Generic[ChannelT], metaclass=ABCMeta):
def __init__(
self,
# Disable RabbitMQ heartbeats by default because BlockingConnection can't process them
- rabbitmq_heartbeat: Optional[int] = 0,
+ rabbitmq_heartbeat: int | None = 0,
prefetch: int = 0,
) -> None:
self.log = logging.getLogger("zulip.queue")
self.queues: set[str] = set()
- self.channel: Optional[ChannelT] = None
+ self.channel: ChannelT | None = None
self.prefetch = prefetch
self.consumers: dict[str, set[Consumer[ChannelT]]] = defaultdict(set)
self.rabbitmq_heartbeat = rabbitmq_heartbeat
@@ -80,7 +80,7 @@ class QueueClient(Generic[ChannelT], metaclass=ABCMeta):
if self.rabbitmq_heartbeat == 0:
tcp_options = dict(TCP_KEEPIDLE=60 * 5)
- ssl_options: Union[type[pika.ConnectionParameters._DEFAULT], pika.SSLOptions] = (
+ ssl_options: type[pika.ConnectionParameters._DEFAULT] | pika.SSLOptions = (
pika.ConnectionParameters._DEFAULT
)
if settings.RABBITMQ_USE_TLS:
@@ -146,7 +146,7 @@ class QueueClient(Generic[ChannelT], metaclass=ABCMeta):
class SimpleQueueClient(QueueClient[BlockingChannel]):
- connection: Optional[pika.BlockingConnection]
+ connection: pika.BlockingConnection | None
@override
def _connect(self) -> None:
@@ -188,7 +188,7 @@ class SimpleQueueClient(QueueClient[BlockingChannel]):
queue_name: str,
callback: Callable[[list[dict[str, Any]]], None],
batch_size: int = 1,
- timeout: Optional[int] = None,
+ timeout: int | None = None,
) -> None:
if batch_size == 1:
timeout = None
@@ -196,7 +196,7 @@ class SimpleQueueClient(QueueClient[BlockingChannel]):
def do_consume(channel: BlockingChannel) -> None:
events: list[dict[str, Any]] = []
last_process = time.time()
- max_processed: Optional[int] = None
+ max_processed: int | None = None
self.is_consuming = True
# This iterator technique will iteratively collect up to
@@ -261,7 +261,7 @@ calling _adapter_disconnect, ignoring",
class TornadoQueueClient(QueueClient[Channel]):
- connection: Optional[ExceptionFreeTornadoConnection]
+ connection: ExceptionFreeTornadoConnection | None
# Based on:
# https://pika.readthedocs.io/en/0.9.8/examples/asynchronous_consumer_example.html
@@ -309,7 +309,7 @@ class TornadoQueueClient(QueueClient[Channel]):
CONNECTION_FAILURES_BEFORE_NOTIFY = 10
def _on_connection_open_error(
- self, connection: pika.connection.Connection, reason: Union[str, Exception]
+ self, connection: pika.connection.Connection, reason: str | Exception
) -> None:
self._connection_failure_count += 1
retry_secs = self.CONNECTION_RETRY_SECS
@@ -388,7 +388,7 @@ class TornadoQueueClient(QueueClient[Channel]):
queue_name: str,
callback: Callable[[list[dict[str, Any]]], None],
batch_size: int = 1,
- timeout: Optional[int] = None,
+ timeout: int | None = None,
) -> None:
def wrapped_consumer(
ch: Channel,
@@ -420,7 +420,7 @@ class TornadoQueueClient(QueueClient[Channel]):
thread_data = threading.local()
-def get_queue_client() -> Union[SimpleQueueClient, TornadoQueueClient]:
+def get_queue_client() -> SimpleQueueClient | TornadoQueueClient:
if not hasattr(thread_data, "queue_client"):
if not settings.USING_RABBITMQ:
raise RuntimeError("Cannot get a queue client without USING_RABBITMQ")
@@ -429,14 +429,14 @@ def get_queue_client() -> Union[SimpleQueueClient, TornadoQueueClient]:
return thread_data.queue_client
-def set_queue_client(queue_client: Union[SimpleQueueClient, TornadoQueueClient]) -> None:
+def set_queue_client(queue_client: SimpleQueueClient | TornadoQueueClient) -> None:
thread_data.queue_client = queue_client
def queue_json_publish(
queue_name: str,
event: dict[str, Any],
- processor: Optional[Callable[[Any], None]] = None,
+ processor: Callable[[Any], None] | None = None,
) -> None:
if settings.USING_RABBITMQ:
get_queue_client().json_publish(queue_name, event)
diff --git a/zerver/lib/rate_limiter.py b/zerver/lib/rate_limiter.py
index 113ddb029e8..a65f7b6b93c 100644
--- a/zerver/lib/rate_limiter.py
+++ b/zerver/lib/rate_limiter.py
@@ -116,7 +116,7 @@ class RateLimitedUser(RateLimitedObject):
self.rate_limits = user.rate_limits
self.domain = domain
if settings.RUNNING_INSIDE_TORNADO and domain in settings.RATE_LIMITING_DOMAINS_FOR_TORNADO:
- backend: Optional[type[RateLimiterBackend]] = TornadoInMemoryRateLimiterBackend
+ backend: type[RateLimiterBackend] | None = TornadoInMemoryRateLimiterBackend
else:
backend = None
super().__init__(backend=backend)
@@ -142,7 +142,7 @@ class RateLimitedIPAddr(RateLimitedObject):
self.ip_addr = ip_addr
self.domain = domain
if settings.RUNNING_INSIDE_TORNADO and domain in settings.RATE_LIMITING_DOMAINS_FOR_TORNADO:
- backend: Optional[type[RateLimiterBackend]] = TornadoInMemoryRateLimiterBackend
+ backend: type[RateLimiterBackend] | None = TornadoInMemoryRateLimiterBackend
else:
backend = None
super().__init__(backend=backend)
@@ -363,7 +363,7 @@ class RedisRateLimiterBackend(RateLimiterBackend):
results = pipe.execute()
count: int = results[0]
- newest_call: Optional[bytes] = results[1]
+ newest_call: bytes | None = results[1]
calls_left = max_calls - count
if newest_call is not None:
@@ -390,7 +390,7 @@ class RedisRateLimiterBackend(RateLimiterBackend):
pipe.get(blocking_key)
pipe.ttl(blocking_key)
- rule_timestamps: list[Optional[bytes]] = pipe.execute()
+ rule_timestamps: list[bytes | None] = pipe.execute()
# Check if there is a manual block on this API key
blocking_ttl_b = rule_timestamps.pop()
@@ -437,7 +437,7 @@ class RedisRateLimiterBackend(RateLimiterBackend):
# Get the last elem that we'll trim (so we can remove it from our sorted set)
last_val = cast( # mypy doesn’t know the pipe is in immediate mode
- Optional[bytes], pipe.lindex(list_key, max_api_calls - 1)
+ bytes | None, pipe.lindex(list_key, max_api_calls - 1)
)
# Restart buffered execution
diff --git a/zerver/lib/recipient_users.py b/zerver/lib/recipient_users.py
index b2f46d433a1..b0e03e6d774 100644
--- a/zerver/lib/recipient_users.py
+++ b/zerver/lib/recipient_users.py
@@ -1,4 +1,4 @@
-from typing import Optional, Sequence
+from typing import Sequence
from django.core.exceptions import ValidationError
from django.utils.translation import gettext as _
@@ -14,7 +14,7 @@ from zerver.models.users import is_cross_realm_bot_email
def get_recipient_from_user_profiles(
recipient_profiles: Sequence[UserProfile],
forwarded_mirror_message: bool,
- forwarder_user_profile: Optional[UserProfile],
+ forwarder_user_profile: UserProfile | None,
sender: UserProfile,
create: bool = True,
) -> Recipient:
@@ -102,7 +102,7 @@ def validate_recipient_user_profiles(
def recipient_for_user_profiles(
user_profiles: Sequence[UserProfile],
forwarded_mirror_message: bool,
- forwarder_user_profile: Optional[UserProfile],
+ forwarder_user_profile: UserProfile | None,
sender: UserProfile,
*,
allow_deactivated: bool = False,
diff --git a/zerver/lib/redis_utils.py b/zerver/lib/redis_utils.py
index 66ddd871a07..89f818ddf07 100644
--- a/zerver/lib/redis_utils.py
+++ b/zerver/lib/redis_utils.py
@@ -1,7 +1,7 @@
import os
import re
import secrets
-from typing import Any, Mapping, Optional
+from typing import Any, Mapping
import orjson
import redis
@@ -40,7 +40,7 @@ def put_dict_in_redis(
data_to_store: Mapping[str, Any],
expiration_seconds: int,
token_length: int = 64,
- token: Optional[str] = None,
+ token: str | None = None,
) -> str:
key_length = len(key_format) - len("{token}") + token_length
if key_length > MAX_KEY_LENGTH:
@@ -62,7 +62,7 @@ def get_dict_from_redis(
redis_client: "redis.StrictRedis[bytes]",
key_format: str,
key: str,
-) -> Optional[dict[str, Any]]:
+) -> dict[str, Any] | None:
# This function requires inputting the intended key_format to validate
# that the key fits it, as an additionally security measure. This protects
# against bugs where a caller requests a key based on user input and doesn't
diff --git a/zerver/lib/remote_server.py b/zerver/lib/remote_server.py
index d081c3faff2..75b6dd56771 100644
--- a/zerver/lib/remote_server.py
+++ b/zerver/lib/remote_server.py
@@ -1,5 +1,5 @@
import logging
-from typing import Any, Mapping, Optional, Union
+from typing import Any, Mapping
from urllib.parse import urljoin
import orjson
@@ -54,7 +54,7 @@ class RealmCountDataForAnalytics(BaseModel):
realm: int
id: int
end_time: float
- subgroup: Optional[str]
+ subgroup: str | None
value: int
@@ -62,7 +62,7 @@ class InstallationCountDataForAnalytics(BaseModel):
property: str
id: int
end_time: float
- subgroup: Optional[str]
+ subgroup: str | None
value: int
@@ -71,7 +71,7 @@ class RealmAuditLogDataForAnalytics(BaseModel):
realm: int
event_time: float
backfilled: bool
- extra_data: Optional[Union[str, dict[str, Any]]]
+ extra_data: str | dict[str, Any] | None
event_type: int
@@ -104,11 +104,11 @@ class RealmDataForAnalytics(BaseModel):
class AnalyticsRequest(BaseModel):
realm_counts: Json[list[RealmCountDataForAnalytics]]
installation_counts: Json[list[InstallationCountDataForAnalytics]]
- realmauditlog_rows: Optional[Json[list[RealmAuditLogDataForAnalytics]]] = None
+ realmauditlog_rows: Json[list[RealmAuditLogDataForAnalytics]] | None = None
realms: Json[list[RealmDataForAnalytics]]
- version: Optional[Json[str]]
- merge_base: Optional[Json[str]]
- api_feature_level: Optional[Json[int]]
+ version: Json[str] | None
+ merge_base: Json[str] | None
+ api_feature_level: Json[int] | None
class UserDataForRemoteBilling(BaseModel):
@@ -120,7 +120,7 @@ class UserDataForRemoteBilling(BaseModel):
def send_to_push_bouncer(
method: str,
endpoint: str,
- post_data: Union[bytes, Mapping[str, Union[str, int, None, bytes]]],
+ post_data: bytes | Mapping[str, str | int | None | bytes],
extra_headers: Mapping[str, str] = {},
) -> dict[str, object]:
"""While it does actually send the notice, this function has a lot of
@@ -275,7 +275,7 @@ def check_push_notifications_recently_working() -> bool:
def maybe_mark_pushes_disabled(
- e: Union[JsonableError, orjson.JSONDecodeError], logger: logging.Logger
+ e: JsonableError | orjson.JSONDecodeError, logger: logging.Logger
) -> None:
if isinstance(e, PushNotificationBouncerServerError):
# We don't fall through and deactivate the flag, since this is
@@ -355,7 +355,7 @@ def build_analytics_data(
return realm_count_data, installation_count_data, zerver_realmauditlog
-def get_realms_info_for_push_bouncer(realm_id: Optional[int] = None) -> list[RealmDataForAnalytics]:
+def get_realms_info_for_push_bouncer(realm_id: int | None = None) -> list[RealmDataForAnalytics]:
realms = Realm.objects.order_by("id")
if realm_id is not None: # nocoverage
realms = realms.filter(id=realm_id)
diff --git a/zerver/lib/request.py b/zerver/lib/request.py
index 854bfa96385..bcf6b418713 100644
--- a/zerver/lib/request.py
+++ b/zerver/lib/request.py
@@ -11,7 +11,6 @@ from typing import (
Optional,
Sequence,
TypeVar,
- Union,
cast,
overload,
)
@@ -48,23 +47,23 @@ class RequestNotes(BaseNotes[HttpRequest, "RequestNotes"]):
of `assert request_notes.foo is not None` when accessing them.
"""
- client: Optional[Client] = None
- client_name: Optional[str] = None
- client_version: Optional[str] = None
- log_data: Optional[MutableMapping[str, Any]] = None
- rate_limit: Optional[str] = None
- requester_for_logs: Optional[str] = None
+ client: Client | None = None
+ client_name: str | None = None
+ client_version: str | None = None
+ log_data: MutableMapping[str, Any] | None = None
+ rate_limit: str | None = None
+ requester_for_logs: str | None = None
# We use realm_cached to indicate whether the realm is cached or not.
# Because the default value of realm is None, which can indicate "unset"
# and "nonexistence" at the same time.
- realm: Optional[Realm] = None
+ realm: Realm | None = None
has_fetched_realm: bool = False
- set_language: Optional[str] = None
+ set_language: str | None = None
ratelimits_applied: list[rate_limiter.RateLimitResult] = field(default_factory=list)
- query: Optional[str] = None
- error_format: Optional[str] = None
- saved_response: Optional[HttpResponse] = None
- tornado_handler_id: Optional[int] = None
+ query: str | None = None
+ error_format: str | None = None
+ saved_response: HttpResponse | None = None
+ tornado_handler_id: int | None = None
processed_parameters: set[str] = field(default_factory=set)
remote_server: Optional["RemoteZulipServer"] = None
is_webhook_view: bool = False
@@ -131,13 +130,13 @@ class _REQ(Generic[ResultT]):
def __init__(
self,
- whence: Optional[str] = None,
+ whence: str | None = None,
*,
- converter: Optional[Callable[[str, str], ResultT]] = None,
- default: Union[_NotSpecified, ResultT, None] = NotSpecified,
- json_validator: Optional[Validator[ResultT]] = None,
- str_validator: Optional[Validator[ResultT]] = None,
- argument_type: Optional[str] = None,
+ converter: Callable[[str, str], ResultT] | None = None,
+ default: _NotSpecified | ResultT | None = NotSpecified,
+ json_validator: Validator[ResultT] | None = None,
+ str_validator: Validator[ResultT] | None = None,
+ argument_type: str | None = None,
intentionally_undocumented: bool = False,
documentation_pending: bool = False,
aliases: Sequence[str] = [],
@@ -176,7 +175,7 @@ class _REQ(Generic[ResultT]):
json_validator = cast(Callable[[str, object], ResultT], check_anything)
self.post_var_name = whence
- self.func_var_name: Optional[str] = None
+ self.func_var_name: str | None = None
self.converter = converter
self.json_validator = json_validator
self.str_validator = str_validator
@@ -209,11 +208,11 @@ class _REQ(Generic[ResultT]):
# Overload 1: converter
@overload
def REQ(
- whence: Optional[str] = ...,
+ whence: str | None = ...,
*,
converter: Callable[[str, str], ResultT],
default: ResultT = ...,
- argument_type: Optional[Literal["body"]] = ...,
+ argument_type: Literal["body"] | None = ...,
intentionally_undocumented: bool = ...,
documentation_pending: bool = ...,
aliases: Sequence[str] = ...,
@@ -224,11 +223,11 @@ def REQ(
# Overload 2: json_validator
@overload
def REQ(
- whence: Optional[str] = ...,
+ whence: str | None = ...,
*,
default: ResultT = ...,
json_validator: Validator[ResultT],
- argument_type: Optional[Literal["body"]] = ...,
+ argument_type: Literal["body"] | None = ...,
intentionally_undocumented: bool = ...,
documentation_pending: bool = ...,
aliases: Sequence[str] = ...,
@@ -239,10 +238,10 @@ def REQ(
# Overload 3: no converter/json_validator, default: str or unspecified, argument_type=None
@overload
def REQ(
- whence: Optional[str] = ...,
+ whence: str | None = ...,
*,
default: str = ...,
- str_validator: Optional[Validator[str]] = ...,
+ str_validator: Validator[str] | None = ...,
intentionally_undocumented: bool = ...,
documentation_pending: bool = ...,
aliases: Sequence[str] = ...,
@@ -253,21 +252,21 @@ def REQ(
# Overload 4: no converter/validator, default=None, argument_type=None
@overload
def REQ(
- whence: Optional[str] = ...,
+ whence: str | None = ...,
*,
default: None,
- str_validator: Optional[Validator[str]] = ...,
+ str_validator: Validator[str] | None = ...,
intentionally_undocumented: bool = ...,
documentation_pending: bool = ...,
aliases: Sequence[str] = ...,
path_only: bool = ...,
-) -> Optional[str]: ...
+) -> str | None: ...
# Overload 5: argument_type="body"
@overload
def REQ(
- whence: Optional[str] = ...,
+ whence: str | None = ...,
*,
default: ResultT = ...,
argument_type: Literal["body"],
@@ -280,13 +279,13 @@ def REQ(
# Implementation
def REQ(
- whence: Optional[str] = None,
+ whence: str | None = None,
*,
- converter: Optional[Callable[[str, str], ResultT]] = None,
- default: Union[_REQ._NotSpecified, ResultT] = _REQ.NotSpecified,
- json_validator: Optional[Validator[ResultT]] = None,
- str_validator: Optional[Validator[ResultT]] = None,
- argument_type: Optional[str] = None,
+ converter: Callable[[str, str], ResultT] | None = None,
+ default: _REQ._NotSpecified | ResultT = _REQ.NotSpecified,
+ json_validator: Validator[ResultT] | None = None,
+ str_validator: Validator[ResultT] | None = None,
+ argument_type: str | None = None,
intentionally_undocumented: bool = False,
documentation_pending: bool = False,
aliases: Sequence[str] = [],
@@ -379,7 +378,7 @@ def has_request_variables(
continue
assert func_var_name is not None
- post_var_name: Optional[str]
+ post_var_name: str | None
if param.argument_type == "body":
post_var_name = "request"
diff --git a/zerver/lib/response.py b/zerver/lib/response.py
index 59dba4c23be..44ebf7555dd 100644
--- a/zerver/lib/response.py
+++ b/zerver/lib/response.py
@@ -1,4 +1,4 @@
-from typing import Any, Iterator, Mapping, Optional
+from typing import Any, Iterator, Mapping
import orjson
from django.http import HttpRequest, HttpResponse, HttpResponseNotAllowed
@@ -76,7 +76,7 @@ class MutableJsonResponse(HttpResponse):
def json_unauthorized(
- message: Optional[str] = None, www_authenticate: Optional[str] = None
+ message: str | None = None, www_authenticate: str | None = None
) -> HttpResponse:
return json_response_from_error(
UnauthorizedError(msg=message, www_authenticate=www_authenticate)
diff --git a/zerver/lib/rest.py b/zerver/lib/rest.py
index a0486e9826c..309bf6e86d7 100644
--- a/zerver/lib/rest.py
+++ b/zerver/lib/rest.py
@@ -1,5 +1,5 @@
from functools import wraps
-from typing import Callable, Union
+from typing import Callable
from django.http import HttpRequest, HttpResponse, HttpResponseBase
from django.urls import path
@@ -48,7 +48,7 @@ def default_never_cache_responses(
def get_target_view_function_or_response(
request: HttpRequest, rest_dispatch_kwargs: dict[str, object]
-) -> Union[tuple[Callable[..., HttpResponse], set[str]], HttpResponse]:
+) -> tuple[Callable[..., HttpResponse], set[str]] | HttpResponse:
"""Helper for REST API request dispatch. The rest_dispatch_kwargs
parameter is expected to be a dictionary mapping HTTP methods to
a mix of view functions and (view_function, {view_flags}) tuples.
@@ -205,9 +205,6 @@ def rest_dispatch(request: HttpRequest, /, **kwargs: object) -> HttpResponse:
def rest_path(
route: str,
- **handlers: Union[
- Callable[..., HttpResponseBase],
- tuple[Callable[..., HttpResponseBase], set[str]],
- ],
+ **handlers: Callable[..., HttpResponseBase] | tuple[Callable[..., HttpResponseBase], set[str]],
) -> URLPattern:
return path(route, rest_dispatch, handlers)
diff --git a/zerver/lib/retention.py b/zerver/lib/retention.py
index a83888ab55f..17f588eac92 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, Iterable, Mapping, Optional, Union
+from typing import Any, Iterable, Mapping
from django.conf import settings
from django.db import connection, transaction
@@ -95,7 +95,7 @@ def move_rows(
base_model: type[Model],
raw_query: SQL,
*,
- src_db_table: Optional[str] = None,
+ src_db_table: str | None = None,
returning_id: bool = False,
**kwargs: Composable,
) -> list[int]:
@@ -122,7 +122,7 @@ def move_rows(
def run_archiving_in_chunks(
query: SQL,
type: int,
- realm: Optional[Realm] = None,
+ realm: Realm | None = None,
chunk_size: int = MESSAGE_BATCH_SIZE,
**kwargs: Composable,
) -> int:
@@ -455,7 +455,7 @@ def get_realms_and_streams_for_archiving() -> list[tuple[Realm, list[Stream]]]:
def move_messages_to_archive(
- message_ids: list[int], realm: Optional[Realm] = None, chunk_size: int = MESSAGE_BATCH_SIZE
+ message_ids: list[int], realm: Realm | None = None, chunk_size: int = MESSAGE_BATCH_SIZE
) -> None:
# Uses index: zerver_message_pkey
query = SQL(
@@ -674,9 +674,9 @@ def clean_archived_data() -> None:
def parse_message_retention_days(
- value: Union[int, str],
- special_values_map: Mapping[str, Optional[int]],
-) -> Optional[int]:
+ value: int | str,
+ special_values_map: Mapping[str, int | None],
+) -> int | None:
if isinstance(value, str) and value in special_values_map:
return special_values_map[value]
if isinstance(value, str) or value <= 0:
diff --git a/zerver/lib/safe_session_cached_db.py b/zerver/lib/safe_session_cached_db.py
index 9da827133d5..2c3242c4e04 100644
--- a/zerver/lib/safe_session_cached_db.py
+++ b/zerver/lib/safe_session_cached_db.py
@@ -1,5 +1,3 @@
-from typing import Optional
-
from django.contrib.sessions.backends.cached_db import SessionStore as CachedDbSessionStore
from django.db.transaction import get_connection
from typing_extensions import override
@@ -23,6 +21,6 @@ class SessionStore(CachedDbSessionStore):
super().save(must_create)
@override
- def delete(self, session_key: Optional[str] = None) -> None:
+ def delete(self, session_key: str | None = None) -> None:
assert not get_connection().in_atomic_block
super().delete(session_key)
diff --git a/zerver/lib/scheduled_messages.py b/zerver/lib/scheduled_messages.py
index 9245cf31634..83caed11fa3 100644
--- a/zerver/lib/scheduled_messages.py
+++ b/zerver/lib/scheduled_messages.py
@@ -1,5 +1,3 @@
-from typing import Union
-
from django.utils.translation import gettext as _
from zerver.lib.exceptions import ResourceNotFoundError
@@ -21,7 +19,7 @@ def access_scheduled_message(
def get_undelivered_scheduled_messages(
user_profile: UserProfile,
-) -> list[Union[APIScheduledDirectMessageDict, APIScheduledStreamMessageDict]]:
+) -> list[APIScheduledDirectMessageDict | APIScheduledStreamMessageDict]:
scheduled_messages = ScheduledMessage.objects.filter(
realm_id=user_profile.realm_id,
sender=user_profile,
@@ -30,7 +28,7 @@ def get_undelivered_scheduled_messages(
delivered=False,
delivery_type=ScheduledMessage.SEND_LATER,
).order_by("scheduled_timestamp")
- scheduled_message_dicts: list[
- Union[APIScheduledDirectMessageDict, APIScheduledStreamMessageDict]
- ] = [scheduled_message.to_dict() for scheduled_message in scheduled_messages]
+ scheduled_message_dicts: list[APIScheduledDirectMessageDict | APIScheduledStreamMessageDict] = [
+ scheduled_message.to_dict() for scheduled_message in scheduled_messages
+ ]
return scheduled_message_dicts
diff --git a/zerver/lib/scim.py b/zerver/lib/scim.py
index d01830c1a08..24a24a43138 100644
--- a/zerver/lib/scim.py
+++ b/zerver/lib/scim.py
@@ -1,4 +1,4 @@
-from typing import Any, Callable, Optional, Union
+from typing import Any, Callable
import django_scim.constants as scim_constants
import django_scim.exceptions as scim_exceptions
@@ -40,7 +40,7 @@ class ZulipSCIMUser(SCIMUser):
}
ROLE_NAME_TO_TYPE = {v: k for k, v in ROLE_TYPE_TO_NAME.items()}
- def __init__(self, obj: UserProfile, request: Optional[HttpRequest] = None) -> None:
+ def __init__(self, obj: UserProfile, request: HttpRequest | None = None) -> None:
# We keep the function signature from the superclass, but this actually
# shouldn't be called with request being None.
assert request is not None
@@ -60,11 +60,11 @@ class ZulipSCIMUser(SCIMUser):
# in response to a request for the corresponding
# UserProfile fields to change. The .save() method inspects
# these fields an executes the requested changes.
- self._email_new_value: Optional[str] = None
- self._is_active_new_value: Optional[bool] = None
- self._full_name_new_value: Optional[str] = None
- self._role_new_value: Optional[int] = None
- self._password_set_to: Optional[str] = None
+ self._email_new_value: str | None = None
+ self._is_active_new_value: bool | None = None
+ self._full_name_new_value: str | None = None
+ self._role_new_value: int | None = None
+ self._password_set_to: str | None = None
def is_new_user(self) -> bool:
return not bool(self.obj.id)
@@ -209,8 +209,8 @@ class ZulipSCIMUser(SCIMUser):
def handle_replace(
self,
- path: Optional[AttrPath],
- value: Union[str, list[object], dict[AttrPath, object]],
+ path: AttrPath | None,
+ value: str | list[object] | dict[AttrPath, object],
operation: Any,
) -> None:
"""
diff --git a/zerver/lib/scim_filter.py b/zerver/lib/scim_filter.py
index 7bbb101d717..6bd388316b9 100644
--- a/zerver/lib/scim_filter.py
+++ b/zerver/lib/scim_filter.py
@@ -1,5 +1,3 @@
-from typing import Optional
-
from django.http import HttpRequest
from django_scim.filters import UserFilterQuery
@@ -45,7 +43,7 @@ class ZulipUserFilterQuery(UserFilterQuery):
joins = ("INNER JOIN zerver_realm ON zerver_realm.id = realm_id",)
@classmethod
- def get_extras(cls, q: str, request: Optional[HttpRequest] = None) -> tuple[str, list[object]]:
+ def get_extras(cls, q: str, request: HttpRequest | None = None) -> tuple[str, list[object]]:
"""
Return extra SQL and params to be attached to end of current Query's
SQL and params. The return format matches the format that should be used
diff --git a/zerver/lib/send_email.py b/zerver/lib/send_email.py
index dddf54c2f0e..8578dd0c49f 100644
--- a/zerver/lib/send_email.py
+++ b/zerver/lib/send_email.py
@@ -8,7 +8,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, Callable, Mapping, Optional, Union
+from typing import Any, Callable, Mapping
import backoff
import css_inline
@@ -69,7 +69,7 @@ class FromAddress:
@staticmethod
def security_email_from_name(
- language: Optional[str] = None, user_profile: Optional[UserProfile] = None
+ language: str | None = None, user_profile: UserProfile | None = None
) -> str:
if language is None:
assert user_profile is not None
@@ -83,14 +83,14 @@ class FromAddress:
def build_email(
template_prefix: str,
- to_user_ids: Optional[list[int]] = None,
- to_emails: Optional[list[str]] = None,
- from_name: Optional[str] = None,
- from_address: Optional[str] = None,
- reply_to_email: Optional[str] = None,
- language: Optional[str] = None,
+ to_user_ids: list[int] | None = None,
+ to_emails: list[str] | None = None,
+ from_name: str | None = None,
+ from_address: str | None = None,
+ reply_to_email: str | None = None,
+ language: str | None = None,
context: Mapping[str, Any] = {},
- realm: Optional[Realm] = None,
+ realm: Realm | None = None,
) -> EmailMultiAlternatives:
# Callers should pass exactly one of to_user_id and to_email.
assert (to_user_ids is None) ^ (to_emails is None)
@@ -244,17 +244,17 @@ class NoEmailArgumentError(CommandError):
# migration to change or remove any emails in ScheduledEmail.
def send_email(
template_prefix: str,
- to_user_ids: Optional[list[int]] = None,
- to_emails: Optional[list[str]] = None,
- from_name: Optional[str] = None,
- from_address: Optional[str] = None,
- reply_to_email: Optional[str] = None,
- language: Optional[str] = None,
+ to_user_ids: list[int] | None = None,
+ to_emails: list[str] | None = None,
+ from_name: str | None = None,
+ from_address: str | None = None,
+ reply_to_email: str | None = None,
+ language: str | None = None,
context: Mapping[str, Any] = {},
- realm: Optional[Realm] = None,
- connection: Optional[BaseEmailBackend] = None,
+ realm: Realm | None = None,
+ connection: BaseEmailBackend | None = None,
dry_run: bool = False,
- request: Optional[HttpRequest] = None,
+ request: HttpRequest | None = None,
) -> None:
mail = build_email(
template_prefix,
@@ -282,7 +282,7 @@ def send_email(
if request is not None:
cause = f" (triggered from {request.META['REMOTE_ADDR']})"
- logging_recipient: Union[str, list[str]] = mail.to
+ logging_recipient: str | list[str] = mail.to
if realm is not None:
logging_recipient = f"{mail.to} in {realm.string_id}"
@@ -310,7 +310,7 @@ def send_email(
@backoff.on_exception(backoff.expo, OSError, max_tries=MAX_CONNECTION_TRIES, logger=None)
-def initialize_connection(connection: Optional[BaseEmailBackend] = None) -> BaseEmailBackend:
+def initialize_connection(connection: BaseEmailBackend | None = None) -> BaseEmailBackend:
if not connection:
connection = get_connection()
assert connection is not None
@@ -347,11 +347,11 @@ def initialize_connection(connection: Optional[BaseEmailBackend] = None) -> Base
def send_future_email(
template_prefix: str,
realm: Realm,
- to_user_ids: Optional[list[int]] = None,
- to_emails: Optional[list[str]] = None,
- from_name: Optional[str] = None,
- from_address: Optional[str] = None,
- language: Optional[str] = None,
+ to_user_ids: list[int] | None = None,
+ to_emails: list[str] | None = None,
+ from_name: str | None = None,
+ from_address: str | None = None,
+ language: str | None = None,
context: Mapping[str, Any] = {},
delay: timedelta = timedelta(0),
) -> None:
@@ -404,9 +404,9 @@ def send_future_email(
def send_email_to_admins(
template_prefix: str,
realm: Realm,
- from_name: Optional[str] = None,
- from_address: Optional[str] = None,
- language: Optional[str] = None,
+ from_name: str | None = None,
+ from_address: str | None = None,
+ language: str | None = None,
context: Mapping[str, Any] = {},
) -> None:
admins = realm.get_human_admin_users()
@@ -424,9 +424,9 @@ def send_email_to_admins(
def send_email_to_billing_admins_and_realm_owners(
template_prefix: str,
realm: Realm,
- from_name: Optional[str] = None,
- from_address: Optional[str] = None,
- language: Optional[str] = None,
+ from_name: str | None = None,
+ from_address: str | None = None,
+ language: str | None = None,
context: Mapping[str, Any] = {},
) -> None:
send_email(
@@ -449,7 +449,7 @@ def clear_scheduled_invitation_emails(email: str) -> None:
@transaction.atomic(savepoint=False)
-def clear_scheduled_emails(user_id: int, email_type: Optional[int] = None) -> None:
+def clear_scheduled_emails(user_id: int, email_type: int | None = None) -> None:
# We need to obtain a FOR UPDATE lock on the selected rows to keep a concurrent
# execution of this function (or something else) from deleting them before we access
# the .users attribute.
@@ -506,7 +506,7 @@ def deliver_scheduled_emails(email: ScheduledEmail) -> None:
email.delete()
-def get_header(option: Optional[str], header: Optional[str], name: str) -> str:
+def get_header(option: str | None, header: str | None, name: str) -> str:
if option and header:
raise DoubledEmailArgumentError(name)
if not option and not header:
@@ -517,10 +517,10 @@ def get_header(option: Optional[str], header: Optional[str], name: str) -> str:
def custom_email_sender(
markdown_template_path: str,
dry_run: bool,
- subject: Optional[str] = None,
+ subject: str | None = None,
from_address: str = FromAddress.SUPPORT,
- from_name: Optional[str] = None,
- reply_to: Optional[str] = None,
+ from_name: str | None = None,
+ reply_to: str | None = None,
**kwargs: Any,
) -> Callable[..., None]:
with open(markdown_template_path) as f:
@@ -561,7 +561,7 @@ def custom_email_sender(
f.write(get_header(subject, parsed_email_template.get("subject"), "subject"))
def send_one_email(
- context: dict[str, Any], to_user_id: Optional[int] = None, to_email: Optional[str] = None
+ context: dict[str, Any], to_user_id: int | None = None, to_email: str | None = None
) -> None:
assert to_user_id is not None or to_email is not None
with suppress(EmailNotDeliveredError):
@@ -584,7 +584,7 @@ def send_custom_email(
*,
dry_run: bool,
options: dict[str, str],
- add_context: Optional[Callable[[dict[str, object], UserProfile], None]] = None,
+ add_context: Callable[[dict[str, object], UserProfile], None] | None = None,
distinct_email: bool = False,
) -> QuerySet[UserProfile]:
"""
@@ -632,7 +632,7 @@ def send_custom_server_email(
*,
dry_run: bool,
options: dict[str, str],
- add_context: Optional[Callable[[dict[str, object], "RemoteZulipServer"], None]] = None,
+ add_context: Callable[[dict[str, object], "RemoteZulipServer"], None] | None = None,
) -> None:
assert settings.CORPORATE_ENABLED
from corporate.lib.stripe import BILLING_SUPPORT_EMAIL
diff --git a/zerver/lib/server_initialization.py b/zerver/lib/server_initialization.py
index 3f8d0af877d..a4af76378eb 100644
--- a/zerver/lib/server_initialization.py
+++ b/zerver/lib/server_initialization.py
@@ -1,4 +1,4 @@
-from typing import Iterable, Optional
+from typing import Iterable
from django.conf import settings
from django.db import transaction
@@ -79,9 +79,9 @@ def create_internal_realm() -> None:
def create_users(
realm: Realm,
name_list: Iterable[tuple[str, str]],
- tos_version: Optional[str] = None,
- bot_type: Optional[int] = None,
- bot_owner: Optional[UserProfile] = None,
+ tos_version: str | None = None,
+ bot_type: int | None = None,
+ bot_owner: UserProfile | None = None,
) -> None:
user_set = set()
for full_name, email in name_list:
diff --git a/zerver/lib/sessions.py b/zerver/lib/sessions.py
index 4855c0489f5..239eec5af8c 100644
--- a/zerver/lib/sessions.py
+++ b/zerver/lib/sessions.py
@@ -1,7 +1,7 @@
import logging
from datetime import timedelta
from importlib import import_module
-from typing import Any, Mapping, Optional, Protocol, cast
+from typing import Any, Mapping, Protocol, cast
from django.conf import settings
from django.contrib.auth import SESSION_KEY, get_user_model
@@ -21,7 +21,7 @@ class SessionEngine(Protocol):
session_engine = cast(SessionEngine, import_module(settings.SESSION_ENGINE))
-def get_session_dict_user(session_dict: Mapping[str, int]) -> Optional[int]:
+def get_session_dict_user(session_dict: Mapping[str, int]) -> int | None:
# Compare django.contrib.auth._get_user_session_key
try:
pk = get_user_model()._meta.pk
@@ -31,7 +31,7 @@ def get_session_dict_user(session_dict: Mapping[str, int]) -> Optional[int]:
return None
-def get_session_user_id(session: Session) -> Optional[int]:
+def get_session_user_id(session: Session) -> int | None:
return get_session_dict_user(session.get_decoded())
diff --git a/zerver/lib/soft_deactivation.py b/zerver/lib/soft_deactivation.py
index 42e2a2d2409..8f2b8df8519 100644
--- a/zerver/lib/soft_deactivation.py
+++ b/zerver/lib/soft_deactivation.py
@@ -1,7 +1,7 @@
# Documented in https://zulip.readthedocs.io/en/latest/subsystems/sending-messages.html#soft-deactivation
import logging
from collections import defaultdict
-from typing import Any, Iterable, Optional, Sequence, TypedDict, Union
+from typing import Any, Iterable, Sequence, TypedDict
from django.conf import settings
from django.db import transaction
@@ -267,7 +267,7 @@ def do_soft_deactivate_user(user_profile: UserProfile) -> None:
def do_soft_deactivate_users(
- users: Union[Sequence[UserProfile], QuerySet[UserProfile]],
+ users: Sequence[UserProfile] | QuerySet[UserProfile],
) -> list[UserProfile]:
BATCH_SIZE = 100
users_soft_deactivated = []
@@ -297,9 +297,7 @@ def do_soft_deactivate_users(
return users_soft_deactivated
-def do_auto_soft_deactivate_users(
- inactive_for_days: int, realm: Optional[Realm]
-) -> list[UserProfile]:
+def do_auto_soft_deactivate_users(inactive_for_days: int, realm: Realm | None) -> list[UserProfile]:
filter_kwargs: dict[str, Realm] = {}
if realm is not None:
filter_kwargs = dict(user_profile__realm=realm)
@@ -317,7 +315,7 @@ def do_auto_soft_deactivate_users(
return users_deactivated
-def reactivate_user_if_soft_deactivated(user_profile: UserProfile) -> Union[UserProfile, None]:
+def reactivate_user_if_soft_deactivated(user_profile: UserProfile) -> UserProfile | None:
if user_profile.long_term_idle:
add_missing_messages(user_profile)
user_profile.long_term_idle = False
@@ -402,7 +400,7 @@ def queue_soft_reactivation(user_profile_id: int) -> None:
def soft_reactivate_if_personal_notification(
user_profile: UserProfile,
unique_triggers: set[str],
- mentioned_user_group_members_count: Optional[int],
+ mentioned_user_group_members_count: int | None,
) -> None:
"""When we're about to send an email/push notification to a
long_term_idle user, it's very likely that the user will try to
diff --git a/zerver/lib/sqlalchemy_utils.py b/zerver/lib/sqlalchemy_utils.py
index d4b7d3d186a..dcc8e9c0393 100644
--- a/zerver/lib/sqlalchemy_utils.py
+++ b/zerver/lib/sqlalchemy_utils.py
@@ -1,5 +1,5 @@
from contextlib import contextmanager
-from typing import Iterator, Optional
+from typing import Iterator
import sqlalchemy
from django.db import connection
@@ -20,7 +20,7 @@ class NonClosingPool(sqlalchemy.pool.NullPool):
pass
-sqlalchemy_engine: Optional[Engine] = None
+sqlalchemy_engine: Engine | None = None
@contextmanager
diff --git a/zerver/lib/storage.py b/zerver/lib/storage.py
index 04245b89ca8..1710010065e 100644
--- a/zerver/lib/storage.py
+++ b/zerver/lib/storage.py
@@ -25,7 +25,7 @@ else:
class IgnoreBundlesManifestStaticFilesStorage(ManifestStaticFilesStorage):
@override
def hashed_name(
- self, name: str, content: Optional["File[bytes]"] = None, filename: Optional[str] = None
+ self, name: str, content: Optional["File[bytes]"] = None, filename: str | None = None
) -> str:
ext = os.path.splitext(name)[1]
if name.startswith("webpack-bundles"):
diff --git a/zerver/lib/stream_subscription.py b/zerver/lib/stream_subscription.py
index dd4180b2581..af3a011a667 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, Collection, Optional
+from typing import AbstractSet, Any, Collection
from django.db.models import Q, QuerySet
from django_stubs_ext import ValuesQuerySet
@@ -230,7 +230,7 @@ def bulk_get_subscriber_peer_info(
def handle_stream_notifications_compatibility(
- user_profile: Optional[UserProfile],
+ user_profile: UserProfile | None,
stream_dict: dict[str, Any],
notification_settings_null: bool,
) -> None:
diff --git a/zerver/lib/stream_traffic.py b/zerver/lib/stream_traffic.py
index bf1c2801481..fe7e3ff5da0 100644
--- a/zerver/lib/stream_traffic.py
+++ b/zerver/lib/stream_traffic.py
@@ -1,5 +1,4 @@
from datetime import datetime, timedelta
-from typing import Optional
from django.db.models import Sum
from django.utils.timezone import now as timezone_now
@@ -9,7 +8,7 @@ from analytics.models import StreamCount
from zerver.models import Realm
-def get_streams_traffic(stream_ids: set[int], realm: Realm) -> Optional[dict[int, int]]:
+def get_streams_traffic(stream_ids: set[int], realm: Realm) -> dict[int, int] | None:
if realm.is_zephyr_mirror_realm:
# We do not need traffic data for streams in zephyr mirroring realm.
return None
@@ -42,7 +41,7 @@ STREAM_TRAFFIC_CALCULATION_MIN_AGE_DAYS = 7
def get_average_weekly_stream_traffic(
stream_id: int, stream_date_created: datetime, recent_traffic: dict[int, int]
-) -> Optional[int]:
+) -> int | None:
try:
stream_traffic = recent_traffic[stream_id]
except KeyError:
diff --git a/zerver/lib/streams.py b/zerver/lib/streams.py
index 24046a54c01..d9887b96b63 100644
--- a/zerver/lib/streams.py
+++ b/zerver/lib/streams.py
@@ -1,4 +1,4 @@
-from typing import Collection, Optional, TypedDict, Union
+from typing import Collection, TypedDict
from django.db import transaction
from django.db.models import Exists, OuterRef, Q, QuerySet
@@ -65,16 +65,16 @@ class StreamDict(TypedDict, total=False):
invite_only: bool
is_web_public: bool
stream_post_policy: int
- history_public_to_subscribers: Optional[bool]
- message_retention_days: Optional[int]
- can_remove_subscribers_group: Optional[UserGroup]
+ history_public_to_subscribers: bool | None
+ message_retention_days: int | None
+ can_remove_subscribers_group: UserGroup | None
def get_stream_permission_policy_name(
*,
- invite_only: Optional[bool] = None,
- history_public_to_subscribers: Optional[bool] = None,
- is_web_public: Optional[bool] = None,
+ invite_only: bool | None = None,
+ history_public_to_subscribers: bool | None = None,
+ is_web_public: bool | None = None,
) -> str:
policy_name = None
for permission_dict in Stream.PERMISSION_POLICIES.values():
@@ -93,7 +93,7 @@ def get_stream_permission_policy_name(
def get_default_value_for_history_public_to_subscribers(
realm: Realm,
invite_only: bool,
- history_public_to_subscribers: Optional[bool],
+ history_public_to_subscribers: bool | None,
) -> bool:
if invite_only:
if history_public_to_subscribers is None:
@@ -120,7 +120,7 @@ def send_stream_creation_event(
realm: Realm,
stream: Stream,
user_ids: list[int],
- recent_traffic: Optional[dict[int, int]] = None,
+ recent_traffic: dict[int, int] | None = None,
) -> None:
event = dict(type="stream", op="create", streams=[stream_to_dict(stream, recent_traffic)])
send_event_on_commit(realm, event, user_ids)
@@ -134,11 +134,11 @@ def create_stream_if_needed(
invite_only: bool = False,
is_web_public: bool = False,
stream_post_policy: int = Stream.STREAM_POST_POLICY_EVERYONE,
- history_public_to_subscribers: Optional[bool] = None,
+ history_public_to_subscribers: bool | None = None,
stream_description: str = "",
- message_retention_days: Optional[int] = None,
- can_remove_subscribers_group: Optional[UserGroup] = None,
- acting_user: Optional[UserProfile] = None,
+ message_retention_days: int | None = None,
+ can_remove_subscribers_group: UserGroup | None = None,
+ acting_user: UserProfile | None = None,
) -> tuple[Stream, bool]:
history_public_to_subscribers = get_default_value_for_history_public_to_subscribers(
realm, invite_only, history_public_to_subscribers
@@ -199,7 +199,7 @@ def create_stream_if_needed(
def create_streams_if_needed(
- realm: Realm, stream_dicts: list[StreamDict], acting_user: Optional[UserProfile] = None
+ realm: Realm, stream_dicts: list[StreamDict], acting_user: UserProfile | None = None
) -> tuple[list[Stream], list[Stream]]:
"""Note that stream_dict["name"] is assumed to already be stripped of
whitespace"""
@@ -261,7 +261,7 @@ def check_stream_access_based_on_stream_post_policy(sender: UserProfile, stream:
def access_stream_for_send_message(
- sender: UserProfile, stream: Stream, forwarder_user_profile: Optional[UserProfile]
+ sender: UserProfile, stream: Stream, forwarder_user_profile: UserProfile | None
) -> None:
# Our caller is responsible for making sure that `stream` actually
# matches the realm of the sender.
@@ -321,7 +321,7 @@ def access_stream_for_send_message(
)
-def check_for_exactly_one_stream_arg(stream_id: Optional[int], stream: Optional[str]) -> None:
+def check_for_exactly_one_stream_arg(stream_id: int | None, stream: str | None) -> None:
if stream_id is None and stream is None:
# Uses the same translated string as RequestVariableMissingError
# with the stream_id parameter, which is the more common use case.
@@ -333,7 +333,7 @@ def check_for_exactly_one_stream_arg(stream_id: Optional[int], stream: Optional[
def check_stream_access_for_delete_or_update(
- user_profile: UserProfile, stream: Stream, sub: Optional[Subscription] = None
+ user_profile: UserProfile, stream: Stream, sub: Subscription | None = None
) -> None:
error = _("Invalid channel ID")
if stream.realm_id != user_profile.realm_id:
@@ -350,7 +350,7 @@ def check_stream_access_for_delete_or_update(
def access_stream_for_delete_or_update(
user_profile: UserProfile, stream_id: int
-) -> tuple[Stream, Optional[Subscription]]:
+) -> tuple[Stream, Subscription | None]:
try:
stream = Stream.objects.get(id=stream_id)
except Stream.DoesNotExist:
@@ -370,7 +370,7 @@ def access_stream_for_delete_or_update(
def check_basic_stream_access(
user_profile: UserProfile,
stream: Stream,
- sub: Optional[Subscription],
+ sub: Subscription | None,
allow_realm_admin: bool = False,
) -> bool:
# Any realm user, even guests, can access web_public streams.
@@ -403,7 +403,7 @@ def access_stream_common(
error: str,
require_active: bool = True,
allow_realm_admin: bool = False,
-) -> Optional[Subscription]:
+) -> Subscription | None:
"""Common function for backend code where the target use attempts to
access the target stream, returning all the data fetched along the
way. If that user does not have permission to access that stream,
@@ -436,7 +436,7 @@ def access_stream_by_id(
stream_id: int,
require_active: bool = True,
allow_realm_admin: bool = False,
-) -> tuple[Stream, Optional[Subscription]]:
+) -> tuple[Stream, Subscription | None]:
error = _("Invalid channel ID")
try:
stream = get_stream_by_id_in_realm(stream_id, user_profile.realm)
@@ -486,7 +486,7 @@ def check_stream_name_available(realm: Realm, name: str) -> None:
def access_stream_by_name(
user_profile: UserProfile, stream_name: str, allow_realm_admin: bool = False
-) -> tuple[Stream, Optional[Subscription]]:
+) -> tuple[Stream, Subscription | None]:
error = _("Invalid channel name '{channel_name}'").format(channel_name=stream_name)
try:
stream = get_realm_stream(stream_name, user_profile.realm_id)
@@ -633,7 +633,7 @@ def can_access_stream_history_by_id(user_profile: UserProfile, stream_id: int) -
def can_remove_subscribers_from_stream(
- stream: Stream, user_profile: UserProfile, sub: Optional[Subscription]
+ stream: Stream, user_profile: UserProfile, sub: Subscription | None
) -> bool:
if not check_basic_stream_access(user_profile, stream, sub, allow_realm_admin=True):
return False
@@ -801,7 +801,7 @@ def access_default_stream_group_by_id(realm: Realm, group_id: int) -> DefaultStr
)
-def get_stream_by_narrow_operand_access_unchecked(operand: Union[str, int], realm: Realm) -> Stream:
+def get_stream_by_narrow_operand_access_unchecked(operand: str | int, realm: Realm) -> Stream:
"""This is required over access_stream_* in certain cases where
we need the stream data only to prepare a response that user can access
and not send it out to unauthorized recipients.
@@ -822,7 +822,7 @@ def ensure_stream(
invite_only: bool = False,
stream_description: str = "",
*,
- acting_user: Optional[UserProfile],
+ acting_user: UserProfile | None,
) -> Stream:
return create_stream_if_needed(
realm,
@@ -851,9 +851,7 @@ def get_occupied_streams(realm: Realm) -> QuerySet[Stream]:
return occupied_streams
-def stream_to_dict(
- stream: Stream, recent_traffic: Optional[dict[int, int]] = None
-) -> APIStreamDict:
+def stream_to_dict(stream: Stream, recent_traffic: dict[int, int] | None = None) -> APIStreamDict:
if recent_traffic is not None:
stream_weekly_traffic = get_average_weekly_stream_traffic(
stream.id, stream.date_created, recent_traffic
@@ -914,7 +912,7 @@ def get_streams_for_user(
else:
# We construct a query as the or (|) of the various sources
# this user requested streams from.
- query_filter: Optional[Q] = None
+ query_filter: Q | None = None
def add_filter_option(option: Q) -> None:
nonlocal query_filter
diff --git a/zerver/lib/string_validation.py b/zerver/lib/string_validation.py
index e5b387bba12..ba0a95ffefb 100644
--- a/zerver/lib/string_validation.py
+++ b/zerver/lib/string_validation.py
@@ -1,5 +1,4 @@
import unicodedata
-from typing import Optional
from django.utils.translation import gettext as _
@@ -27,7 +26,7 @@ def is_character_printable(char: str) -> bool:
return True
-def check_string_is_printable(var: str) -> Optional[int]:
+def check_string_is_printable(var: str) -> int | None:
# Return position (1-indexed!) of the character which is not
# printable, None if no such character is present.
for i, char in enumerate(var):
diff --git a/zerver/lib/subdomains.py b/zerver/lib/subdomains.py
index de6d297c284..745984b3477 100644
--- a/zerver/lib/subdomains.py
+++ b/zerver/lib/subdomains.py
@@ -1,5 +1,4 @@
import re
-from typing import Optional
from urllib.parse import urlsplit
from django.conf import settings
@@ -55,7 +54,7 @@ def is_root_domain_available() -> bool:
return not Realm.objects.filter(string_id=Realm.SUBDOMAIN_FOR_ROOT_DOMAIN).exists()
-def is_static_or_current_realm_url(url: str, realm: Optional[Realm]) -> bool:
+def is_static_or_current_realm_url(url: str, realm: Realm | None) -> bool:
assert settings.STATIC_URL is not None
split_url = urlsplit(url)
split_static_url = urlsplit(settings.STATIC_URL)
diff --git a/zerver/lib/subscription_info.py b/zerver/lib/subscription_info.py
index 6759c5b43ed..22a77e36a31 100644
--- a/zerver/lib/subscription_info.py
+++ b/zerver/lib/subscription_info.py
@@ -1,6 +1,6 @@
import itertools
from operator import itemgetter
-from typing import Any, Callable, Collection, Iterable, Mapping, Optional
+from typing import Any, Callable, Collection, Iterable, Mapping
from django.core.exceptions import ValidationError
from django.db import connection
@@ -140,7 +140,7 @@ def build_stream_dict_for_sub(
user: UserProfile,
sub_dict: RawSubscriptionDict,
raw_stream_dict: RawStreamDict,
- recent_traffic: Optional[dict[int, int]],
+ recent_traffic: dict[int, int] | None,
) -> SubscriptionStreamDict:
# Handle Stream.API_FIELDS
can_remove_subscribers_group_id = raw_stream_dict["can_remove_subscribers_group_id"]
@@ -215,7 +215,7 @@ def build_stream_dict_for_sub(
def build_stream_dict_for_never_sub(
raw_stream_dict: RawStreamDict,
- recent_traffic: Optional[dict[int, int]],
+ recent_traffic: dict[int, int] | None,
) -> NeverSubscribedStreamDict:
can_remove_subscribers_group_id = raw_stream_dict["can_remove_subscribers_group_id"]
creator_id = raw_stream_dict["creator_id"]
@@ -261,9 +261,7 @@ def build_stream_dict_for_never_sub(
)
-def validate_user_access_to_subscribers(
- user_profile: Optional[UserProfile], stream: Stream
-) -> None:
+def validate_user_access_to_subscribers(user_profile: UserProfile | None, stream: Stream) -> None:
"""Validates whether the user can view the subscribers of a stream. Raises a JsonableError if:
* The user and the stream are in different realms
* The realm is MIT and the stream is not invite only.
@@ -284,7 +282,7 @@ def validate_user_access_to_subscribers(
def validate_user_access_to_subscribers_helper(
- user_profile: Optional[UserProfile],
+ user_profile: UserProfile | None,
stream_dict: Mapping[str, Any],
check_user_subscribed: Callable[[UserProfile], bool],
) -> None:
@@ -412,7 +410,7 @@ def bulk_get_subscriber_user_ids(
def get_subscribers_query(
- stream: Stream, requesting_user: Optional[UserProfile]
+ stream: Stream, requesting_user: UserProfile | None
) -> QuerySet[Subscription]:
"""Build a query to get the subscribers list for a stream, raising a JsonableError if:
diff --git a/zerver/lib/templates.py b/zerver/lib/templates.py
index 63ce43efd67..e3c16320a27 100644
--- a/zerver/lib/templates.py
+++ b/zerver/lib/templates.py
@@ -1,5 +1,5 @@
import time
-from typing import Any, Optional
+from typing import Any
import markdown
import markdown.extensions.admonition
@@ -66,8 +66,8 @@ def display_list(values: list[str], display_limit: int) -> str:
return display_string
-md_extensions: Optional[list[markdown.Extension]] = None
-md_macro_extension: Optional[markdown.Extension] = None
+md_extensions: list[markdown.Extension] | None = None
+md_macro_extension: markdown.Extension | None = None
# Prevent the automatic substitution of macros in these docs. If
# they contain a macro, it is always used literally for documenting
# the macro system.
@@ -85,7 +85,7 @@ docs_without_macros = [
@register.filter(name="render_markdown_path", is_safe=True)
def render_markdown_path(
markdown_file_path: str,
- context: Optional[dict[str, Any]] = None,
+ context: dict[str, Any] | None = None,
integration_doc: bool = False,
help_center: bool = False,
) -> str:
diff --git a/zerver/lib/test_classes.py b/zerver/lib/test_classes.py
index 33c9e560740..72ad307b38d 100644
--- a/zerver/lib/test_classes.py
+++ b/zerver/lib/test_classes.py
@@ -13,7 +13,6 @@ from typing import (
Collection,
Iterator,
Mapping,
- Optional,
Sequence,
Union,
cast,
@@ -192,11 +191,11 @@ class ZulipTestClient(TestClient):
class ZulipTestCaseMixin(SimpleTestCase):
# Ensure that the test system just shows us diffs
- maxDiff: Optional[int] = None
+ maxDiff: int | None = None
# This bypasses BAN_CONSOLE_OUTPUT for the test case when set.
# Override this to verify if the given extra console output matches the
# expectation.
- expected_console_output: Optional[str] = None
+ expected_console_output: str | None = None
client_class = ZulipTestClient
@override
@@ -232,7 +231,7 @@ class ZulipTestCaseMixin(SimpleTestCase):
return get_user(email, realm)
@override
- def run(self, result: Optional[TestResult] = None) -> Optional[TestResult]: # nocoverage
+ def run(self, result: TestResult | None = None) -> TestResult | None: # nocoverage
if not settings.BAN_CONSOLE_OUTPUT and self.expected_console_output is None:
return super().run(result)
extra_output_finder = ExtraConsoleOutputFinder()
@@ -321,7 +320,7 @@ Output:
follow: bool = False,
secure: bool = False,
intentionally_undocumented: bool = False,
- headers: Optional[Mapping[str, Any]] = None,
+ headers: Mapping[str, Any] | None = None,
**extra: str,
) -> "TestHttpResponse":
"""
@@ -349,7 +348,7 @@ Output:
skip_user_agent: bool = False,
follow: bool = False,
secure: bool = False,
- headers: Optional[Mapping[str, Any]] = None,
+ headers: Mapping[str, Any] | None = None,
intentionally_undocumented: bool = False,
**extra: str,
) -> "TestHttpResponse":
@@ -405,7 +404,7 @@ Output:
skip_user_agent: bool = False,
follow: bool = False,
secure: bool = False,
- headers: Optional[Mapping[str, Any]] = None,
+ headers: Mapping[str, Any] | None = None,
**extra: str,
) -> "TestHttpResponse":
encoded = urlencode(info)
@@ -423,7 +422,7 @@ Output:
skip_user_agent: bool = False,
follow: bool = False,
secure: bool = False,
- headers: Optional[Mapping[str, Any]] = None,
+ headers: Mapping[str, Any] | None = None,
**extra: str,
) -> "TestHttpResponse":
data = orjson.dumps(payload)
@@ -447,7 +446,7 @@ Output:
skip_user_agent: bool = False,
follow: bool = False,
secure: bool = False,
- headers: Optional[Mapping[str, Any]] = None,
+ headers: Mapping[str, Any] | None = None,
intentionally_undocumented: bool = False,
**extra: str,
) -> "TestHttpResponse":
@@ -476,7 +475,7 @@ Output:
skip_user_agent: bool = False,
follow: bool = False,
secure: bool = False,
- headers: Optional[Mapping[str, Any]] = None,
+ headers: Mapping[str, Any] | None = None,
**extra: str,
) -> "TestHttpResponse":
django_client = self.client # see WRAPPER_COMMENT
@@ -493,7 +492,7 @@ Output:
skip_user_agent: bool = False,
follow: bool = False,
secure: bool = False,
- headers: Optional[Mapping[str, Any]] = None,
+ headers: Mapping[str, Any] | None = None,
**extra: str,
) -> "TestHttpResponse":
django_client = self.client # see WRAPPER_COMMENT
@@ -504,13 +503,13 @@ Output:
def client_post(
self,
url: str,
- info: Union[str, bytes, Mapping[str, Any]] = {},
+ info: str | bytes | Mapping[str, Any] = {},
skip_user_agent: bool = False,
follow: bool = False,
secure: bool = False,
- headers: Optional[Mapping[str, Any]] = None,
+ headers: Mapping[str, Any] | None = None,
intentionally_undocumented: bool = False,
- content_type: Optional[str] = None,
+ content_type: str | None = None,
**extra: str,
) -> "TestHttpResponse":
django_client = self.client # see WRAPPER_COMMENT
@@ -560,7 +559,7 @@ Output:
skip_user_agent: bool = False,
follow: bool = False,
secure: bool = False,
- headers: Optional[Mapping[str, Any]] = None,
+ headers: Mapping[str, Any] | None = None,
intentionally_undocumented: bool = False,
**extra: str,
) -> "TestHttpResponse":
@@ -694,7 +693,7 @@ Output:
page_params = orjson.loads(page_params_json)
return page_params
- def _get_sentry_params(self, response: "TestHttpResponse") -> Optional[dict[str, Any]]:
+ def _get_sentry_params(self, response: "TestHttpResponse") -> dict[str, Any] | None:
doc = lxml.html.document_fromstring(response.content)
try:
script = cast(lxml.html.HtmlMixin, doc).get_element_by_id("sentry-params")
@@ -714,7 +713,7 @@ Output:
self.assertEqual(page_params["is_spectator"], False)
def login_with_return(
- self, email: str, password: Optional[str] = None, **extra: str
+ self, email: str, password: str | None = None, **extra: str
) -> "TestHttpResponse":
if password is None:
password = initial_password(email)
@@ -810,20 +809,20 @@ Output:
def submit_reg_form_for_user(
self,
email: str,
- password: Optional[str],
+ password: str | None,
realm_name: str = "Zulip Test",
realm_subdomain: str = "zuliptest",
from_confirmation: str = "",
- full_name: Optional[str] = None,
+ full_name: str | None = None,
timezone: str = "",
- realm_in_root_domain: Optional[str] = None,
+ realm_in_root_domain: str | None = None,
default_stream_groups: Sequence[str] = [],
source_realm_id: str = "",
- key: Optional[str] = None,
+ key: str | None = None,
realm_type: int = Realm.ORG_TYPES["business"]["id"],
realm_default_language: str = "en",
- enable_marketing_emails: Optional[bool] = None,
- email_address_visibility: Optional[int] = None,
+ enable_marketing_emails: bool | None = None,
+ email_address_visibility: int | None = None,
is_demo_organization: bool = False,
**extra: str,
) -> "TestHttpResponse":
@@ -880,7 +879,7 @@ Output:
realm_name: str,
realm_type: int = Realm.ORG_TYPES["business"]["id"],
realm_default_language: str = "en",
- realm_in_root_domain: Optional[str] = None,
+ realm_in_root_domain: str | None = None,
) -> "TestHttpResponse":
payload = {
"email": email,
@@ -900,9 +899,9 @@ Output:
self,
email_address: str,
*,
- url_pattern: Optional[str] = None,
- email_subject_contains: Optional[str] = None,
- email_body_contains: Optional[str] = None,
+ url_pattern: str | None = None,
+ email_subject_contains: str | None = None,
+ email_body_contains: str | None = None,
) -> str:
from django.core.mail import outbox
@@ -977,7 +976,7 @@ Output:
self,
identifier: str,
url: str,
- info: Union[str, bytes, Mapping[str, Any]] = {},
+ info: str | bytes | Mapping[str, Any] = {},
**extra: str,
) -> "TestHttpResponse":
extra["HTTP_AUTHORIZATION"] = self.encode_uuid(identifier)
@@ -1011,7 +1010,7 @@ Output:
self,
user: UserProfile,
url: str,
- info: Union[str, bytes, Mapping[str, Any]] = {},
+ info: str | bytes | Mapping[str, Any] = {},
intentionally_undocumented: bool = False,
**extra: str,
) -> "TestHttpResponse":
@@ -1120,7 +1119,7 @@ Output:
stream_name: str,
content: str = "test content",
topic_name: str = "test",
- recipient_realm: Optional[Realm] = None,
+ recipient_realm: Realm | None = None,
*,
allow_unsubscribed_sender: bool = False,
read_by_sender: bool = True,
@@ -1160,7 +1159,7 @@ Output:
def get_messages_response(
self,
- anchor: Union[int, str] = 1,
+ anchor: int | str = 1,
num_before: int = 100,
num_after: int = 100,
use_first_unread_anchor: bool = False,
@@ -1179,7 +1178,7 @@ Output:
def get_messages(
self,
- anchor: Union[str, int] = 1,
+ anchor: str | int = 1,
num_before: int = 100,
num_after: int = 100,
use_first_unread_anchor: bool = False,
@@ -1209,7 +1208,7 @@ Output:
self,
result: Union["TestHttpResponse", HttpResponse],
*,
- ignored_parameters: Optional[list[str]] = None,
+ ignored_parameters: list[str] | None = None,
) -> dict[str, Any]:
"""
Successful POSTs return a 200 and JSON of the form {"result": "success",
@@ -1322,7 +1321,7 @@ Output:
for substring in substrings:
self.assertNotIn(substring, decoded)
- def assert_logged_in_user_id(self, user_id: Optional[int]) -> None:
+ def assert_logged_in_user_id(self, user_id: int | None) -> None:
"""
Verifies the user currently logged in for the test client has the provided user_id.
Pass None to verify no user is logged in.
@@ -1358,10 +1357,10 @@ Output:
def make_stream(
self,
stream_name: str,
- realm: Optional[Realm] = None,
+ realm: Realm | None = None,
invite_only: bool = False,
is_web_public: bool = False,
- history_public_to_subscribers: Optional[bool] = None,
+ history_public_to_subscribers: bool | None = None,
) -> Stream:
if realm is None:
realm = get_realm("zulip")
@@ -1398,7 +1397,7 @@ Output:
INVALID_STREAM_ID = 999999
- def get_stream_id(self, name: str, realm: Optional[Realm] = None) -> int:
+ def get_stream_id(self, name: str, realm: Realm | None = None) -> int:
if not realm:
realm = get_realm("zulip")
try:
@@ -1508,7 +1507,7 @@ Output:
self,
user_profile: UserProfile,
url: str,
- payload: Union[str, dict[str, Any]],
+ payload: str | dict[str, Any],
**extra: str,
) -> Message:
"""
@@ -1647,7 +1646,7 @@ Output:
self.mock_initialize.return_value = self.mock_ldap
def change_ldap_user_attr(
- self, username: str, attr_name: str, attr_value: Union[str, bytes], binary: bool = False
+ self, username: str, attr_name: str, attr_value: str | bytes, binary: bool = False
) -> None:
"""
Method for changing the value of an attribute of a user entry in the mock
@@ -1660,7 +1659,7 @@ Output:
if binary:
with open(attr_value, "rb") as f:
# attr_value should be a path to the file with the binary data
- data: Union[str, bytes] = f.read()
+ data: str | bytes = f.read()
else:
data = attr_value
@@ -1997,7 +1996,7 @@ Output:
self,
direct_members: list[UserProfile],
direct_subgroups: list[NamedUserGroup],
- existing_setting_group: Optional[UserGroup] = None,
+ existing_setting_group: UserGroup | None = None,
) -> UserGroup:
realm = get_realm("zulip")
if existing_setting_group is not None:
@@ -2121,7 +2120,7 @@ class ZulipTestCase(ZulipTestCaseMixin, TestCase):
stream_name: str,
content: str = "test content",
topic_name: str = "test",
- recipient_realm: Optional[Realm] = None,
+ recipient_realm: Realm | None = None,
*,
allow_unsubscribed_sender: bool = False,
read_by_sender: bool = True,
@@ -2242,13 +2241,13 @@ class WebhookTestCase(ZulipTestCase):
important for ensuring we document all fully supported event types.
"""
- CHANNEL_NAME: Optional[str] = None
+ CHANNEL_NAME: str | None = None
TEST_USER_EMAIL = "[email protected]"
URL_TEMPLATE: str
- WEBHOOK_DIR_NAME: Optional[str] = None
+ WEBHOOK_DIR_NAME: str | None = None
# This last parameter is a workaround to handle webhooks that do not
# name the main function api_{WEBHOOK_DIR_NAME}_webhook.
- VIEW_FUNCTION_NAME: Optional[str] = None
+ VIEW_FUNCTION_NAME: str | None = None
@property
def test_user(self) -> UserProfile:
@@ -2314,9 +2313,9 @@ You can fix this by adding "{complete_event_type}" to ALL_EVENT_TYPES for this w
self,
user: UserProfile,
fixture_name: str,
- expected_topic: Optional[str] = None,
- expected_message: Optional[str] = None,
- content_type: Optional[str] = "application/json",
+ expected_topic: str | None = None,
+ expected_message: str | None = None,
+ content_type: str | None = "application/json",
expect_noop: bool = False,
**extra: str,
) -> None:
@@ -2333,9 +2332,9 @@ You can fix this by adding "{complete_event_type}" to ALL_EVENT_TYPES for this w
def check_webhook(
self,
fixture_name: str,
- expected_topic_name: Optional[str] = None,
- expected_message: Optional[str] = None,
- content_type: Optional[str] = "application/json",
+ expected_topic_name: str | None = None,
+ expected_message: str | None = None,
+ content_type: str | None = "application/json",
expect_noop: bool = False,
**extra: str,
) -> None:
@@ -2418,7 +2417,7 @@ one or more new messages.
expected_message: str,
content_type: str = "application/json",
*,
- sender: Optional[UserProfile] = None,
+ sender: UserProfile | None = None,
**extra: str,
) -> Message:
"""
@@ -2471,7 +2470,7 @@ one or more new messages.
return url[:-1] if has_arguments else url
- def get_payload(self, fixture_name: str) -> Union[str, dict[str, str]]:
+ def get_payload(self, fixture_name: str) -> str | dict[str, str]:
"""
Generally webhooks that override this should return dicts."""
return self.get_body(fixture_name)
@@ -2497,8 +2496,8 @@ class MigrationsTestCase(ZulipTransactionTestCase): # nocoverage
assert app_config is not None
return app_config.name
- migrate_from: Optional[str] = None
- migrate_to: Optional[str] = None
+ migrate_from: str | None = None
+ migrate_to: str | None = None
@override
def setUp(self) -> None:
diff --git a/zerver/lib/test_console_output.py b/zerver/lib/test_console_output.py
index cb0a58e16b2..13089a8759f 100644
--- a/zerver/lib/test_console_output.py
+++ b/zerver/lib/test_console_output.py
@@ -5,7 +5,7 @@ import sys
from contextlib import contextmanager
from io import SEEK_SET, TextIOWrapper
from types import TracebackType
-from typing import IO, TYPE_CHECKING, Iterable, Iterator, Optional
+from typing import IO, TYPE_CHECKING, Iterable, Iterator
from typing_extensions import override
@@ -111,7 +111,7 @@ class WrappedIO(IO[bytes]):
return self.stream.tell()
@override
- def truncate(self, size: Optional[int] = None) -> int:
+ def truncate(self, size: int | None = None) -> int:
return self.truncate(size)
@override
@@ -147,9 +147,9 @@ class WrappedIO(IO[bytes]):
@override
def __exit__(
self,
- exc_type: Optional[type[BaseException]],
- exc_value: Optional[BaseException],
- traceback: Optional[TracebackType],
+ exc_type: type[BaseException] | None,
+ exc_value: BaseException | None,
+ traceback: TracebackType | None,
) -> None:
self.stream.__exit__(exc_type, exc_value, traceback)
diff --git a/zerver/lib/test_helpers.py b/zerver/lib/test_helpers.py
index b3519309df0..6c6bf37d07b 100644
--- a/zerver/lib/test_helpers.py
+++ b/zerver/lib/test_helpers.py
@@ -14,7 +14,6 @@ from typing import (
Iterable,
Iterator,
Mapping,
- Optional,
TypeVar,
Union,
cast,
@@ -88,17 +87,17 @@ def stub_event_queue_user_events(
@contextmanager
-def cache_tries_captured() -> Iterator[list[tuple[str, Union[str, list[str]], Optional[str]]]]:
- cache_queries: list[tuple[str, Union[str, list[str]], Optional[str]]] = []
+def cache_tries_captured() -> Iterator[list[tuple[str, str | list[str], str | None]]]:
+ cache_queries: list[tuple[str, str | list[str], str | None]] = []
orig_get = cache.cache_get
orig_get_many = cache.cache_get_many
- def my_cache_get(key: str, cache_name: Optional[str] = None) -> Optional[dict[str, Any]]:
+ def my_cache_get(key: str, cache_name: str | None = None) -> dict[str, Any] | None:
cache_queries.append(("get", key, cache_name))
return orig_get(key, cache_name)
- def my_cache_get_many(keys: list[str], cache_name: Optional[str] = None) -> dict[str, Any]:
+ def my_cache_get_many(keys: list[str], cache_name: str | None = None) -> dict[str, Any]:
cache_queries.append(("getmany", keys, cache_name))
return orig_get_many(keys, cache_name)
@@ -107,15 +106,15 @@ def cache_tries_captured() -> Iterator[list[tuple[str, Union[str, list[str]], Op
@contextmanager
-def simulated_empty_cache() -> Iterator[list[tuple[str, Union[str, list[str]], Optional[str]]]]:
- cache_queries: list[tuple[str, Union[str, list[str]], Optional[str]]] = []
+def simulated_empty_cache() -> Iterator[list[tuple[str, str | list[str], str | None]]]:
+ cache_queries: list[tuple[str, str | list[str], str | None]] = []
- def my_cache_get(key: str, cache_name: Optional[str] = None) -> Optional[dict[str, Any]]:
+ def my_cache_get(key: str, cache_name: str | None = None) -> dict[str, Any] | None:
cache_queries.append(("get", key, cache_name))
return None
def my_cache_get_many(
- keys: list[str], cache_name: Optional[str] = None
+ keys: list[str], cache_name: str | None = None
) -> dict[str, Any]: # nocoverage -- simulated code doesn't use this
cache_queries.append(("getmany", keys, cache_name))
return {}
@@ -141,7 +140,7 @@ def queries_captured(
queries: list[CapturedQuery] = []
- def cursor_execute(self: TimeTrackingCursor, sql: Query, vars: Optional[Params] = None) -> None:
+ def cursor_execute(self: TimeTrackingCursor, sql: Query, vars: Params | None = None) -> None:
start = time.time()
try:
return super(TimeTrackingCursor, self).execute(sql, vars)
@@ -255,7 +254,7 @@ def make_client(name: str) -> Client:
return client
-def find_key_by_email(address: str) -> Optional[str]:
+def find_key_by_email(address: str) -> str | None:
from django.core.mail import outbox
key_regex = re.compile(r"accounts/do_confirm/([a-z0-9]{24})>")
@@ -327,12 +326,12 @@ class HostRequestMock(HttpRequest):
def __init__(
self,
post_data: Mapping[str, Any] = {},
- user_profile: Union[UserProfile, None] = None,
- remote_server: Optional[RemoteZulipServer] = None,
+ user_profile: UserProfile | None = None,
+ remote_server: RemoteZulipServer | None = None,
host: str = settings.EXTERNAL_HOST,
- client_name: Optional[str] = None,
- meta_data: Optional[dict[str, Any]] = None,
- tornado_handler: Optional[AsyncDjangoHandler] = None,
+ client_name: str | None = None,
+ meta_data: dict[str, Any] | None = None,
+ tornado_handler: AsyncDjangoHandler | None = None,
path: str = "",
) -> None:
self.host = host
@@ -390,7 +389,7 @@ def instrument_url(f: UrlFuncT) -> UrlFuncT:
else:
def wrapper(
- self: "ZulipTestCase", url: str, info: object = {}, **kwargs: Union[bool, str]
+ self: "ZulipTestCase", url: str, info: object = {}, **kwargs: bool | str
) -> HttpResponseBase:
start = time.time()
result = f(self, url, info, **kwargs)
@@ -723,7 +722,7 @@ def mock_queue_publish(
def verify_serialize(
queue_name: str,
event: dict[str, object],
- processor: Optional[Callable[[object], None]] = None,
+ processor: Callable[[object], None] | None = None,
) -> None:
marshalled_event = orjson.loads(orjson.dumps(event))
assert marshalled_event == event
diff --git a/zerver/lib/test_runner.py b/zerver/lib/test_runner.py
index 7f458eb6888..5dcdb472b9d 100644
--- a/zerver/lib/test_runner.py
+++ b/zerver/lib/test_runner.py
@@ -3,7 +3,7 @@ import os
import random
import shutil
import unittest
-from typing import Any, Callable, Iterable, Optional, Union
+from typing import Any, Callable, Iterable
from unittest import TestSuite, runner
from unittest.result import TestResult
@@ -34,7 +34,7 @@ from zerver.lib.test_helpers import append_instrumentation_data, write_instrumen
random_id_range_start = str(random.randint(1, 10000000))
-def get_database_id(worker_id: Optional[int] = None) -> str:
+def get_database_id(worker_id: int | None = None) -> str:
if worker_id:
return f"{random_id_range_start}_{worker_id}"
return random_id_range_start
@@ -130,7 +130,7 @@ def run_subsuite(args: SubsuiteArgs) -> tuple[int, Any]:
return subsuite_index, result.events
-def destroy_test_databases(worker_id: Optional[int] = None) -> None:
+def destroy_test_databases(worker_id: int | None = None) -> None:
for alias in connections:
connection = connections[alias]
@@ -181,12 +181,12 @@ def create_test_databases(worker_id: int) -> None:
def init_worker(
counter: "multiprocessing.sharedctypes.Synchronized[int]",
- initial_settings: Optional[dict[str, Any]] = None,
- serialized_contents: Optional[dict[str, str]] = None,
- process_setup: Optional[Callable[..., None]] = None,
- process_setup_args: Optional[tuple[Any, ...]] = None,
- debug_mode: Optional[bool] = None,
- used_aliases: Optional[set[str]] = None,
+ initial_settings: dict[str, Any] | None = None,
+ serialized_contents: dict[str, str] | None = None,
+ process_setup: Callable[..., None] | None = None,
+ process_setup_args: tuple[Any, ...] | None = None,
+ debug_mode: bool | None = None,
+ used_aliases: set[str] | None = None,
) -> None:
"""
This function runs only under parallel mode. It initializes the
@@ -266,7 +266,7 @@ class Runner(DiscoverRunner):
template_rendered.connect(self.on_template_rendered)
@override
- def get_resultclass(self) -> Optional[type[TextTestResult]]:
+ def get_resultclass(self) -> type[TextTestResult] | None:
return TextTestResult
def on_template_rendered(self, sender: Any, context: dict[str, Any], **kwargs: Any) -> None:
@@ -333,9 +333,7 @@ class Runner(DiscoverRunner):
print("Unable to clean up the test run's directory.")
return super().teardown_test_environment(*args, **kwargs)
- def test_imports(
- self, test_labels: list[str], suite: Union[TestSuite, ParallelTestSuite]
- ) -> None:
+ def test_imports(self, test_labels: list[str], suite: TestSuite | ParallelTestSuite) -> None:
prefix = "unittest.loader._FailedTest."
for test_name in get_test_names(suite):
if test_name.startswith(prefix):
@@ -360,7 +358,7 @@ class Runner(DiscoverRunner):
def run_tests(
self,
test_labels: list[str],
- failed_tests_path: Optional[str] = None,
+ failed_tests_path: str | None = None,
full_suite: bool = False,
include_webhooks: bool = False,
**kwargs: Any,
@@ -396,7 +394,7 @@ class Runner(DiscoverRunner):
return failed
-def get_test_names(suite: Union[TestSuite, ParallelTestSuite]) -> list[str]:
+def get_test_names(suite: TestSuite | ParallelTestSuite) -> list[str]:
if isinstance(suite, ParallelTestSuite):
return [name for subsuite in suite.subsuites for name in get_test_names(subsuite)]
else:
diff --git a/zerver/lib/tex.py b/zerver/lib/tex.py
index 6e2b399a911..bf1d26d7663 100644
--- a/zerver/lib/tex.py
+++ b/zerver/lib/tex.py
@@ -1,7 +1,7 @@
import logging
import os
import subprocess
-from typing import Any, Optional
+from typing import Any
import lxml.html
import requests
@@ -19,7 +19,7 @@ class KatexSession(OutgoingSession):
super().__init__(role="katex", timeout=0.5, **kwargs)
-def render_tex(tex: str, is_inline: bool = True) -> Optional[str]:
+def render_tex(tex: str, is_inline: bool = True) -> str | None:
r"""Render a TeX string into HTML using KaTeX
Returns the HTML string, or None if there was some error in the TeX syntax
diff --git a/zerver/lib/thumbnail.py b/zerver/lib/thumbnail.py
index f219739e6ea..c5fefd35632 100644
--- a/zerver/lib/thumbnail.py
+++ b/zerver/lib/thumbnail.py
@@ -1,7 +1,7 @@
import logging
import os
from contextlib import contextmanager
-from typing import Iterator, Optional
+from typing import Iterator
from urllib.parse import urljoin
import pyvips
@@ -132,7 +132,7 @@ def resize_logo(image_data: bytes) -> bytes:
def resize_emoji(
image_data: bytes, emoji_file_name: str, size: int = DEFAULT_EMOJI_SIZE
-) -> tuple[bytes, Optional[bytes]]:
+) -> tuple[bytes, bytes | None]:
# Square brackets are used for providing options to libvips' save
# operation; the extension on the filename comes from reversing
# the content-type, which removes most of the attacker control of
diff --git a/zerver/lib/timeout.py b/zerver/lib/timeout.py
index dc55524b5c9..395e95fb052 100644
--- a/zerver/lib/timeout.py
+++ b/zerver/lib/timeout.py
@@ -4,7 +4,7 @@ import sys
import threading
import time
from types import TracebackType
-from typing import Callable, Optional, TypeVar
+from typing import Callable, TypeVar
from typing_extensions import override
@@ -41,11 +41,11 @@ def unsafe_timeout(timeout: float, func: Callable[[], ResultT]) -> ResultT:
class TimeoutThread(threading.Thread):
def __init__(self) -> None:
threading.Thread.__init__(self)
- self.result: Optional[ResultT] = None
+ self.result: ResultT | None = None
self.exc_info: tuple[
- Optional[type[BaseException]],
- Optional[BaseException],
- Optional[TracebackType],
+ type[BaseException] | None,
+ BaseException | None,
+ TracebackType | None,
] = (None, None, None)
# Don't block the whole program from exiting
diff --git a/zerver/lib/topic.py b/zerver/lib/topic.py
index b87b049a807..8e755728a65 100644
--- a/zerver/lib/topic.py
+++ b/zerver/lib/topic.py
@@ -1,5 +1,5 @@
from datetime import datetime
-from typing import Any, Callable, Optional
+from typing import Any, Callable
import orjson
from django.db import connection
@@ -45,7 +45,7 @@ def get_topic_from_message_info(message_info: dict[str, Any]) -> str:
return message_info["subject"]
-def REQ_topic() -> Optional[str]:
+def REQ_topic() -> str | None:
# REQ handlers really return a REQ, but we
# lie to make the rest of the type matching work.
return REQ(
@@ -131,8 +131,8 @@ def update_messages_for_topic_edit(
edited_message: Message,
propagate_mode: str,
orig_topic_name: str,
- topic_name: Optional[str],
- new_stream: Optional[Stream],
+ topic_name: str | None,
+ new_stream: Stream | None,
old_stream: Stream,
edit_history_event: EditHistoryEvent,
last_edit_time: datetime,
diff --git a/zerver/lib/typed_endpoint.py b/zerver/lib/typed_endpoint.py
index 9a60c142764..70c1024987c 100644
--- a/zerver/lib/typed_endpoint.py
+++ b/zerver/lib/typed_endpoint.py
@@ -4,7 +4,7 @@ import types
from dataclasses import dataclass
from enum import Enum, auto
from functools import wraps
-from typing import Callable, Generic, Optional, Sequence, TypeVar, Union
+from typing import Callable, Generic, Sequence, TypeVar, Union
from django.http import HttpRequest
from django.utils.translation import gettext as _
@@ -89,7 +89,7 @@ class ApiParamConfig:
"whence".
"""
- whence: Optional[str] = None
+ whence: str | None = None
path_only: bool = False
argument_type_is_body: bool = False
documentation_status: DocumentationStatus = DOCUMENTED
@@ -105,7 +105,7 @@ JsonBodyPayload: TypeAlias = Annotated[Json[T], ApiParamConfig(argument_type_is_
# request by the @typed_endpoint decorator.
PathOnly: TypeAlias = Annotated[T, ApiParamConfig(path_only=True)]
OptionalTopic: TypeAlias = Annotated[
- Optional[str],
+ str | None,
StringConstraints(strip_whitespace=True),
ApiParamConfig(whence="topic", aliases=("subject",)),
]
@@ -133,7 +133,7 @@ NotSpecified = _NotSpecified()
@dataclass(frozen=True)
class FuncParam(Generic[T]):
# Default value of the parameter.
- default: Union[T, _NotSpecified]
+ default: T | _NotSpecified
# Name of the function parameter as defined in the original function.
param_name: str
# Inspected the underlying type of the parameter by unwrapping the Annotated
@@ -232,7 +232,7 @@ def parse_single_parameter(
), API_PARAM_CONFIG_USAGE_HINT.format(param_name=param_name, param_type=param_type)
param_type = inner_type
- param_config: Optional[ApiParamConfig] = None
+ param_config: ApiParamConfig | None = None
if is_annotated(param_type):
# The first type is the underlying type of the parameter, the rest are
# metadata attached to Annotated. Note that we do not transform
diff --git a/zerver/lib/typed_endpoint_validators.py b/zerver/lib/typed_endpoint_validators.py
index 286e90bc4a9..f5e37b3b7d5 100644
--- a/zerver/lib/typed_endpoint_validators.py
+++ b/zerver/lib/typed_endpoint_validators.py
@@ -1,5 +1,3 @@
-from typing import Optional
-
from django.core.exceptions import ValidationError
from django.core.validators import URLValidator
from django.utils.translation import gettext as _
@@ -9,7 +7,7 @@ from pydantic_core import PydanticCustomError
# of the specified length. So, we need to create a custom validator for that.
-def check_string_fixed_length(string: str, length: int) -> Optional[str]:
+def check_string_fixed_length(string: str, length: int) -> str | None:
if len(string) != length:
raise PydanticCustomError(
"string_fixed_length",
diff --git a/zerver/lib/types.py b/zerver/lib/types.py
index fee4e2433e2..d33a6b05aa6 100644
--- a/zerver/lib/types.py
+++ b/zerver/lib/types.py
@@ -1,6 +1,6 @@
from dataclasses import dataclass, field
from datetime import datetime
-from typing import Any, Callable, Optional, TypeVar, Union
+from typing import Any, Callable, TypeVar
from django_stubs_ext import StrPromise
from typing_extensions import NotRequired, TypeAlias, TypedDict
@@ -13,7 +13,7 @@ ExtendedValidator: TypeAlias = Callable[[str, str, object], str]
RealmUserValidator: TypeAlias = Callable[[int, object, bool], list[int]]
-ProfileDataElementValue: TypeAlias = Union[str, list[int]]
+ProfileDataElementValue: TypeAlias = str | list[int]
class ProfileDataElementBase(TypedDict, total=False):
@@ -28,8 +28,8 @@ class ProfileDataElementBase(TypedDict, total=False):
class ProfileDataElement(ProfileDataElementBase):
- value: Optional[ProfileDataElementValue]
- rendered_value: Optional[str]
+ value: ProfileDataElementValue | None
+ rendered_value: str | None
class ProfileDataElementUpdateDict(TypedDict):
@@ -47,7 +47,7 @@ ExtendedFieldElement: TypeAlias = tuple[
]
UserFieldElement: TypeAlias = tuple[int, StrPromise, RealmUserValidator, Callable[[Any], Any], str]
-ProfileFieldData: TypeAlias = dict[str, Union[dict[str, str], str]]
+ProfileFieldData: TypeAlias = dict[str, dict[str, str] | str]
class UserDisplayRecipient(TypedDict):
@@ -57,7 +57,7 @@ class UserDisplayRecipient(TypedDict):
is_mirror_dummy: bool
-DisplayRecipientT: TypeAlias = Union[str, list[UserDisplayRecipient]]
+DisplayRecipientT: TypeAlias = str | list[UserDisplayRecipient]
class LinkifierDict(TypedDict):
@@ -90,15 +90,15 @@ class EditHistoryEvent(TypedDict, total=False):
# predating March 2017, when we started tracking the person who
# made edits, which is still years after the introduction of topic
# editing support in Zulip.
- user_id: Optional[int]
+ user_id: int | None
timestamp: int
prev_stream: int
stream: int
prev_topic: str
topic: str
prev_content: str
- prev_rendered_content: Optional[str]
- prev_rendered_content_version: Optional[int]
+ prev_rendered_content: str | None
+ prev_rendered_content_version: int | None
class FormattedEditHistoryEvent(TypedDict, total=False):
@@ -107,7 +107,7 @@ class FormattedEditHistoryEvent(TypedDict, total=False):
"""
# See EditHistoryEvent for details on when this can be null.
- user_id: Optional[int]
+ user_id: int | None
timestamp: int
prev_stream: int
stream: int
@@ -115,8 +115,8 @@ class FormattedEditHistoryEvent(TypedDict, total=False):
topic: str
prev_content: str
content: str
- prev_rendered_content: Optional[str]
- rendered_content: Optional[str]
+ prev_rendered_content: str | None
+ rendered_content: str | None
content_html_diff: str
@@ -139,15 +139,15 @@ class RawStreamDict(TypedDict):
"""
can_remove_subscribers_group_id: int
- creator_id: Optional[int]
+ creator_id: int | None
date_created: datetime
description: str
- first_message_id: Optional[int]
+ first_message_id: int | None
history_public_to_subscribers: bool
id: int
invite_only: bool
is_web_public: bool
- message_retention_days: Optional[int]
+ message_retention_days: int | None
name: str
rendered_description: str
stream_post_policy: int
@@ -159,15 +159,15 @@ class RawSubscriptionDict(TypedDict):
"""
active: bool
- audible_notifications: Optional[bool]
+ audible_notifications: bool | None
color: str
- desktop_notifications: Optional[bool]
- email_notifications: Optional[bool]
+ desktop_notifications: bool | None
+ email_notifications: bool | None
is_muted: bool
pin_to_top: bool
- push_notifications: Optional[bool]
+ push_notifications: bool | None
recipient_id: int
- wildcard_mentions_notify: Optional[bool]
+ wildcard_mentions_notify: bool | None
class SubscriptionStreamDict(TypedDict):
@@ -177,49 +177,49 @@ class SubscriptionStreamDict(TypedDict):
computed fields.
"""
- audible_notifications: Optional[bool]
+ audible_notifications: bool | None
can_remove_subscribers_group: int
color: str
- creator_id: Optional[int]
+ creator_id: int | None
date_created: int
description: str
- desktop_notifications: Optional[bool]
- email_notifications: Optional[bool]
- first_message_id: Optional[int]
+ desktop_notifications: bool | None
+ email_notifications: bool | None
+ first_message_id: int | None
history_public_to_subscribers: bool
in_home_view: bool
invite_only: bool
is_announcement_only: bool
is_muted: bool
is_web_public: bool
- message_retention_days: Optional[int]
+ message_retention_days: int | None
name: str
pin_to_top: bool
- push_notifications: Optional[bool]
+ push_notifications: bool | None
rendered_description: str
stream_id: int
stream_post_policy: int
- stream_weekly_traffic: Optional[int]
+ stream_weekly_traffic: int | None
subscribers: NotRequired[list[int]]
- wildcard_mentions_notify: Optional[bool]
+ wildcard_mentions_notify: bool | None
class NeverSubscribedStreamDict(TypedDict):
can_remove_subscribers_group: int
- creator_id: Optional[int]
+ creator_id: int | None
date_created: int
description: str
- first_message_id: Optional[int]
+ first_message_id: int | None
history_public_to_subscribers: bool
invite_only: bool
is_announcement_only: bool
is_web_public: bool
- message_retention_days: Optional[int]
+ message_retention_days: int | None
name: str
rendered_description: str
stream_id: int
stream_post_policy: int
- stream_weekly_traffic: Optional[int]
+ stream_weekly_traffic: int | None
subscribers: NotRequired[list[int]]
@@ -230,14 +230,14 @@ class DefaultStreamDict(TypedDict):
"""
can_remove_subscribers_group: int
- creator_id: Optional[int]
+ creator_id: int | None
date_created: int
description: str
- first_message_id: Optional[int]
+ first_message_id: int | None
history_public_to_subscribers: bool
invite_only: bool
is_web_public: bool
- message_retention_days: Optional[int]
+ message_retention_days: int | None
name: str
rendered_description: str
stream_id: int # `stream_id`` represents `id` of the `Stream` object in `API_FIELDS`
@@ -248,7 +248,7 @@ class DefaultStreamDict(TypedDict):
class APIStreamDict(DefaultStreamDict):
- stream_weekly_traffic: Optional[int]
+ stream_weekly_traffic: int | None
class APISubscriptionDict(APIStreamDict):
@@ -256,14 +256,14 @@ class APISubscriptionDict(APIStreamDict):
`zerver.models.Subscription.API_FIELDS` and several additional fields.
"""
- audible_notifications: Optional[bool]
+ audible_notifications: bool | None
color: str
- desktop_notifications: Optional[bool]
- email_notifications: Optional[bool]
+ desktop_notifications: bool | None
+ email_notifications: bool | None
is_muted: bool
pin_to_top: bool
- push_notifications: Optional[bool]
- wildcard_mentions_notify: Optional[bool]
+ push_notifications: bool | None
+ wildcard_mentions_notify: bool | None
# Computed fields not specified in `Subscription.API_FIELDS`
in_home_view: bool
subscribers: list[int]
@@ -292,7 +292,7 @@ class GroupPermissionSetting:
allow_everyone_group: bool
default_group_name: str
id_field_name: str
- default_for_system_groups: Optional[str] = None
+ default_for_system_groups: str | None = None
allowed_system_groups: list[str] = field(default_factory=list)
@@ -315,13 +315,13 @@ class RawUserDict(TypedDict):
is_bot: bool
timezone: str
date_joined: datetime
- bot_owner_id: Optional[int]
+ bot_owner_id: int | None
delivery_email: str
- bot_type: Optional[int]
+ bot_type: int | None
long_term_idle: bool
email_address_visibility: int
class RemoteRealmDictValue(TypedDict):
can_push: bool
- expected_end_timestamp: Optional[int]
+ expected_end_timestamp: int | None
diff --git a/zerver/lib/upload/__init__.py b/zerver/lib/upload/__init__.py
index 5e088c31994..a3659c0ea50 100644
--- a/zerver/lib/upload/__init__.py
+++ b/zerver/lib/upload/__init__.py
@@ -4,7 +4,7 @@ import os
import re
import unicodedata
from datetime import datetime
-from typing import IO, Any, BinaryIO, Callable, Iterator, Optional, Union
+from typing import IO, Any, BinaryIO, Callable, Iterator
from urllib.parse import unquote, urljoin
from django.conf import settings
@@ -128,7 +128,7 @@ def upload_message_attachment(
content_type: str,
file_data: bytes,
user_profile: UserProfile,
- target_realm: Optional[Realm] = None,
+ target_realm: Realm | None = None,
) -> str:
if target_realm is None:
target_realm = user_profile.realm
@@ -154,7 +154,7 @@ def upload_message_attachment(
def claim_attachment(
path_id: str,
- message: Union[Message, ScheduledMessage],
+ message: Message | ScheduledMessage,
is_message_realm_public: bool,
is_message_web_public: bool = False,
) -> Attachment:
@@ -211,8 +211,8 @@ def write_avatar_images(
user_profile: UserProfile,
image_data: bytes,
*,
- content_type: Optional[str],
- backend: Optional[ZulipUploadBackend] = None,
+ content_type: str | None,
+ backend: ZulipUploadBackend | None = None,
future: bool = True,
) -> None:
if backend is None:
@@ -245,8 +245,8 @@ def write_avatar_images(
def upload_avatar_image(
user_file: IO[bytes],
user_profile: UserProfile,
- content_type: Optional[str] = None,
- backend: Optional[ZulipUploadBackend] = None,
+ content_type: str | None = None,
+ backend: ZulipUploadBackend | None = None,
future: bool = True,
) -> None:
if content_type is None:
@@ -335,7 +335,7 @@ def upload_emoji_image(
emoji_file_name: str,
user_profile: UserProfile,
content_type: str,
- backend: Optional[ZulipUploadBackend] = None,
+ backend: ZulipUploadBackend | None = None,
) -> bool:
if backend is None:
backend = upload_backend
@@ -433,12 +433,12 @@ def handle_reupload_emojis_event(realm: Realm, logger: logging.Logger) -> None:
def upload_export_tarball(
- realm: Realm, tarball_path: str, percent_callback: Optional[Callable[[Any], None]] = None
+ realm: Realm, tarball_path: str, percent_callback: Callable[[Any], None] | None = None
) -> str:
return upload_backend.upload_export_tarball(
realm, tarball_path, percent_callback=percent_callback
)
-def delete_export_tarball(export_path: str) -> Optional[str]:
+def delete_export_tarball(export_path: str) -> str | None:
return upload_backend.delete_export_tarball(export_path)
diff --git a/zerver/lib/upload/base.py b/zerver/lib/upload/base.py
index 770da1c8dba..bf0a0cb5fb4 100644
--- a/zerver/lib/upload/base.py
+++ b/zerver/lib/upload/base.py
@@ -1,6 +1,6 @@
import os
from datetime import datetime
-from typing import IO, Any, BinaryIO, Callable, Iterator, Optional
+from typing import IO, Any, BinaryIO, Callable, Iterator
from zerver.models import Realm, UserProfile
@@ -75,7 +75,7 @@ class ZulipUploadBackend:
*,
user_profile: UserProfile,
image_data: bytes,
- content_type: Optional[str],
+ content_type: str | None,
future: bool = True,
) -> None:
raise NotImplementedError
@@ -110,7 +110,7 @@ class ZulipUploadBackend:
def upload_single_emoji_image(
self,
path: str,
- content_type: Optional[str],
+ content_type: str | None,
user_profile: UserProfile,
image_data: bytes,
) -> None:
@@ -124,9 +124,9 @@ class ZulipUploadBackend:
self,
realm: Realm,
tarball_path: str,
- percent_callback: Optional[Callable[[Any], None]] = None,
+ percent_callback: Callable[[Any], None] | None = None,
) -> str:
raise NotImplementedError
- def delete_export_tarball(self, export_path: str) -> Optional[str]:
+ def delete_export_tarball(self, export_path: str) -> str | None:
raise NotImplementedError
diff --git a/zerver/lib/upload/local.py b/zerver/lib/upload/local.py
index 8ce6c57bf0a..2e705c87454 100644
--- a/zerver/lib/upload/local.py
+++ b/zerver/lib/upload/local.py
@@ -4,7 +4,7 @@ import random
import secrets
import shutil
from datetime import datetime
-from typing import IO, Any, BinaryIO, Callable, Iterator, Literal, Optional
+from typing import IO, Any, BinaryIO, Callable, Iterator, Literal
from django.conf import settings
from typing_extensions import override
@@ -122,7 +122,7 @@ class LocalUploadBackend(ZulipUploadBackend):
*,
user_profile: UserProfile,
image_data: bytes,
- content_type: Optional[str],
+ content_type: str | None,
future: bool = True,
) -> None:
write_local_file("avatars", file_path, image_data)
@@ -193,7 +193,7 @@ class LocalUploadBackend(ZulipUploadBackend):
@override
def upload_single_emoji_image(
- self, path: str, content_type: Optional[str], user_profile: UserProfile, image_data: bytes
+ self, path: str, content_type: str | None, user_profile: UserProfile, image_data: bytes
) -> None:
write_local_file("avatars", path, image_data)
@@ -207,7 +207,7 @@ class LocalUploadBackend(ZulipUploadBackend):
self,
realm: Realm,
tarball_path: str,
- percent_callback: Optional[Callable[[Any], None]] = None,
+ percent_callback: Callable[[Any], None] | None = None,
) -> str:
path = os.path.join(
"exports",
@@ -222,7 +222,7 @@ class LocalUploadBackend(ZulipUploadBackend):
return public_url
@override
- def delete_export_tarball(self, export_path: str) -> Optional[str]:
+ def delete_export_tarball(self, export_path: str) -> str | None:
# Get the last element of a list in the form ['user_avatars', '<file_path>']
assert export_path.startswith("/")
file_path = export_path[1:].split("/", 1)[-1]
diff --git a/zerver/lib/upload/s3.py b/zerver/lib/upload/s3.py
index 9f0d1260041..66e2d3d21d2 100644
--- a/zerver/lib/upload/s3.py
+++ b/zerver/lib/upload/s3.py
@@ -2,7 +2,7 @@ import logging
import os
import secrets
from datetime import datetime
-from typing import IO, Any, BinaryIO, Callable, Iterator, Literal, Optional
+from typing import IO, Any, BinaryIO, Callable, Iterator, Literal
from urllib.parse import urljoin, urlsplit, urlunsplit
import boto3
@@ -62,7 +62,7 @@ def get_bucket(bucket_name: str, authed: bool = True) -> Bucket:
def upload_image_to_s3(
bucket: Bucket,
file_name: str,
- content_type: Optional[str],
+ content_type: str | None,
user_profile: UserProfile,
contents: bytes,
*,
@@ -74,8 +74,8 @@ def upload_image_to_s3(
"STANDARD",
"STANDARD_IA",
] = "STANDARD",
- cache_control: Optional[str] = None,
- extra_metadata: Optional[dict[str, str]] = None,
+ cache_control: str | None = None,
+ extra_metadata: dict[str, str] | None = None,
) -> None:
key = bucket.Object(file_name)
metadata = {
@@ -270,7 +270,7 @@ class S3UploadBackend(ZulipUploadBackend):
*,
user_profile: UserProfile,
image_data: bytes,
- content_type: Optional[str],
+ content_type: str | None,
future: bool = True,
) -> None:
extra_metadata = {"avatar_version": str(user_profile.avatar_version + (1 if future else 0))}
@@ -376,7 +376,7 @@ class S3UploadBackend(ZulipUploadBackend):
@override
def upload_single_emoji_image(
- self, path: str, content_type: Optional[str], user_profile: UserProfile, image_data: bytes
+ self, path: str, content_type: str | None, user_profile: UserProfile, image_data: bytes
) -> None:
upload_image_to_s3(
self.avatar_bucket,
@@ -395,9 +395,9 @@ class S3UploadBackend(ZulipUploadBackend):
@override
def upload_export_tarball(
self,
- realm: Optional[Realm],
+ realm: Realm | None,
tarball_path: str,
- percent_callback: Optional[Callable[[Any], None]] = None,
+ percent_callback: Callable[[Any], None] | None = None,
) -> str:
# We use the avatar bucket, because it's world-readable.
key = self.avatar_bucket.Object(
@@ -413,7 +413,7 @@ class S3UploadBackend(ZulipUploadBackend):
return public_url
@override
- def delete_export_tarball(self, export_path: str) -> Optional[str]:
+ def delete_export_tarball(self, export_path: str) -> str | None:
assert export_path.startswith("/")
path_id = export_path[1:]
if self.delete_file_from_s3(path_id, self.avatar_bucket):
diff --git a/zerver/lib/url_preview/oembed.py b/zerver/lib/url_preview/oembed.py
index 0fe8de3a2b6..697d23f30d8 100644
--- a/zerver/lib/url_preview/oembed.py
+++ b/zerver/lib/url_preview/oembed.py
@@ -1,5 +1,4 @@
import json
-from typing import Optional
import requests
from pyoembed import PyOembedException, oEmbed
@@ -7,7 +6,7 @@ from pyoembed import PyOembedException, oEmbed
from zerver.lib.url_preview.types import UrlEmbedData, UrlOEmbedData
-def get_oembed_data(url: str, maxwidth: int = 640, maxheight: int = 480) -> Optional[UrlEmbedData]:
+def get_oembed_data(url: str, maxwidth: int = 640, maxheight: int = 480) -> UrlEmbedData | None:
try:
data = oEmbed(url, maxwidth=maxwidth, maxheight=maxheight)
except (PyOembedException, json.decoder.JSONDecodeError, requests.exceptions.ConnectionError):
diff --git a/zerver/lib/url_preview/parsers/base.py b/zerver/lib/url_preview/parsers/base.py
index a70675415d8..921349f3d74 100644
--- a/zerver/lib/url_preview/parsers/base.py
+++ b/zerver/lib/url_preview/parsers/base.py
@@ -1,11 +1,10 @@
import cgi
-from typing import Optional
from zerver.lib.url_preview.types import UrlEmbedData
class BaseParser:
- def __init__(self, html_source: bytes, content_type: Optional[str]) -> None:
+ def __init__(self, html_source: bytes, content_type: str | None) -> None:
# We import BeautifulSoup here, because it's not used by most
# processes in production, and bs4 is big enough that
# importing it adds 10s of milliseconds to manage.py startup.
diff --git a/zerver/lib/url_preview/parsers/generic.py b/zerver/lib/url_preview/parsers/generic.py
index afea17c7d3b..d330a21b378 100644
--- a/zerver/lib/url_preview/parsers/generic.py
+++ b/zerver/lib/url_preview/parsers/generic.py
@@ -1,4 +1,3 @@
-from typing import Optional
from urllib.parse import urlsplit
from bs4.element import Tag
@@ -17,7 +16,7 @@ class GenericParser(BaseParser):
image=self._get_image(),
)
- def _get_title(self) -> Optional[str]:
+ def _get_title(self) -> str | None:
soup = self._soup
if soup.title and soup.title.text != "":
return soup.title.text
@@ -25,7 +24,7 @@ class GenericParser(BaseParser):
return soup.h1.text
return None
- def _get_description(self) -> Optional[str]:
+ def _get_description(self) -> str | None:
soup = self._soup
meta_description = soup.find("meta", attrs={"name": "description"})
if isinstance(meta_description, Tag) and meta_description.get("content", "") != "":
@@ -41,7 +40,7 @@ class GenericParser(BaseParser):
return first_p.text
return None
- def _get_image(self) -> Optional[str]:
+ def _get_image(self) -> str | None:
"""
Finding a first image after the h1 header.
Presumably it will be the main image.
diff --git a/zerver/lib/url_preview/preview.py b/zerver/lib/url_preview/preview.py
index edae547d6be..8781cce7cbd 100644
--- a/zerver/lib/url_preview/preview.py
+++ b/zerver/lib/url_preview/preview.py
@@ -1,5 +1,5 @@
import re
-from typing import Any, Callable, Match, Optional
+from typing import Any, Callable, Match
from urllib.parse import urljoin
import magic
@@ -40,7 +40,7 @@ class PreviewSession(OutgoingSession):
super().__init__(role="preview", timeout=TIMEOUT, headers=HEADERS)
-def is_link(url: str) -> Optional[Match[str]]:
+def is_link(url: str) -> Match[str] | None:
return link_regex.match(smart_str(url))
@@ -82,9 +82,7 @@ def catch_network_errors(func: Callable[..., Any]) -> Callable[..., Any]:
@catch_network_errors
@cache_with_key(preview_url_cache_key)
-def get_link_embed_data(
- url: str, maxwidth: int = 640, maxheight: int = 480
-) -> Optional[UrlEmbedData]:
+def get_link_embed_data(url: str, maxwidth: int = 640, maxheight: int = 480) -> UrlEmbedData | None:
if not is_link(url):
return None
diff --git a/zerver/lib/url_preview/types.py b/zerver/lib/url_preview/types.py
index 853a535555b..5a5af8401bb 100644
--- a/zerver/lib/url_preview/types.py
+++ b/zerver/lib/url_preview/types.py
@@ -1,14 +1,14 @@
from dataclasses import dataclass
-from typing import Literal, Optional
+from typing import Literal
@dataclass
class UrlEmbedData:
- type: Optional[str] = None
- html: Optional[str] = None
- title: Optional[str] = None
- description: Optional[str] = None
- image: Optional[str] = None
+ type: str | None = None
+ html: str | None = None
+ title: str | None = None
+ description: str | None = None
+ image: str | None = None
def merge(self, other: "UrlEmbedData") -> None:
if self.title is None and other.title is not None:
@@ -22,4 +22,4 @@ class UrlEmbedData:
@dataclass
class UrlOEmbedData(UrlEmbedData):
type: Literal["photo", "video"]
- html: Optional[str] = None
+ html: str | None = None
diff --git a/zerver/lib/user_groups.py b/zerver/lib/user_groups.py
index 7fcefe296f3..130768a89db 100644
--- a/zerver/lib/user_groups.py
+++ b/zerver/lib/user_groups.py
@@ -1,6 +1,6 @@
from contextlib import contextmanager
from dataclasses import asdict, dataclass
-from typing import Collection, Iterable, Iterator, Mapping, Optional, TypedDict, Union
+from typing import Collection, Iterable, Iterator, Mapping, TypedDict
from django.conf import settings
from django.db import connection, transaction
@@ -38,8 +38,8 @@ class AnonymousSettingGroupDict:
@dataclass
class GroupSettingChangeRequest:
- new: Union[int, AnonymousSettingGroupDict]
- old: Optional[Union[int, AnonymousSettingGroupDict]] = None
+ new: int | AnonymousSettingGroupDict
+ old: int | AnonymousSettingGroupDict | None = None
class UserGroupDict(TypedDict):
@@ -49,7 +49,7 @@ class UserGroupDict(TypedDict):
members: list[int]
direct_subgroup_ids: list[int]
is_system_group: bool
- can_mention_group: Union[int, AnonymousSettingGroupDict]
+ can_mention_group: int | AnonymousSettingGroupDict
@dataclass
@@ -254,7 +254,7 @@ def update_or_create_user_group_for_setting(
realm: Realm,
direct_members: list[int],
direct_subgroups: list[int],
- current_setting_value: Optional[UserGroup],
+ current_setting_value: UserGroup | None,
) -> UserGroup:
if current_setting_value is not None and not hasattr(current_setting_value, "named_user_group"):
# We do not create a new group if the setting was already set
@@ -285,12 +285,12 @@ def update_or_create_user_group_for_setting(
def access_user_group_for_setting(
- setting_user_group: Union[int, AnonymousSettingGroupDict],
+ setting_user_group: int | AnonymousSettingGroupDict,
user_profile: UserProfile,
*,
setting_name: str,
permission_configuration: GroupPermissionSetting,
- current_setting_value: Optional[UserGroup] = None,
+ current_setting_value: UserGroup | None = None,
) -> UserGroup:
if isinstance(setting_user_group, int):
named_user_group = access_user_group_by_id(setting_user_group, user_profile, for_read=True)
@@ -335,7 +335,7 @@ def check_user_group_name(group_name: str) -> str:
def get_group_setting_value_for_api(
setting_value_group: UserGroup,
-) -> Union[int, AnonymousSettingGroupDict]:
+) -> int | AnonymousSettingGroupDict:
if hasattr(setting_value_group, "named_user_group"):
return setting_value_group.id
@@ -728,9 +728,9 @@ def get_server_supported_permission_settings() -> ServerSupportedPermissionSetti
def parse_group_setting_value(
- setting_value: Union[int, AnonymousSettingGroupDict],
+ setting_value: int | AnonymousSettingGroupDict,
setting_name: str,
-) -> Union[int, AnonymousSettingGroupDict]:
+) -> int | AnonymousSettingGroupDict:
if isinstance(setting_value, int):
return setting_value
@@ -744,8 +744,8 @@ def parse_group_setting_value(
def are_both_group_setting_values_equal(
- first_setting_value: Union[int, AnonymousSettingGroupDict],
- second_setting_value: Union[int, AnonymousSettingGroupDict],
+ first_setting_value: int | AnonymousSettingGroupDict,
+ second_setting_value: int | AnonymousSettingGroupDict,
) -> bool:
if isinstance(first_setting_value, int) and isinstance(second_setting_value, int):
return first_setting_value == second_setting_value
@@ -763,9 +763,9 @@ def are_both_group_setting_values_equal(
def validate_group_setting_value_change(
- current_setting_api_value: Union[int, AnonymousSettingGroupDict],
- new_setting_value: Union[int, AnonymousSettingGroupDict],
- expected_current_setting_value: Optional[Union[int, AnonymousSettingGroupDict]],
+ current_setting_api_value: int | AnonymousSettingGroupDict,
+ new_setting_value: int | AnonymousSettingGroupDict,
+ expected_current_setting_value: int | AnonymousSettingGroupDict | None,
) -> bool:
if expected_current_setting_value is not None and not are_both_group_setting_values_equal(
expected_current_setting_value,
@@ -780,8 +780,8 @@ def validate_group_setting_value_change(
def get_group_setting_value_for_audit_log_data(
- setting_value: Union[int, AnonymousSettingGroupDict],
-) -> Union[int, dict[str, list[int]]]:
+ setting_value: int | AnonymousSettingGroupDict,
+) -> int | dict[str, list[int]]:
if isinstance(setting_value, int):
return setting_value
diff --git a/zerver/lib/user_message.py b/zerver/lib/user_message.py
index 421118bf5b2..c6fa35ec993 100644
--- a/zerver/lib/user_message.py
+++ b/zerver/lib/user_message.py
@@ -1,5 +1,3 @@
-from typing import Optional
-
from django.db import connection
from psycopg2.extras import execute_values
from psycopg2.sql import SQL, Composable, Literal
@@ -30,8 +28,8 @@ def create_historical_user_messages(
*,
user_id: int,
message_ids: list[int],
- flagattr: Optional[int] = None,
- flag_target: Optional[int] = None,
+ flagattr: int | None = None,
+ flag_target: int | None = None,
) -> None:
# Users can see and interact with messages sent to streams with
# public history for which they do not have a UserMessage because
@@ -76,7 +74,7 @@ def bulk_insert_ums(ums: list[UserMessageLite]) -> None:
def bulk_insert_all_ums(
- user_ids: list[int], message_ids: list[int], flags: int, conflict: Optional[Composable] = None
+ user_ids: list[int], message_ids: list[int], flags: int, conflict: Composable | None = None
) -> None:
if not user_ids or not message_ids:
return
diff --git a/zerver/lib/user_status.py b/zerver/lib/user_status.py
index afa02ec2003..64f0e335452 100644
--- a/zerver/lib/user_status.py
+++ b/zerver/lib/user_status.py
@@ -1,4 +1,4 @@
-from typing import Optional, TypedDict
+from typing import TypedDict
from django.db.models import Q
from django.utils.timezone import now as timezone_now
@@ -84,11 +84,11 @@ def get_all_users_status_dict(realm: Realm, user_profile: UserProfile) -> dict[s
def update_user_status(
user_profile_id: int,
- status_text: Optional[str],
+ status_text: str | None,
client_id: int,
- emoji_name: Optional[str],
- emoji_code: Optional[str],
- reaction_type: Optional[str],
+ emoji_name: str | None,
+ emoji_code: str | None,
+ reaction_type: str | None,
) -> None:
timestamp = timezone_now()
diff --git a/zerver/lib/user_topics.py b/zerver/lib/user_topics.py
index 47cea8fb8fd..b688b8764c1 100644
--- a/zerver/lib/user_topics.py
+++ b/zerver/lib/user_topics.py
@@ -1,7 +1,7 @@
import logging
from collections import defaultdict
from datetime import datetime
-from typing import Callable, Optional, TypedDict
+from typing import Callable, TypedDict
from django.db import connection, transaction
from django.db.models import QuerySet
@@ -21,7 +21,7 @@ def get_user_topics(
user_profile: UserProfile,
include_deactivated: bool = False,
include_stream_name: bool = False,
- visibility_policy: Optional[int] = None,
+ visibility_policy: int | None = None,
) -> list[UserTopicDict]:
"""
Fetches UserTopic objects associated with the target user.
@@ -84,7 +84,7 @@ def set_topic_visibility_policy(
user_profile: UserProfile,
topics: list[list[str]],
visibility_policy: int,
- last_updated: Optional[datetime] = None,
+ last_updated: datetime | None = None,
) -> None:
"""
This is only used in tests.
@@ -134,8 +134,8 @@ def bulk_set_user_topic_visibility_policy_in_database(
topic_name: str,
*,
visibility_policy: int,
- recipient_id: Optional[int] = None,
- last_updated: Optional[datetime] = None,
+ recipient_id: int | None = None,
+ last_updated: datetime | None = None,
) -> list[UserProfile]:
# returns the list of user_profiles whose user_topic row
# is either deleted, updated, or created.
@@ -228,7 +228,7 @@ def topic_has_visibility_policy(
def exclude_topic_mutes(
- conditions: list[ClauseElement], user_profile: UserProfile, stream_id: Optional[int]
+ conditions: list[ClauseElement], user_profile: UserProfile, stream_id: int | None
) -> list[ClauseElement]:
# Note: Unlike get_topic_mutes, here we always want to
# consider topics in deactivated streams, so they are
diff --git a/zerver/lib/users.py b/zerver/lib/users.py
index 2d0d9379051..9197bd1d7d9 100644
--- a/zerver/lib/users.py
+++ b/zerver/lib/users.py
@@ -4,7 +4,7 @@ import unicodedata
from collections import defaultdict
from email.headerregistry import Address
from operator import itemgetter
-from typing import Any, Iterable, Mapping, Optional, Sequence, TypedDict
+from typing import Any, Iterable, Mapping, Sequence, TypedDict
import dateutil.parser as date_parser
from django.conf import settings
@@ -51,7 +51,7 @@ from zerver.models.users import (
def check_full_name(
- full_name_raw: str, *, user_profile: Optional[UserProfile], realm: Optional[Realm]
+ full_name_raw: str, *, user_profile: UserProfile | None, realm: Realm | None
) -> str:
full_name = full_name_raw.strip()
if len(full_name) > UserProfile.MAX_NAME_LENGTH:
@@ -202,7 +202,7 @@ def check_valid_bot_type(user_profile: UserProfile, bot_type: int) -> None:
raise JsonableError(_("Invalid bot type"))
-def check_valid_interface_type(interface_type: Optional[int]) -> None:
+def check_valid_interface_type(interface_type: int | None) -> None:
if interface_type not in Service.ALLOWED_INTERFACE_TYPES:
raise JsonableError(_("Invalid interface type"))
@@ -351,7 +351,7 @@ class Account(TypedDict):
realm_name: str
realm_id: int
full_name: str
- avatar: Optional[str]
+ avatar: str | None
def get_accounts_for_email(email: str) -> list[Account]:
@@ -462,22 +462,22 @@ class APIUserDict(TypedDict):
timezone: NotRequired[str]
is_active: bool
date_joined: str
- avatar_url: NotRequired[Optional[str]]
- delivery_email: Optional[str]
- bot_type: NotRequired[Optional[int]]
- bot_owner_id: NotRequired[Optional[int]]
- profile_data: NotRequired[Optional[dict[str, Any]]]
+ avatar_url: NotRequired[str | None]
+ delivery_email: str | None
+ bot_type: NotRequired[int | None]
+ bot_owner_id: NotRequired[int | None]
+ profile_data: NotRequired[dict[str, Any] | None]
is_system_bot: NotRequired[bool]
max_message_id: NotRequired[int]
def format_user_row(
realm_id: int,
- acting_user: Optional[UserProfile],
+ acting_user: UserProfile | None,
row: RawUserDict,
client_gravatar: bool,
user_avatar_url_field_optional: bool,
- custom_profile_field_data: Optional[dict[str, Any]] = None,
+ custom_profile_field_data: dict[str, Any] | None = None,
) -> APIUserDict:
"""Formats a user row returned by a database fetch using
.values(*realm_user_dict_fields) into a dictionary representation
@@ -575,7 +575,7 @@ def user_access_restricted_in_realm(target_user: UserProfile) -> bool:
return True
-def check_user_can_access_all_users(acting_user: Optional[UserProfile]) -> bool:
+def check_user_can_access_all_users(acting_user: UserProfile | None) -> bool:
if acting_user is None:
# We allow spectators to access all users since they
# have very limited access to the user already.
@@ -592,7 +592,7 @@ def check_user_can_access_all_users(acting_user: Optional[UserProfile]) -> bool:
def check_can_access_user(
- target_user: UserProfile, user_profile: Optional[UserProfile] = None
+ target_user: UserProfile, user_profile: UserProfile | None = None
) -> bool:
if not user_access_restricted_in_realm(target_user):
return True
@@ -637,7 +637,7 @@ def check_can_access_user(
def get_inaccessible_user_ids(
- target_user_ids: list[int], acting_user: Optional[UserProfile]
+ target_user_ids: list[int], acting_user: UserProfile | None
) -> set[int]:
if check_user_can_access_all_users(acting_user):
return set()
@@ -934,7 +934,7 @@ def get_accessible_user_ids(
def get_user_dicts_in_realm(
- realm: Realm, user_profile: Optional[UserProfile]
+ realm: Realm, user_profile: UserProfile | None
) -> tuple[list[RawUserDict], list[APIUserDict]]:
group_allowed_to_access_all_users = realm.can_access_all_users_group
assert group_allowed_to_access_all_users is not None
@@ -979,9 +979,9 @@ def get_custom_profile_field_values(
def get_users_for_api(
realm: Realm,
- acting_user: Optional[UserProfile],
+ acting_user: UserProfile | None,
*,
- target_user: Optional[UserProfile] = None,
+ target_user: UserProfile | None = None,
client_gravatar: bool,
user_avatar_url_field_optional: bool,
include_custom_profile_fields: bool = True,
@@ -1082,7 +1082,7 @@ def get_users_with_access_to_real_email(user_profile: UserProfile) -> list[int]:
]
-def max_message_id_for_user(user_profile: Optional[UserProfile]) -> int:
+def max_message_id_for_user(user_profile: UserProfile | None) -> int:
if user_profile is None:
return -1
max_message = (
diff --git a/zerver/lib/utils.py b/zerver/lib/utils.py
index b7980080f4b..7346588fc9f 100644
--- a/zerver/lib/utils.py
+++ b/zerver/lib/utils.py
@@ -1,6 +1,6 @@
import re
import secrets
-from typing import Callable, Optional, TypeVar
+from typing import Callable, TypeVar
T = TypeVar("T")
@@ -17,7 +17,7 @@ def has_api_key_format(key: str) -> bool:
return bool(re.fullmatch(r"([A-Za-z0-9]){32}", key))
-def assert_is_not_none(value: Optional[T]) -> T:
+def assert_is_not_none(value: T | None) -> T:
assert value is not None
return value
@@ -35,7 +35,7 @@ def process_list_in_batches(
offset += chunk_size
-def optional_bytes_to_mib(value: Optional[int]) -> Optional[int]:
+def optional_bytes_to_mib(value: int | None) -> int | None:
if value is None:
return None
else:
diff --git a/zerver/lib/validator.py b/zerver/lib/validator.py
index 0cf2d74112a..e40b217dd1a 100644
--- a/zerver/lib/validator.py
+++ b/zerver/lib/validator.py
@@ -31,19 +31,7 @@ for any particular type of object.
import re
from dataclasses import dataclass
from datetime import datetime, timezone
-from typing import (
- Any,
- Callable,
- Collection,
- Container,
- Iterator,
- NoReturn,
- Optional,
- TypeVar,
- Union,
- cast,
- overload,
-)
+from typing import Any, Callable, Collection, Container, Iterator, NoReturn, TypeVar, cast, overload
import orjson
import zoneinfo
@@ -209,8 +197,8 @@ def check_color(var_name: str, val: object) -> str:
return s
-def check_none_or(sub_validator: Validator[ResultT]) -> Validator[Optional[ResultT]]:
- def f(var_name: str, val: object) -> Optional[ResultT]:
+def check_none_or(sub_validator: Validator[ResultT]) -> Validator[ResultT | None]:
+ def f(var_name: str, val: object) -> ResultT | None:
if val is None:
return val
else:
@@ -220,7 +208,7 @@ def check_none_or(sub_validator: Validator[ResultT]) -> Validator[Optional[Resul
def check_list(
- sub_validator: Validator[ResultT], length: Optional[int] = None
+ sub_validator: Validator[ResultT], length: int | None = None
) -> Validator[list[ResultT]]:
def f(var_name: str, val: object) -> list[ResultT]:
if not isinstance(val, list):
@@ -264,7 +252,7 @@ def check_dict(
required_keys: Collection[tuple[str, Validator[ResultT]]] = [],
optional_keys: Collection[tuple[str, Validator[ResultT]]] = [],
*,
- value_validator: Optional[Validator[ResultT]] = None,
+ value_validator: Validator[ResultT] | None = None,
_allow_only_listed_keys: bool = False,
) -> Validator[dict[str, ResultT]]:
def f(var_name: str, val: object) -> dict[str, ResultT]:
@@ -622,7 +610,7 @@ def to_converted_or_fallback(
return converter
-def check_string_or_int_list(var_name: str, val: object) -> Union[str, list[int]]:
+def check_string_or_int_list(var_name: str, val: object) -> str | list[int]:
if isinstance(val, str):
return val
@@ -634,7 +622,7 @@ def check_string_or_int_list(var_name: str, val: object) -> Union[str, list[int]
return check_list(check_int)(var_name, val)
-def check_string_or_int(var_name: str, val: object) -> Union[str, int]:
+def check_string_or_int(var_name: str, val: object) -> str | int:
if isinstance(val, (str, int)):
return val
@@ -687,7 +675,7 @@ class WildValue:
def __contains__(self, key: str) -> bool:
self._need_dict()
- def __getitem__(self, key: Union[int, str]) -> "WildValue":
+ def __getitem__(self, key: int | str) -> "WildValue":
if isinstance(key, int):
self._need_list()
else:
@@ -718,7 +706,7 @@ class WildValueList(WildValue):
yield wrap_wild_value(f"{self.var_name}[{i}]", item)
@override
- def __getitem__(self, key: Union[int, str]) -> WildValue:
+ def __getitem__(self, key: int | str) -> WildValue:
if not isinstance(key, int):
return super().__getitem__(key)
@@ -740,7 +728,7 @@ class WildValueDict(WildValue):
return key in self.value
@override
- def __getitem__(self, key: Union[int, str]) -> WildValue:
+ def __getitem__(self, key: int | str) -> WildValue:
if not isinstance(key, str):
return super().__getitem__(key)
diff --git a/zerver/lib/webhooks/common.py b/zerver/lib/webhooks/common.py
index 3fb6c32ae0e..366644824c9 100644
--- a/zerver/lib/webhooks/common.py
+++ b/zerver/lib/webhooks/common.py
@@ -1,7 +1,7 @@
import fnmatch
import importlib
from datetime import datetime
-from typing import Any, Callable, Optional, Union
+from typing import Any, Callable
from urllib.parse import unquote
from django.http import HttpRequest
@@ -45,10 +45,10 @@ that this integration expects!
SETUP_MESSAGE_TEMPLATE = "{integration} webhook has been successfully configured"
SETUP_MESSAGE_USER_PART = " by {user_name}"
-OptionalUserSpecifiedTopicStr: TypeAlias = Annotated[Optional[str], ApiParamConfig("topic")]
+OptionalUserSpecifiedTopicStr: TypeAlias = Annotated[str | None, ApiParamConfig("topic")]
-def get_setup_webhook_message(integration: str, user_name: Optional[str] = None) -> str:
+def get_setup_webhook_message(integration: str, user_name: str | None = None) -> str:
content = SETUP_MESSAGE_TEMPLATE.format(integration=integration)
if user_name:
content += SETUP_MESSAGE_USER_PART.format(user_name=user_name)
@@ -85,12 +85,12 @@ def check_send_webhook_message(
user_profile: UserProfile,
topic: str,
body: str,
- complete_event_type: Optional[str] = None,
+ complete_event_type: str | None = None,
*,
- stream: Optional[str] = None,
+ stream: str | None = None,
user_specified_topic: OptionalUserSpecifiedTopicStr = None,
- only_events: Optional[Json[list[str]]] = None,
- exclude_events: Optional[Json[list[str]]] = None,
+ only_events: Json[list[str]] | None = None,
+ exclude_events: Json[list[str]] | None = None,
unquote_url_parameters: bool = False,
) -> None:
if complete_event_type is not None and (
@@ -146,7 +146,7 @@ def check_send_webhook_message(
pass
-def standardize_headers(input_headers: Union[None, dict[str, Any]]) -> dict[str, str]:
+def standardize_headers(input_headers: None | dict[str, Any]) -> dict[str, str]:
"""This method can be used to standardize a dictionary of headers with
the standard format that Django expects. For reference, refer to:
https://docs.djangoproject.com/en/5.0/ref/request-response/#django.http.HttpRequest.headers
diff --git a/zerver/lib/webhooks/git.py b/zerver/lib/webhooks/git.py
index 4d5ebae1a9e..2d9c2a5dd4e 100644
--- a/zerver/lib/webhooks/git.py
+++ b/zerver/lib/webhooks/git.py
@@ -1,6 +1,6 @@
import string
from collections import defaultdict
-from typing import Any, Optional
+from typing import Any
TOPIC_WITH_BRANCH_TEMPLATE = "{repo} / {branch}"
TOPIC_WITH_PR_OR_ISSUE_INFO_TEMPLATE = "{repo} / {type} #{id} {title}"
@@ -90,12 +90,12 @@ def get_assignee_string(assignees: list[dict[str, Any]]) -> str:
def get_push_commits_event_message(
user_name: str,
- compare_url: Optional[str],
+ compare_url: str | None,
branch_name: str,
commits_data: list[dict[str, Any]],
is_truncated: bool = False,
deleted: bool = False,
- force_push: Optional[bool] = False,
+ force_push: bool | None = False,
) -> str:
if not commits_data and deleted:
return PUSH_DELETE_BRANCH_MESSAGE_TEMPLATE.format(
@@ -167,7 +167,7 @@ def get_force_push_commits_event_message(
)
-def get_create_branch_event_message(user_name: str, url: Optional[str], branch_name: str) -> str:
+def get_create_branch_event_message(user_name: str, url: str | None, branch_name: str) -> str:
if url is None:
return CREATE_BRANCH_WITHOUT_URL_MESSAGE_TEMPLATE.format(
user_name=user_name,
@@ -192,15 +192,15 @@ def get_pull_request_event_message(
user_name: str,
action: str,
url: str,
- number: Optional[int] = None,
- target_branch: Optional[str] = None,
- base_branch: Optional[str] = None,
- message: Optional[str] = None,
- assignee: Optional[str] = None,
- assignees: Optional[list[dict[str, Any]]] = None,
- reviewer: Optional[str] = None,
+ number: int | None = None,
+ target_branch: str | None = None,
+ base_branch: str | None = None,
+ message: str | None = None,
+ assignee: str | None = None,
+ assignees: list[dict[str, Any]] | None = None,
+ reviewer: str | None = None,
type: str = "PR",
- title: Optional[str] = None,
+ title: str | None = None,
) -> str:
kwargs = {
"user_name": user_name,
@@ -260,11 +260,11 @@ def get_issue_event_message(
user_name: str,
action: str,
url: str,
- number: Optional[int] = None,
- message: Optional[str] = None,
- assignee: Optional[str] = None,
- assignees: Optional[list[dict[str, Any]]] = None,
- title: Optional[str] = None,
+ number: int | None = None,
+ message: str | None = None,
+ assignee: str | None = None,
+ assignees: list[dict[str, Any]] | None = None,
+ title: str | None = None,
) -> str:
return get_pull_request_event_message(
user_name=user_name,
@@ -286,7 +286,7 @@ def get_issue_labeled_or_unlabeled_event_message(
number: int,
label_name: str,
user_url: str,
- title: Optional[str] = None,
+ title: str | None = None,
) -> str:
args = {
"user_name": user_name,
@@ -311,7 +311,7 @@ def get_issue_milestoned_or_demilestoned_event_message(
milestone_name: str,
milestone_url: str,
user_url: str,
- title: Optional[str] = None,
+ title: str | None = None,
) -> str:
args = {
"user_name": user_name,
@@ -330,7 +330,7 @@ def get_issue_milestoned_or_demilestoned_event_message(
def get_push_tag_event_message(
- user_name: str, tag_name: str, tag_url: Optional[str] = None, action: str = "pushed"
+ user_name: str, tag_name: str, tag_url: str | None = None, action: str = "pushed"
) -> str:
if tag_url:
tag_part = TAG_WITH_URL_TEMPLATE.format(tag_name=tag_name, tag_url=tag_url)
@@ -350,7 +350,7 @@ def get_push_tag_event_message(
def get_commits_comment_action_message(
- user_name: str, action: str, commit_url: str, sha: str, message: Optional[str] = None
+ user_name: str, action: str, commit_url: str, sha: str, message: str | None = None
) -> str:
content = COMMITS_COMMENT_MESSAGE_TEMPLATE.format(
user_name=user_name,
diff --git a/zerver/lib/widget.py b/zerver/lib/widget.py
index f1160d25db2..ea9363b9780 100644
--- a/zerver/lib/widget.py
+++ b/zerver/lib/widget.py
@@ -1,12 +1,12 @@
import json
import re
-from typing import Any, Optional
+from typing import Any
from zerver.lib.message import SendMessageRequest
from zerver.models import Message, SubMessage
-def get_widget_data(content: str) -> tuple[Optional[str], Any]:
+def get_widget_data(content: str) -> tuple[str | None, Any]:
valid_widget_types = ["poll", "todo"]
tokens = re.split(r"\s+|\n+", content)
@@ -71,7 +71,7 @@ def parse_todo_extra_data(content: str) -> Any:
return extra_data
-def get_extra_data_from_widget_type(content: str, widget_type: Optional[str]) -> Any:
+def get_extra_data_from_widget_type(content: str, widget_type: str | None) -> Any:
if widget_type == "poll":
return parse_poll_extra_data(content)
else:
@@ -113,7 +113,7 @@ def do_widget_post_save_actions(send_request: SendMessageRequest) -> None:
send_request.submessages = SubMessage.get_raw_db_rows([message_id])
-def get_widget_type(*, message_id: int) -> Optional[str]:
+def get_widget_type(*, message_id: int) -> str | None:
submessage = (
SubMessage.objects.filter(
message_id=message_id,
diff --git a/zerver/lib/zulip_update_announcements.py b/zerver/lib/zulip_update_announcements.py
index 72fb465571a..d27a37a185e 100644
--- a/zerver/lib/zulip_update_announcements.py
+++ b/zerver/lib/zulip_update_announcements.py
@@ -1,7 +1,6 @@
import logging
from dataclasses import dataclass
from datetime import timedelta
-from typing import Optional
from django.conf import settings
from django.db import transaction
@@ -165,7 +164,7 @@ def get_realms_behind_zulip_update_announcements_level(level: int) -> QuerySet[R
def internal_prep_group_direct_message_for_old_realm(
realm: Realm, sender: UserProfile
-) -> Optional[SendMessageRequest]:
+) -> SendMessageRequest | None:
administrators = list(realm.get_human_admin_users())
with override_language(realm.default_language):
topic_name = str(realm.ZULIP_UPDATE_ANNOUNCEMENTS_TOPIC_NAME)
@@ -199,7 +198,7 @@ configuration change), or [turn this feature off]({organization_settings_url}) a
)
-def get_level_none_to_initial_auditlog(realm: Realm) -> Optional[RealmAuditLog]:
+def get_level_none_to_initial_auditlog(realm: Realm) -> RealmAuditLog | None:
return RealmAuditLog.objects.filter(
realm=realm,
event_type=RealmAuditLog.REALM_PROPERTY_CHANGED,
@@ -223,7 +222,7 @@ def is_group_direct_message_sent_to_admins_within_days(realm: Realm, days: int)
def internal_prep_zulip_update_announcements_stream_messages(
current_level: int, latest_level: int, sender: UserProfile, realm: Realm
-) -> list[Optional[SendMessageRequest]]:
+) -> list[SendMessageRequest | None]:
message_requests = []
stream = realm.zulip_update_announcements_stream
assert stream is not None
@@ -247,7 +246,7 @@ def internal_prep_zulip_update_announcements_stream_messages(
def send_messages_and_update_level(
realm: Realm,
new_zulip_update_announcements_level: int,
- send_message_requests: list[Optional[SendMessageRequest]],
+ send_message_requests: list[SendMessageRequest | None],
) -> None:
sent_message_ids = []
if send_message_requests:
diff --git a/zerver/logging_handlers.py b/zerver/logging_handlers.py
index c48e7ad0c33..7fe0e535294 100644
--- a/zerver/logging_handlers.py
+++ b/zerver/logging_handlers.py
@@ -1,10 +1,9 @@
# System documented in https://zulip.readthedocs.io/en/latest/subsystems/logging.html
import os
import subprocess
-from typing import Optional
-def try_git_describe() -> Optional[str]:
+def try_git_describe() -> str | None:
try: # nocoverage
return subprocess.check_output(
["git", "describe", "--tags", "--match=[0-9]*", "--always", "--dirty", "--long"],
diff --git a/zerver/management/commands/check_redis.py b/zerver/management/commands/check_redis.py
index e500b1f8d02..1a8bacb96c9 100644
--- a/zerver/management/commands/check_redis.py
+++ b/zerver/management/commands/check_redis.py
@@ -1,6 +1,6 @@
import logging
import time
-from typing import Any, Callable, Optional
+from typing import Any, Callable
from django.conf import settings
from django.core.management.base import CommandError, CommandParser
@@ -26,7 +26,7 @@ class Command(ZulipBaseCommand):
self,
key: bytes,
count_func: Callable[[], int],
- trim_func: Optional[Callable[[bytes, int], object]] = None,
+ trim_func: Callable[[bytes, int], object] | None = None,
) -> None:
user_id = int(key.split(b":")[2])
user = get_user_profile_by_id(user_id)
@@ -58,7 +58,7 @@ than max_api_calls! (trying to trim) %s %s",
wildcard_list = "ratelimit:*:*:*:list"
wildcard_zset = "ratelimit:*:*:*:zset"
- trim_func: Optional[Callable[[bytes, int], object]] = lambda key, max_calls: client.ltrim(
+ trim_func: Callable[[bytes, int], object] | None = lambda key, max_calls: client.ltrim(
key, 0, max_calls - 1
)
if not options["trim"]:
diff --git a/zerver/management/commands/fill_memcached_caches.py b/zerver/management/commands/fill_memcached_caches.py
index e4ae4046fc5..247385cced8 100644
--- a/zerver/management/commands/fill_memcached_caches.py
+++ b/zerver/management/commands/fill_memcached_caches.py
@@ -1,5 +1,5 @@
from argparse import ArgumentParser
-from typing import Any, Optional
+from typing import Any
from typing_extensions import override
@@ -15,7 +15,7 @@ class Command(ZulipBaseCommand):
)
@override
- def handle(self, *args: Any, **options: Optional[str]) -> None:
+ def handle(self, *args: Any, **options: str | None) -> None:
if options["cache"] is not None:
fill_remote_cache(options["cache"])
return
diff --git a/zerver/management/commands/process_queue.py b/zerver/management/commands/process_queue.py
index 51d96196fd3..550bb98cee6 100644
--- a/zerver/management/commands/process_queue.py
+++ b/zerver/management/commands/process_queue.py
@@ -6,7 +6,7 @@ import threading
from argparse import ArgumentParser
from contextlib import contextmanager
from types import FrameType
-from typing import Any, Iterator, Optional
+from typing import Any, Iterator
from django.conf import settings
from django.core.management.base import CommandError
@@ -57,7 +57,7 @@ class Command(ZulipBaseCommand):
logging.basicConfig()
logger = logging.getLogger("process_queue")
- def exit_with_three(signal: int, frame: Optional[FrameType]) -> None:
+ def exit_with_three(signal: int, frame: FrameType | None) -> None:
"""
This process is watched by Django's autoreload, so exiting
with status code 3 will cause this process to restart.
@@ -95,7 +95,7 @@ class Command(ZulipBaseCommand):
queue_name = options["queue_name"]
worker_num = options["worker_num"]
- def signal_handler(signal: int, frame: Optional[FrameType]) -> None:
+ def signal_handler(signal: int, frame: FrameType | None) -> None:
logger.info("Worker %d disconnecting from queue %s", worker_num, queue_name)
worker.stop()
sys.exit(0)
diff --git a/zerver/management/commands/realm_domain.py b/zerver/management/commands/realm_domain.py
index e33ab287112..70f60b586d8 100644
--- a/zerver/management/commands/realm_domain.py
+++ b/zerver/management/commands/realm_domain.py
@@ -1,6 +1,6 @@
import sys
from argparse import ArgumentParser
-from typing import Any, Union
+from typing import Any
from django.core.exceptions import ValidationError
from django.core.management.base import CommandError
@@ -28,7 +28,7 @@ class Command(ZulipBaseCommand):
self.add_realm_args(parser, required=True)
@override
- def handle(self, *args: Any, **options: Union[str, bool]) -> None:
+ def handle(self, *args: Any, **options: str | bool) -> None:
realm = self.get_realm(options)
assert realm is not None # Should be ensured by parser
if options["op"] == "show":
diff --git a/zerver/management/commands/send_custom_email.py b/zerver/management/commands/send_custom_email.py
index 7b4282c1780..5996fe89da0 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, Callable, Optional
+from typing import Any, Callable
import orjson
from django.conf import settings
@@ -97,7 +97,7 @@ class Command(ZulipBaseCommand):
self, *args: Any, dry_run: bool = False, admins_only: bool = False, **options: str
) -> None:
users: QuerySet[UserProfile] = UserProfile.objects.none()
- add_context: Optional[Callable[[dict[str, object], UserProfile], None]] = None
+ add_context: Callable[[dict[str, object], UserProfile], None] | None = None
distinct_email = False
if options["remote_servers"]:
diff --git a/zerver/management/commands/send_to_email_mirror.py b/zerver/management/commands/send_to_email_mirror.py
index 1bdee441a7c..9ab132871cd 100644
--- a/zerver/management/commands/send_to_email_mirror.py
+++ b/zerver/management/commands/send_to_email_mirror.py
@@ -3,7 +3,7 @@ import email
import email.policy
import os
from email.message import EmailMessage
-from typing import Any, Optional
+from typing import Any
import orjson
from django.conf import settings
@@ -59,7 +59,7 @@ Example:
self.add_realm_args(parser, help="Specify which realm to connect to; default is zulip")
@override
- def handle(self, *args: Any, **options: Optional[str]) -> None:
+ def handle(self, *args: Any, **options: str | None) -> None:
if options["fixture"] is None:
self.print_help("./manage.py", "send_to_email_mirror")
raise CommandError
diff --git a/zerver/management/commands/send_webhook_fixture_message.py b/zerver/management/commands/send_webhook_fixture_message.py
index 2030fb92c8a..16bad2a1ce3 100644
--- a/zerver/management/commands/send_webhook_fixture_message.py
+++ b/zerver/management/commands/send_webhook_fixture_message.py
@@ -1,5 +1,5 @@
import os
-from typing import Any, Optional, Union
+from typing import Any
import orjson
from django.conf import settings
@@ -51,7 +51,7 @@ approach shown above.
parser, help="Specify which realm/subdomain to connect to; default is zulip"
)
- def parse_headers(self, custom_headers: Union[None, str]) -> Union[None, dict[str, str]]:
+ def parse_headers(self, custom_headers: None | str) -> None | dict[str, str]:
if not custom_headers:
return {}
try:
@@ -64,7 +64,7 @@ approach shown above.
return standardize_headers(custom_headers_dict)
@override
- def handle(self, *args: Any, **options: Optional[str]) -> None:
+ def handle(self, *args: Any, **options: str | None) -> None:
if options["fixture"] is None or options["url"] is None:
self.print_help("./manage.py", "send_webhook_fixture_message")
raise CommandError
diff --git a/zerver/management/commands/unarchive_channel.py b/zerver/management/commands/unarchive_channel.py
index 6a10a0807cd..969197cb8d4 100644
--- a/zerver/management/commands/unarchive_channel.py
+++ b/zerver/management/commands/unarchive_channel.py
@@ -1,5 +1,5 @@
from argparse import ArgumentParser
-from typing import Any, Optional
+from typing import Any
from django.core.management.base import CommandError
from typing_extensions import override
@@ -33,7 +33,7 @@ class Command(ZulipBaseCommand):
self.add_realm_args(parser, required=True)
@override
- def handle(self, *args: Any, **options: Optional[str]) -> None:
+ def handle(self, *args: Any, **options: str | None) -> None:
realm = self.get_realm(options)
assert realm is not None # Should be ensured by parser
diff --git a/zerver/middleware.py b/zerver/middleware.py
index 2ba73086fe8..e63f9c3a888 100644
--- a/zerver/middleware.py
+++ b/zerver/middleware.py
@@ -2,7 +2,7 @@ import cProfile
import logging
import tempfile
import time
-from typing import Any, Callable, MutableMapping, Optional
+from typing import Any, Callable, MutableMapping
from urllib.parse import urlencode, urljoin
from django.conf import settings
@@ -126,9 +126,9 @@ def write_log_line(
remote_ip: str,
requester_for_logs: str,
client_name: str,
- client_version: Optional[str] = None,
+ client_version: str | None = None,
status_code: int = 200,
- error_content: Optional[bytes] = None,
+ error_content: bytes | None = None,
) -> None:
time_delta = -1
# A time duration of -1 means the StartLogRequests middleware
@@ -236,16 +236,16 @@ def parse_client(
# not to document on every endpoint's individual parameters.
*,
req_client: Annotated[
- Optional[str], ApiParamConfig("client", documentation_status=INTENTIONALLY_UNDOCUMENTED)
+ str | None, ApiParamConfig("client", documentation_status=INTENTIONALLY_UNDOCUMENTED)
] = None,
-) -> tuple[str, Optional[str]]:
+) -> tuple[str, str | None]:
# If the API request specified a client in the request content,
# that has priority. Otherwise, extract the client from the
# USER_AGENT.
if req_client is not None:
return req_client, None
if "User-Agent" in request.headers:
- user_agent: Optional[dict[str, str]] = parse_user_agent(request.headers["User-Agent"])
+ user_agent: dict[str, str] | None = parse_user_agent(request.headers["User-Agent"])
else:
user_agent = None
if user_agent is None:
@@ -363,9 +363,7 @@ class LogRequests(MiddlewareMixin):
class JsonErrorHandler(MiddlewareMixin):
- def process_exception(
- self, request: HttpRequest, exception: Exception
- ) -> Optional[HttpResponse]:
+ def process_exception(self, request: HttpRequest, exception: Exception) -> HttpResponse | None:
if isinstance(exception, MissingAuthenticationError):
if "text/html" in request.headers.get("Accept", ""):
# If this looks like a request from a top-level page in a
@@ -536,7 +534,7 @@ class FlushDisplayRecipientCache(MiddlewareMixin):
class HostDomainMiddleware(MiddlewareMixin):
- def process_request(self, request: HttpRequest) -> Optional[HttpResponse]:
+ def process_request(self, request: HttpRequest) -> HttpResponse | None:
# Match against ALLOWED_HOSTS, which is rather permissive;
# failure will raise DisallowedHost, which is a 400.
request.get_host()
@@ -717,7 +715,7 @@ class ZulipSCIMAuthCheckMiddleware(SCIMAuthCheckMiddleware):
the request when accessing SCIM endpoints.
"""
- def process_request(self, request: HttpRequest) -> Optional[HttpResponse]:
+ def process_request(self, request: HttpRequest) -> HttpResponse | None:
# Defensive assertion to ensure this can't accidentally get called on a request
# to a non-SCIM endpoint.
assert request.path.startswith(self.reverse_url)
diff --git a/zerver/migrations/0209_user_profile_no_empty_password.py b/zerver/migrations/0209_user_profile_no_empty_password.py
index b1d91db4163..15aec02d0f1 100644
--- a/zerver/migrations/0209_user_profile_no_empty_password.py
+++ b/zerver/migrations/0209_user_profile_no_empty_password.py
@@ -1,6 +1,6 @@
# Generated by Django 1.11.24 on 2019-10-16 22:48
-from typing import Any, Union
+from typing import Any
import orjson
from django.conf import settings
@@ -66,8 +66,8 @@ def ensure_no_empty_passwords(apps: StateApps, schema_editor: BaseDatabaseSchema
# searching for the relevant events in that log.
event_type_class = RealmAuditLog._meta.get_field("event_type").get_internal_type()
if event_type_class == "CharField":
- USER_PASSWORD_CHANGED: Union[int, str] = "user_password_changed"
- USER_API_KEY_CHANGED: Union[int, str] = "user_api_key_changed"
+ USER_PASSWORD_CHANGED: int | str = "user_password_changed"
+ USER_API_KEY_CHANGED: int | str = "user_api_key_changed"
else:
USER_PASSWORD_CHANGED = 122
USER_API_KEY_CHANGED = 127
diff --git a/zerver/migrations/0224_alter_field_realm_video_chat_provider.py b/zerver/migrations/0224_alter_field_realm_video_chat_provider.py
index b29bf3bedff..93e2a2b5517 100644
--- a/zerver/migrations/0224_alter_field_realm_video_chat_provider.py
+++ b/zerver/migrations/0224_alter_field_realm_video_chat_provider.py
@@ -1,6 +1,6 @@
# Generated by Django 1.11.20 on 2019-05-09 06:54
-from typing import Any, Optional
+from typing import Any
from django.db import migrations, models
from django.db.backends.base.schema import BaseDatabaseSchemaEditor
@@ -26,8 +26,8 @@ VIDEO_CHAT_PROVIDERS = {
def get_video_chat_provider_detail(
providers_dict: dict[str, dict[str, Any]],
- p_name: Optional[str] = None,
- p_id: Optional[int] = None,
+ p_name: str | None = None,
+ p_id: int | None = None,
) -> dict[str, Any]:
for provider in providers_dict.values():
if p_name and provider["name"] == p_name:
diff --git a/zerver/migrations/0377_message_edit_history_format.py b/zerver/migrations/0377_message_edit_history_format.py
index e2a296854a4..8cac73d2ed0 100644
--- a/zerver/migrations/0377_message_edit_history_format.py
+++ b/zerver/migrations/0377_message_edit_history_format.py
@@ -1,5 +1,5 @@
import time
-from typing import Any, Optional, TypedDict
+from typing import Any, TypedDict
import orjson
from django.db import migrations, transaction
@@ -21,20 +21,20 @@ class LegacyEditHistoryEvent(TypedDict, total=False):
prev_subject: str
prev_topic: str
prev_content: str
- prev_rendered_content: Optional[str]
- prev_rendered_content_version: Optional[int]
+ prev_rendered_content: str | None
+ prev_rendered_content_version: int | None
class EditHistoryEvent(TypedDict, total=False):
- user_id: Optional[int]
+ user_id: int | None
timestamp: int
prev_stream: int
stream: int
prev_topic: str
topic: str
prev_content: str
- prev_rendered_content: Optional[str]
- prev_rendered_content_version: Optional[int]
+ prev_rendered_content: str | None
+ prev_rendered_content_version: int | None
@transaction.atomic
diff --git a/zerver/migrations/0544_copy_avatar_images.py b/zerver/migrations/0544_copy_avatar_images.py
index bfdbb4a8b35..f58abe9187c 100644
--- a/zerver/migrations/0544_copy_avatar_images.py
+++ b/zerver/migrations/0544_copy_avatar_images.py
@@ -1,7 +1,7 @@
import contextlib
import hashlib
import os
-from typing import Any, Optional, Union
+from typing import Any
import boto3
import pyvips
@@ -20,9 +20,9 @@ MEDIUM_AVATAR_SIZE = 500
def resize_avatar(
- image_data: Union[bytes, pyvips.Image],
+ image_data: bytes | pyvips.Image,
size: int,
-) -> Optional[bytes]:
+) -> bytes | None:
try:
source_image = pyvips.Image.new_from_buffer(image_data, "")
if source_image.width * source_image.height > IMAGE_BOMB_TOTAL_PIXELS:
diff --git a/zerver/migrations/0553_copy_emoji_images.py b/zerver/migrations/0553_copy_emoji_images.py
index ae083bd56fb..de5f2f3af6e 100644
--- a/zerver/migrations/0553_copy_emoji_images.py
+++ b/zerver/migrations/0553_copy_emoji_images.py
@@ -2,7 +2,7 @@ import contextlib
import hashlib
import logging
import os
-from typing import Any, Iterator, Optional
+from typing import Any, Iterator
import boto3
import botocore
@@ -56,7 +56,7 @@ def libvips_check_image(image_data: bytes) -> Iterator[pyvips.Image]:
# From zerver.lib.thumbnail, with minor exception changes
def resize_emoji(
image_data: bytes, emoji_file_name: str, size: int = DEFAULT_EMOJI_SIZE
-) -> tuple[bytes, Optional[bytes]]:
+) -> tuple[bytes, bytes | None]:
if len(image_data) > MAX_EMOJI_GIF_FILE_SIZE_BYTES:
raise SkipImageError(f"Image has too many bytes: {len(image_data)}")
diff --git a/zerver/models/lookups.py b/zerver/models/lookups.py
index ad308c85edd..c059997786b 100644
--- a/zerver/models/lookups.py
+++ b/zerver/models/lookups.py
@@ -1,5 +1,3 @@
-from typing import Union
-
from django.db import models
from django.db.backends.base.base import BaseDatabaseWrapper
from django.db.models.sql.compiler import SQLCompiler
@@ -13,7 +11,7 @@ class AndZero(models.Lookup[int]):
@override
def as_sql(
self, compiler: SQLCompiler, connection: BaseDatabaseWrapper
- ) -> tuple[str, list[Union[str, int]]]: # nocoverage # currently only used in migrations
+ ) -> tuple[str, list[str | int]]: # nocoverage # currently only used in migrations
lhs, lhs_params = self.process_lhs(compiler, connection)
rhs, rhs_params = self.process_rhs(compiler, connection)
return f"{lhs} & {rhs} = 0", lhs_params + rhs_params
@@ -26,7 +24,7 @@ class AndNonZero(models.Lookup[int]):
@override
def as_sql(
self, compiler: SQLCompiler, connection: BaseDatabaseWrapper
- ) -> tuple[str, list[Union[str, int]]]: # nocoverage # currently only used in migrations
+ ) -> tuple[str, list[str | int]]: # nocoverage # currently only used in migrations
lhs, lhs_params = self.process_lhs(compiler, connection)
rhs, rhs_params = self.process_rhs(compiler, connection)
return f"{lhs} & {rhs} != 0", lhs_params + rhs_params
diff --git a/zerver/models/messages.py b/zerver/models/messages.py
index 2d32a45ce3d..f88b8ffaa0d 100644
--- a/zerver/models/messages.py
+++ b/zerver/models/messages.py
@@ -3,7 +3,7 @@
import time
from datetime import timedelta
-from typing import Any, Optional
+from typing import Any
from bitfield import BitField
from bitfield.types import Bit, BitHandler
@@ -263,8 +263,8 @@ class Message(AbstractMessage):
@staticmethod
def need_to_render_content(
- rendered_content: Optional[str],
- rendered_content_version: Optional[int],
+ rendered_content: str | None,
+ rendered_content_version: int | None,
markdown_version: int,
) -> bool:
return (
@@ -644,9 +644,7 @@ class UserMessage(AbstractUserMessage):
).exists()
-def get_usermessage_by_message_id(
- user_profile: UserProfile, message_id: int
-) -> Optional[UserMessage]:
+def get_usermessage_by_message_id(user_profile: UserProfile, message_id: int) -> UserMessage | None:
try:
return UserMessage.objects.get(user_profile=user_profile, message_id=message_id)
except UserMessage.DoesNotExist:
diff --git a/zerver/models/presence.py b/zerver/models/presence.py
index a83daf83ed4..63f2923875e 100644
--- a/zerver/models/presence.py
+++ b/zerver/models/presence.py
@@ -1,7 +1,6 @@
# https://github.com/typeddjango/django-stubs/issues/1698
# mypy: disable-error-code="explicit-override"
-from typing import Optional
from django.db import models
from django.db.models import CASCADE
@@ -74,7 +73,7 @@ class UserPresence(models.Model):
]
@staticmethod
- def status_from_string(status: str) -> Optional[int]:
+ def status_from_string(status: str) -> int | None:
if status == "active":
return UserPresence.LEGACY_STATUS_ACTIVE_INT
elif status == "idle":
diff --git a/zerver/models/realm_emoji.py b/zerver/models/realm_emoji.py
index faa3292bf63..4a7f5feaa5f 100644
--- a/zerver/models/realm_emoji.py
+++ b/zerver/models/realm_emoji.py
@@ -1,4 +1,4 @@
-from typing import Optional, TypedDict
+from typing import TypedDict
from django.core.validators import MinLengthValidator, RegexValidator
from django.db import models
@@ -16,8 +16,8 @@ class EmojiInfo(TypedDict):
name: str
source_url: str
deactivated: bool
- author_id: Optional[int]
- still_url: Optional[str]
+ author_id: int | None
+ still_url: str | None
def get_all_custom_emoji_for_realm_cache_key(realm_id: int) -> str:
diff --git a/zerver/models/realms.py b/zerver/models/realms.py
index 4d543f8d387..4517f812ec9 100644
--- a/zerver/models/realms.py
+++ b/zerver/models/realms.py
@@ -1,6 +1,6 @@
from email.headerregistry import Address
from enum import IntEnum
-from typing import TYPE_CHECKING, Optional, TypedDict, Union
+from typing import TYPE_CHECKING, Optional, TypedDict
from uuid import uuid4
import django.contrib.auth
@@ -37,7 +37,7 @@ SECONDS_PER_DAY = 86400
# these values cannot change in a running production system, but do
# regularly change within unit tests; we address the latter by calling
# clear_supported_auth_backends_cache in our standard tearDown code.
-supported_backends: Optional[list["BaseBackend"]] = None
+supported_backends: list["BaseBackend"] | None = None
def supported_auth_backends() -> list["BaseBackend"]:
@@ -96,7 +96,7 @@ class OrgTypeDict(TypedDict):
id: int
hidden: bool
display_order: int
- onboarding_zulip_guide_url: Optional[str]
+ onboarding_zulip_guide_url: str | None
class CommonPolicyEnum(IntEnum):
@@ -640,7 +640,7 @@ class Realm(models.Model): # type: ignore[django-manager-missing] # django-stub
enable_guest_user_indicator = models.BooleanField(default=True)
# Define the types of the various automatically managed properties
- property_types: dict[str, Union[type, tuple[type, ...]]] = dict(
+ property_types: dict[str, type | tuple[type, ...]] = dict(
add_custom_emoji_policy=int,
allow_edit_history=bool,
allow_message_editing=bool,
@@ -920,11 +920,11 @@ class Realm(models.Model): # type: ignore[django-manager-missing] # django-stub
return self._max_invites
@max_invites.setter
- def max_invites(self, value: Optional[int]) -> None:
+ def max_invites(self, value: int | None) -> None:
self._max_invites = value
@property
- def upload_quota_gb(self) -> Optional[int]:
+ def upload_quota_gb(self) -> int | None:
# See upload_quota_bytes; don't interpret upload_quota_gb directly.
if self.custom_upload_quota_gb is not None:
@@ -951,7 +951,7 @@ class Realm(models.Model): # type: ignore[django-manager-missing] # django-stub
else:
raise AssertionError("Invalid plan type")
- def upload_quota_bytes(self) -> Optional[int]:
+ def upload_quota_bytes(self) -> int | None:
if self.upload_quota_gb is None:
return None
# We describe the quota to users in "GB" or "gigabytes", but actually apply
@@ -1120,14 +1120,14 @@ def get_realm_with_settings(realm_id: int) -> Realm:
).get(id=realm_id)
-def require_unique_names(realm: Optional[Realm]) -> bool:
+def require_unique_names(realm: Realm | None) -> bool:
if realm is None:
# realm is None when a new realm is being created.
return False
return realm.require_unique_names
-def name_changes_disabled(realm: Optional[Realm]) -> bool:
+def name_changes_disabled(realm: Realm | None) -> bool:
if realm is None:
return settings.NAME_CHANGES_DISABLED
return settings.NAME_CHANGES_DISABLED or realm.name_changes_disabled
diff --git a/zerver/models/scheduled_jobs.py b/zerver/models/scheduled_jobs.py
index 7fe7d386838..db42bdba27e 100644
--- a/zerver/models/scheduled_jobs.py
+++ b/zerver/models/scheduled_jobs.py
@@ -1,7 +1,7 @@
# https://github.com/typeddjango/django-stubs/issues/1698
# mypy: disable-error-code="explicit-override"
-from typing import TypedDict, Union
+from typing import TypedDict
from django.conf import settings
from django.db import models
@@ -213,7 +213,7 @@ class ScheduledMessage(models.Model):
def is_stream_message(self) -> bool:
return self.recipient.type == Recipient.STREAM
- def to_dict(self) -> Union[APIScheduledStreamMessageDict, APIScheduledDirectMessageDict]:
+ def to_dict(self) -> APIScheduledStreamMessageDict | APIScheduledDirectMessageDict:
recipient, recipient_type_str = get_recipient_ids(self.recipient, self.sender.id)
if recipient_type_str == "private":
diff --git a/zerver/models/users.py b/zerver/models/users.py
index f156785969c..17eec0052d1 100644
--- a/zerver/models/users.py
+++ b/zerver/models/users.py
@@ -881,7 +881,7 @@ class UserProfile(AbstractBaseUser, PermissionsMixin, UserBaseSettings):
return "{}@{}".format(self.id, self.realm.string_id or "root")
@override
- def set_password(self, password: Optional[str]) -> None:
+ def set_password(self, password: str | None) -> None:
if password is None:
self.set_unusable_password()
return
@@ -934,7 +934,7 @@ def get_user_profile_by_email(email: str) -> UserProfile:
@cache_with_key(user_profile_by_api_key_cache_key, timeout=3600 * 24 * 7)
-def maybe_get_user_profile_by_api_key(api_key: str) -> Optional[UserProfile]:
+def maybe_get_user_profile_by_api_key(api_key: str) -> UserProfile | None:
try:
return UserProfile.objects.select_related(
"realm",
@@ -1132,7 +1132,7 @@ def bot_owner_user_ids(user_profile: UserProfile) -> set[int]:
return users
-def get_source_profile(email: str, realm_id: int) -> Optional[UserProfile]:
+def get_source_profile(email: str, realm_id: int) -> UserProfile | None:
from zerver.models import Realm
from zerver.models.realms import get_realm_by_id
diff --git a/zerver/openapi/curl_param_value_generators.py b/zerver/openapi/curl_param_value_generators.py
index 3593165049a..da23d6074fe 100644
--- a/zerver/openapi/curl_param_value_generators.py
+++ b/zerver/openapi/curl_param_value_generators.py
@@ -6,7 +6,7 @@
# fetching of appropriate parameter values to use when running the
# cURL examples as part of the tools/test-api test suite.
from functools import wraps
-from typing import Any, Callable, Optional
+from typing import Any, Callable
from django.utils.timezone import now as timezone_now
@@ -73,8 +73,8 @@ def assert_all_helper_functions_called() -> None:
def patch_openapi_example_values(
entry: str,
parameters: list[Parameter],
- request_body: Optional[dict[str, Any]] = None,
-) -> tuple[list[Parameter], Optional[dict[str, object]]]:
+ request_body: dict[str, Any] | None = None,
+) -> tuple[list[Parameter], dict[str, object] | None]:
if entry not in GENERATOR_FUNCTIONS:
return parameters, request_body
func = GENERATOR_FUNCTIONS[entry]
diff --git a/zerver/openapi/markdown_extension.py b/zerver/openapi/markdown_extension.py
index 9ea2b0c803b..1fc5abd011d 100644
--- a/zerver/openapi/markdown_extension.py
+++ b/zerver/openapi/markdown_extension.py
@@ -10,7 +10,7 @@ import json
import re
import shlex
from textwrap import dedent
-from typing import Any, Mapping, Match, Optional, Pattern
+from typing import Any, Mapping, Match, Pattern
import markdown
from django.conf import settings
@@ -268,8 +268,8 @@ def generate_curl_example(
api_url: str,
auth_email: str = DEFAULT_AUTH_EMAIL,
auth_api_key: str = DEFAULT_AUTH_API_KEY,
- exclude: Optional[list[str]] = None,
- include: Optional[list[str]] = None,
+ exclude: list[str] | None = None,
+ include: list[str] | None = None,
) -> list[str]:
lines = ["```curl"]
operation = endpoint + ":" + method.lower()
@@ -398,7 +398,7 @@ SUPPORTED_LANGUAGES: dict[str, Any] = {
class APIMarkdownExtension(Extension):
- def __init__(self, api_url: Optional[str]) -> None:
+ def __init__(self, api_url: str | None) -> None:
self.config = {
"api_url": [
api_url,
diff --git a/zerver/openapi/openapi.py b/zerver/openapi/openapi.py
index 47e4b6e01d0..d2c23216e36 100644
--- a/zerver/openapi/openapi.py
+++ b/zerver/openapi/openapi.py
@@ -8,7 +8,7 @@
import json
import os
import re
-from typing import Any, Literal, Mapping, Optional, Union
+from typing import Any, Literal, Mapping
import orjson
from openapi_core import OpenAPI
@@ -75,10 +75,10 @@ def naively_merge_allOf_dict(obj: dict[str, object]) -> dict[str, object]:
class OpenAPISpec:
def __init__(self, openapi_path: str) -> None:
self.openapi_path = openapi_path
- self.mtime: Optional[float] = None
+ self.mtime: float | None = None
self._openapi: dict[str, Any] = {}
self._endpoints_dict: dict[str, str] = {}
- self._spec: Optional[OpenAPI] = None
+ self._spec: OpenAPI | None = None
def check_reload(self) -> None:
# Because importing yaml takes significant time, and we only
@@ -232,7 +232,7 @@ def check_requires_administrator(endpoint: str, method: str) -> bool:
)
-def check_additional_imports(endpoint: str, method: str) -> Optional[list[str]]:
+def check_additional_imports(endpoint: str, method: str) -> list[str] | None:
"""Fetch the additional imports required for an endpoint."""
return openapi_spec.openapi()["paths"][endpoint][method.lower()].get(
"x-python-examples-extra-imports", None
@@ -413,7 +413,7 @@ def get_openapi_return_values(endpoint: str, method: str) -> dict[str, Any]:
return schema["properties"]
-def find_openapi_endpoint(path: str) -> Optional[str]:
+def find_openapi_endpoint(path: str) -> str | None:
for path_regex, endpoint in openapi_spec.endpoints_dict().items():
matches = re.match(path_regex, path)
if matches:
@@ -541,7 +541,7 @@ SKIP_JSON = {
def validate_request(
url: str,
method: str,
- data: Union[str, bytes, Mapping[str, Any]],
+ data: str | bytes | Mapping[str, Any],
http_headers: dict[str, str],
json_url: bool,
status_code: str,
diff --git a/zerver/signals.py b/zerver/signals.py
index bcabc978215..b6b46f859fa 100644
--- a/zerver/signals.py
+++ b/zerver/signals.py
@@ -1,4 +1,4 @@
-from typing import Any, Optional
+from typing import Any
import zoneinfo
from django.conf import settings
@@ -17,7 +17,7 @@ from zerver.models import UserProfile
JUST_CREATED_THRESHOLD = 60
-def get_device_browser(user_agent: str) -> Optional[str]:
+def get_device_browser(user_agent: str) -> str | None:
user_agent = user_agent.lower()
if "zulip" in user_agent:
return "Zulip"
@@ -39,7 +39,7 @@ def get_device_browser(user_agent: str) -> Optional[str]:
return None
-def get_device_os(user_agent: str) -> Optional[str]:
+def get_device_os(user_agent: str) -> str | None:
user_agent = user_agent.lower()
if "windows" in user_agent:
return "Windows"
@@ -115,7 +115,7 @@ def email_on_new_login(sender: Any, user: UserProfile, request: Any, **kwargs: A
@receiver(user_logged_out)
def clear_zoom_token_on_logout(
- sender: object, *, user: Optional[UserProfile], **kwargs: object
+ sender: object, *, user: UserProfile | None, **kwargs: object
) -> None:
# Loaded lazily so django.setup() succeeds before static asset generation
from zerver.actions.video_calls import do_set_zoom_token
diff --git a/zerver/tests/test_audit_log.py b/zerver/tests/test_audit_log.py
index 7aa93ce6bb1..d542e5219be 100644
--- a/zerver/tests/test_audit_log.py
+++ b/zerver/tests/test_audit_log.py
@@ -1,5 +1,5 @@
from datetime import timedelta
-from typing import Any, Union
+from typing import Any
from django.contrib.auth.password_validation import validate_password
from django.utils.timezone import now as timezone_now
@@ -772,7 +772,7 @@ class TestRealmAuditLog(ZulipTestCase):
def test_change_user_settings(self) -> None:
user = self.example_user("hamlet")
- value: Union[bool, int, str]
+ value: bool | int | str
test_values = dict(
default_language="de",
web_home_view="all_messages",
diff --git a/zerver/tests/test_auth_backends.py b/zerver/tests/test_auth_backends.py
index 86fec399947..50715016fe3 100644
--- a/zerver/tests/test_auth_backends.py
+++ b/zerver/tests/test_auth_backends.py
@@ -9,7 +9,7 @@ from abc import ABC, abstractmethod
from contextlib import contextmanager
from datetime import timedelta
from email.headerregistry import Address
-from typing import TYPE_CHECKING, Any, Callable, Iterable, Iterator, Mapping, Optional, Sequence
+from typing import TYPE_CHECKING, Any, Callable, Iterable, Iterator, Mapping, Sequence
from unittest import mock
from urllib.parse import parse_qs, urlencode, urlsplit
@@ -172,7 +172,7 @@ class AuthBackendTest(ZulipTestCase):
backend: Any,
*,
good_kwargs: dict[str, Any],
- bad_kwargs: Optional[dict[str, Any]] = None,
+ bad_kwargs: dict[str, Any] | None = None,
) -> None:
clear_supported_auth_backends_cache()
user_profile = self.example_user("hamlet")
@@ -508,7 +508,7 @@ class RateLimitAuthenticationTests(ZulipTestCase):
@override_settings(RATE_LIMITING_AUTHENTICATE=True)
def do_test_auth_rate_limiting(
self,
- attempt_authentication_func: Callable[[HttpRequest, str, str], Optional[UserProfile]],
+ attempt_authentication_func: Callable[[HttpRequest, str, str], UserProfile | None],
username: str,
correct_password: str,
wrong_password: str,
@@ -522,7 +522,7 @@ class RateLimitAuthenticationTests(ZulipTestCase):
def _mock_key(self: RateLimitedAuthenticationByUsername) -> str:
return f"{salt}:{original_key_method(self)}"
- def attempt_authentication(username: str, password: str) -> Optional[UserProfile]:
+ def attempt_authentication(username: str, password: str) -> UserProfile | None:
request = HttpRequest()
request.session = mock.MagicMock()
return attempt_authentication_func(request, username, password)
@@ -574,7 +574,7 @@ class RateLimitAuthenticationTests(ZulipTestCase):
def attempt_authentication(
request: HttpRequest, username: str, password: str
- ) -> Optional[UserProfile]:
+ ) -> UserProfile | None:
return EmailAuthBackend().authenticate(
request=request,
username=username,
@@ -601,7 +601,7 @@ class RateLimitAuthenticationTests(ZulipTestCase):
def attempt_authentication(
request: HttpRequest, username: str, password: str
- ) -> Optional[UserProfile]:
+ ) -> UserProfile | None:
return ZulipLDAPAuthBackend().authenticate(
request=request,
username=username,
@@ -636,7 +636,7 @@ class RateLimitAuthenticationTests(ZulipTestCase):
def attempt_authentication(
request: HttpRequest, username: str, password: str
- ) -> Optional[UserProfile]:
+ ) -> UserProfile | None:
user = authenticate(
request=request,
username=username,
@@ -781,15 +781,15 @@ class SocialAuthBase(DesktopFlowTestingLib, ZulipTestCase, ABC):
def prepare_login_url_and_headers(
self,
subdomain: str,
- mobile_flow_otp: Optional[str] = None,
- desktop_flow_otp: Optional[str] = None,
+ mobile_flow_otp: str | None = None,
+ desktop_flow_otp: str | None = None,
is_signup: bool = False,
next: str = "",
multiuse_object_key: str = "",
- alternative_start_url: Optional[str] = None,
+ alternative_start_url: str | None = None,
*,
- user_agent: Optional[str] = None,
- extra_headers: Optional[dict[str, Any]] = None,
+ user_agent: str | None = None,
+ extra_headers: dict[str, Any] | None = None,
) -> tuple[str, dict[str, Any]]:
url = self.LOGIN_URL
if alternative_start_url is not None:
@@ -848,15 +848,15 @@ class SocialAuthBase(DesktopFlowTestingLib, ZulipTestCase, ABC):
account_data_dict: dict[str, str],
*,
subdomain: str,
- mobile_flow_otp: Optional[str] = None,
- desktop_flow_otp: Optional[str] = None,
+ mobile_flow_otp: str | None = None,
+ desktop_flow_otp: str | None = None,
is_signup: bool = False,
next: str = "",
multiuse_object_key: str = "",
expect_choose_email_screen: bool = False,
- alternative_start_url: Optional[str] = None,
- user_agent: Optional[str] = None,
- extra_headers: Optional[dict[str, Any]] = None,
+ alternative_start_url: str | None = None,
+ user_agent: str | None = None,
+ extra_headers: dict[str, Any] | None = None,
**extra_data: Any,
) -> "TestHttpResponse":
"""Main entry point for all social authentication tests.
@@ -1054,7 +1054,7 @@ class SocialAuthBase(DesktopFlowTestingLib, ZulipTestCase, ABC):
def custom_auth_wrapper(
auth_func: AuthFuncT, *args: Any, **kwargs: Any
- ) -> Optional[UserProfile]:
+ ) -> UserProfile | None:
nonlocal backends_with_restriction
backend = args[0]
@@ -1104,7 +1104,7 @@ class SocialAuthBase(DesktopFlowTestingLib, ZulipTestCase, ABC):
def custom_auth_wrapper_none(
auth_func: AuthFuncT, *args: Any, **kwargs: Any
- ) -> Optional[UserProfile]:
+ ) -> UserProfile | None:
return None
with self.settings(CUSTOM_AUTHENTICATION_WRAPPER_FUNCTION=custom_auth_wrapper_none):
@@ -1313,7 +1313,7 @@ class SocialAuthBase(DesktopFlowTestingLib, ZulipTestCase, ABC):
def test_social_auth_session_fields_cleared_correctly(self) -> None:
mobile_flow_otp = "1234abcd" * 8
- def initiate_auth(mobile_flow_otp: Optional[str] = None) -> None:
+ def initiate_auth(mobile_flow_otp: str | None = None) -> None:
url, headers = self.prepare_login_url_and_headers(
subdomain="zulip", mobile_flow_otp=mobile_flow_otp
)
@@ -1378,8 +1378,8 @@ class SocialAuthBase(DesktopFlowTestingLib, ZulipTestCase, ABC):
name: str,
expected_final_name: str,
skip_registration_form: bool,
- mobile_flow_otp: Optional[str] = None,
- desktop_flow_otp: Optional[str] = None,
+ mobile_flow_otp: str | None = None,
+ desktop_flow_otp: str | None = None,
expect_confirm_registration_page: bool = False,
expect_full_name_prepopulated: bool = True,
) -> None:
@@ -1924,14 +1924,14 @@ class SAMLAuthBackendTest(SocialAuthBase):
account_data_dict: dict[str, str],
*,
subdomain: str,
- mobile_flow_otp: Optional[str] = None,
- desktop_flow_otp: Optional[str] = None,
+ mobile_flow_otp: str | None = None,
+ desktop_flow_otp: str | None = None,
is_signup: bool = False,
next: str = "",
multiuse_object_key: str = "",
- user_agent: Optional[str] = None,
+ user_agent: str | None = None,
extra_attributes: Mapping[str, list[str]] = {},
- extra_headers: Optional[dict[str, Any]] = None,
+ extra_headers: dict[str, Any] | None = None,
**extra_data: Any,
) -> "TestHttpResponse":
url, headers = self.prepare_login_url_and_headers(
@@ -3268,7 +3268,7 @@ class AppleAuthMixin:
AUTH_FINISH_URL = "/complete/apple/"
def generate_id_token(
- self, account_data_dict: dict[str, str], audience: Optional[str] = None
+ self, account_data_dict: dict[str, str], audience: str | None = None
) -> str:
payload = dict(email=account_data_dict["email"])
@@ -3436,17 +3436,17 @@ class AppleAuthBackendNativeFlowTest(AppleAuthMixin, SocialAuthBase):
def prepare_login_url_and_headers(
self,
subdomain: str,
- mobile_flow_otp: Optional[str] = None,
- desktop_flow_otp: Optional[str] = None,
+ mobile_flow_otp: str | None = None,
+ desktop_flow_otp: str | None = None,
is_signup: bool = False,
next: str = "",
multiuse_object_key: str = "",
- alternative_start_url: Optional[str] = None,
- id_token: Optional[str] = None,
+ alternative_start_url: str | None = None,
+ id_token: str | None = None,
account_data_dict: Mapping[str, str] = {},
*,
- user_agent: Optional[str] = None,
- extra_headers: Optional[dict[str, Any]] = None,
+ user_agent: str | None = None,
+ extra_headers: dict[str, Any] | None = None,
) -> tuple[str, dict[str, Any]]:
url, headers = super().prepare_login_url_and_headers(
subdomain,
@@ -3482,15 +3482,15 @@ class AppleAuthBackendNativeFlowTest(AppleAuthMixin, SocialAuthBase):
account_data_dict: dict[str, str],
*,
subdomain: str,
- mobile_flow_otp: Optional[str] = None,
- desktop_flow_otp: Optional[str] = None,
+ mobile_flow_otp: str | None = None,
+ desktop_flow_otp: str | None = None,
is_signup: bool = False,
next: str = "",
multiuse_object_key: str = "",
- alternative_start_url: Optional[str] = None,
+ alternative_start_url: str | None = None,
skip_id_token: bool = False,
- user_agent: Optional[str] = None,
- extra_headers: Optional[dict[str, Any]] = None,
+ user_agent: str | None = None,
+ extra_headers: dict[str, Any] | None = None,
**extra_data: Any,
) -> "TestHttpResponse":
"""In Apple's native authentication flow, the client app authenticates
@@ -3506,7 +3506,7 @@ class AppleAuthBackendNativeFlowTest(AppleAuthMixin, SocialAuthBase):
"""
if not skip_id_token:
- id_token: Optional[str] = self.generate_id_token(
+ id_token: str | None = self.generate_id_token(
account_data_dict, settings.SOCIAL_AUTH_APPLE_APP_ID
)
else:
@@ -3561,7 +3561,7 @@ class AppleAuthBackendNativeFlowTest(AppleAuthMixin, SocialAuthBase):
mobile_flow_otp = "1234abcd" * 8
account_data_dict = self.get_account_data_dict(email=self.email, name=self.name)
- def initiate_auth(mobile_flow_otp: Optional[str] = None) -> None:
+ def initiate_auth(mobile_flow_otp: str | None = None) -> None:
url, headers = self.prepare_login_url_and_headers(
subdomain="zulip",
id_token="invalid",
@@ -3737,7 +3737,7 @@ class GenericOpenIdConnectTest(SocialAuthBase):
)
@override
- def get_account_data_dict(self, email: str, name: Optional[str]) -> dict[str, Any]:
+ def get_account_data_dict(self, email: str, name: str | None) -> dict[str, Any]:
if name is not None:
name_parts = name.split(" ")
given_name = name_parts[0]
@@ -4525,7 +4525,7 @@ class GoogleAuthBackendTest(SocialAuthBase):
data: ExternalAuthDataDict,
*,
subdomain: str = "zulip",
- force_token: Optional[str] = None,
+ force_token: str | None = None,
) -> "TestHttpResponse":
if force_token is None:
token = ExternalAuthResult(data_dict=data).store_data()
@@ -7642,7 +7642,7 @@ class TestCustomAuthDecorator(ZulipTestCase):
def custom_auth_wrapper(
auth_func: AuthFuncT, *args: Any, **kwargs: Any
- ) -> Optional[UserProfile]:
+ ) -> UserProfile | None:
nonlocal call_count
nonlocal backends_with_restriction
call_count += 1
diff --git a/zerver/tests/test_bots.py b/zerver/tests/test_bots.py
index e5fccbe3bbb..9ad1ae31be0 100644
--- a/zerver/tests/test_bots.py
+++ b/zerver/tests/test_bots.py
@@ -1,6 +1,6 @@
import filecmp
import os
-from typing import Any, Optional
+from typing import Any
from unittest.mock import MagicMock, patch
import orjson
@@ -25,7 +25,7 @@ from zerver.models.users import get_user, is_cross_realm_bot_email
# A test validator
-def _check_string(var_name: str, val: str) -> Optional[str]:
+def _check_string(var_name: str, val: str) -> str | None:
if val.startswith("_"):
return f'{var_name} starts with a "_" and is hence invalid.'
return None
diff --git a/zerver/tests/test_cache.py b/zerver/tests/test_cache.py
index 65268608c90..69a2a452b4c 100644
--- a/zerver/tests/test_cache.py
+++ b/zerver/tests/test_cache.py
@@ -1,4 +1,3 @@
-from typing import Optional
from unittest.mock import Mock, patch
from django.conf import settings
@@ -139,7 +138,7 @@ class CacheWithKeyDecoratorTest(ZulipTestCase):
return f"CacheWithKeyDecoratorTest:test_cache_with_key_none_values:{user_id}"
@cache_with_key(cache_key_function, timeout=1000)
- def get_user_function_can_return_none(user_id: int) -> Optional[UserProfile]:
+ def get_user_function_can_return_none(user_id: int) -> UserProfile | None:
try:
return UserProfile.objects.get(id=user_id)
except UserProfile.DoesNotExist:
diff --git a/zerver/tests/test_custom_profile_data.py b/zerver/tests/test_custom_profile_data.py
index 57102e1b9e4..776e3e94b7a 100644
--- a/zerver/tests/test_custom_profile_data.py
+++ b/zerver/tests/test_custom_profile_data.py
@@ -1,4 +1,4 @@
-from typing import Any, Iterable, Optional, Union, cast
+from typing import Any, Iterable, cast
from unittest import mock
import orjson
@@ -100,7 +100,7 @@ class CreateCustomProfileFieldTest(CustomProfileFieldTestCase):
def test_create_select_field(self) -> None:
self.login("iago")
- data: dict[str, Union[str, int]] = {}
+ data: dict[str, str | int] = {}
data["name"] = "Favorite programming language"
data["field_type"] = CustomProfileField.SELECT
@@ -241,7 +241,7 @@ class CreateCustomProfileFieldTest(CustomProfileFieldTestCase):
def test_create_external_account_field(self) -> None:
self.login("iago")
realm = get_realm("zulip")
- data: dict[str, Union[str, int, dict[str, str]]] = {}
+ data: dict[str, str | int | dict[str, str]] = {}
data["name"] = "Twitter username"
data["field_type"] = CustomProfileField.EXTERNAL_ACCOUNT
@@ -724,7 +724,7 @@ class UpdateCustomProfileFieldTest(CustomProfileFieldTestCase):
def test_update_profile_data_successfully(self) -> None:
self.login("iago")
realm = get_realm("zulip")
- fields: list[tuple[str, Union[str, list[int]]]] = [
+ fields: list[tuple[str, str | list[int]]] = [
("Phone number", "*short* text data"),
("Biography", "~~short~~ **long** text data"),
("Favorite food", "long short text data"),
@@ -738,7 +738,7 @@ class UpdateCustomProfileFieldTest(CustomProfileFieldTestCase):
data: list[ProfileDataElementUpdateDict] = []
expected_value: dict[int, ProfileDataElementValue] = {}
- expected_rendered_value: dict[int, Optional[str]] = {}
+ expected_rendered_value: dict[int, str | None] = {}
for i, field_value in enumerate(fields):
name, value = field_value
field = CustomProfileField.objects.get(name=name, realm=realm)
diff --git a/zerver/tests/test_decorators.py b/zerver/tests/test_decorators.py
index bd80a63e7e0..5e536129dbd 100644
--- a/zerver/tests/test_decorators.py
+++ b/zerver/tests/test_decorators.py
@@ -3,7 +3,7 @@ import os
import re
import uuid
from collections import defaultdict
-from typing import TYPE_CHECKING, Any, Callable, Optional, Union
+from typing import TYPE_CHECKING, Any, Callable
from unittest import mock, skipUnless
import orjson
@@ -468,7 +468,7 @@ class RateLimitTestCase(ZulipTestCase):
@staticmethod
@public_json_view
def ratelimited_json_view(
- req: HttpRequest, maybe_user_profile: Union[AnonymousUser, UserProfile], /
+ req: HttpRequest, maybe_user_profile: AnonymousUser | UserProfile, /
) -> HttpResponse:
return HttpResponse("some value")
@@ -1235,7 +1235,7 @@ class TestPublicJsonViewDecorator(ZulipTestCase):
@public_json_view
def public_view(
- request: HttpRequest, maybe_user_profile: Union[UserProfile, AnonymousUser]
+ request: HttpRequest, maybe_user_profile: UserProfile | AnonymousUser
) -> HttpResponse:
self.assertEqual(maybe_user_profile, hamlet)
return json_success(request)
@@ -1543,7 +1543,7 @@ class TestRequestNotes(ZulipTestCase):
depending on the subdomain.
"""
- def mock_home(expected_realm: Optional[Realm]) -> Callable[[HttpRequest], HttpResponse]:
+ def mock_home(expected_realm: Realm | None) -> Callable[[HttpRequest], HttpResponse]:
def inner(request: HttpRequest) -> HttpResponse:
self.assertEqual(RequestNotes.get_notes(request).realm, expected_realm)
return HttpResponse()
diff --git a/zerver/tests/test_delete_unclaimed_attachments.py b/zerver/tests/test_delete_unclaimed_attachments.py
index cbb3c5cadc5..61cb0d2b289 100644
--- a/zerver/tests/test_delete_unclaimed_attachments.py
+++ b/zerver/tests/test_delete_unclaimed_attachments.py
@@ -2,7 +2,6 @@ import os
import re
from datetime import datetime, timedelta
from io import StringIO
-from typing import Optional
import time_machine
from django.conf import settings
@@ -19,7 +18,7 @@ from zerver.models.clients import get_client
class UnclaimedAttachmentTest(UploadSerializeMixin, ZulipTestCase):
def make_attachment(
- self, filename: str, when: Optional[datetime] = None, uploader: Optional[UserProfile] = None
+ self, filename: str, when: datetime | None = None, uploader: UserProfile | None = None
) -> Attachment:
if when is None:
when = timezone_now() - timedelta(weeks=2)
diff --git a/zerver/tests/test_drafts.py b/zerver/tests/test_drafts.py
index c86d13430d6..50e0c381bba 100644
--- a/zerver/tests/test_drafts.py
+++ b/zerver/tests/test_drafts.py
@@ -1,6 +1,6 @@
import time
from copy import deepcopy
-from typing import Any, Optional
+from typing import Any
import orjson
@@ -12,7 +12,7 @@ class DraftCreationTests(ZulipTestCase):
def create_and_check_drafts_for_success(
self,
draft_dicts: list[dict[str, Any]],
- expected_draft_dicts: Optional[list[dict[str, Any]]] = None,
+ expected_draft_dicts: list[dict[str, Any]] | None = None,
) -> None:
hamlet = self.example_user("hamlet")
diff --git a/zerver/tests/test_email_mirror.py b/zerver/tests/test_email_mirror.py
index 9438ee2a9c7..520414dbb69 100644
--- a/zerver/tests/test_email_mirror.py
+++ b/zerver/tests/test_email_mirror.py
@@ -5,7 +5,7 @@ import subprocess
from email import message_from_string
from email.headerregistry import Address
from email.message import EmailMessage, MIMEPart
-from typing import TYPE_CHECKING, Any, Callable, Mapping, Optional
+from typing import TYPE_CHECKING, Any, Callable, Mapping
from unittest import mock
import orjson
@@ -1527,7 +1527,7 @@ class TestEmailMirrorTornadoView(ZulipTestCase):
def check_queue_json_publish(
queue_name: str,
event: Mapping[str, Any],
- processor: Optional[Callable[[Any], None]] = None,
+ processor: Callable[[Any], None] | None = None,
) -> None:
self.assertEqual(queue_name, "email_mirror")
self.assertEqual(event, {"rcpt_to": to_address, "msg_base64": msg_base64})
diff --git a/zerver/tests/test_events.py b/zerver/tests/test_events.py
index 343060aea0e..69a70bd27d7 100644
--- a/zerver/tests/test_events.py
+++ b/zerver/tests/test_events.py
@@ -9,7 +9,7 @@ import time
from contextlib import contextmanager
from datetime import timedelta
from io import StringIO
-from typing import Any, Iterator, Optional
+from typing import Any, Iterator
from unittest import mock
import orjson
@@ -276,7 +276,7 @@ class BaseAction(ZulipTestCase):
def verify_action(
self,
*,
- event_types: Optional[list[str]] = None,
+ event_types: list[str] | None = None,
include_subscribers: bool = True,
state_change_expected: bool = True,
notification_settings_null: bool = False,
diff --git a/zerver/tests/test_external.py b/zerver/tests/test_external.py
index a409824ae83..f99609dd768 100644
--- a/zerver/tests/test_external.py
+++ b/zerver/tests/test_external.py
@@ -1,7 +1,7 @@
import time
import uuid
from contextlib import contextmanager
-from typing import IO, TYPE_CHECKING, Any, Callable, Iterator, Optional, Sequence
+from typing import IO, TYPE_CHECKING, Any, Callable, Iterator, Sequence
from unittest import mock, skipUnless
import DNS
@@ -291,7 +291,7 @@ class RateLimitTests(ZulipTestCase):
@contextmanager
def tor_mock(
self,
- side_effect: Optional[Exception] = None,
+ side_effect: Exception | None = None,
read_data: Sequence[str] = ["1.2.3.4", "5.6.7.8"],
) -> Iterator[mock.Mock]:
# We need to reset the circuitbreaker before starting. We
diff --git a/zerver/tests/test_has_request_variables.py b/zerver/tests/test_has_request_variables.py
index 41093404770..2bfb494ffd1 100644
--- a/zerver/tests/test_has_request_variables.py
+++ b/zerver/tests/test_has_request_variables.py
@@ -1,4 +1,4 @@
-from typing import Any, Optional, Sequence
+from typing import Any, Sequence
import orjson
from django.http import HttpRequest, HttpResponse
@@ -160,8 +160,8 @@ class TestIgnoredParametersUnsupported(ZulipTestCase):
@has_request_variables
def test_view(
request: HttpRequest,
- name: Optional[str] = REQ(default=None),
- age: Optional[int] = 0,
+ name: str | None = REQ(default=None),
+ age: int | None = 0,
) -> HttpResponse:
return json_success(request)
diff --git a/zerver/tests/test_import_export.py b/zerver/tests/test_import_export.py
index d1f675263b5..0e62db8a2d4 100644
--- a/zerver/tests/test_import_export.py
+++ b/zerver/tests/test_import_export.py
@@ -4,7 +4,7 @@ import shutil
import uuid
from collections import defaultdict
from datetime import datetime, timedelta, timezone
-from typing import Any, Callable, Iterable, Optional
+from typing import Any, Callable, Iterable
from unittest.mock import patch
import orjson
@@ -321,8 +321,8 @@ class RealmImportExportTest(ExportFile):
def export_realm(
self,
realm: Realm,
- exportable_user_ids: Optional[set[int]] = None,
- consent_message_id: Optional[int] = None,
+ exportable_user_ids: set[int] | None = None,
+ consent_message_id: int | None = None,
public_only: bool = False,
) -> None:
output_dir = make_export_output_dir()
@@ -351,8 +351,8 @@ class RealmImportExportTest(ExportFile):
def export_realm_and_create_auditlog(
self,
original_realm: Realm,
- exportable_user_ids: Optional[set[int]] = None,
- consent_message_id: Optional[int] = None,
+ exportable_user_ids: set[int] | None = None,
+ consent_message_id: int | None = None,
public_only: bool = False,
) -> None:
RealmAuditLog.objects.create(
@@ -1560,7 +1560,7 @@ class RealmImportExportTest(ExportFile):
def mock_send_to_push_bouncer_response( # type: ignore[return]
method: str, *args: Any
- ) -> Optional[dict[str, int]]:
+ ) -> dict[str, int] | None:
if method == "GET":
return get_response
diff --git a/zerver/tests/test_invite.py b/zerver/tests/test_invite.py
index aa725b34d24..a91862df376 100644
--- a/zerver/tests/test_invite.py
+++ b/zerver/tests/test_invite.py
@@ -1,6 +1,6 @@
import re
from datetime import datetime, timedelta
-from typing import TYPE_CHECKING, Optional, Sequence, Union
+from typing import TYPE_CHECKING, Sequence
from unittest.mock import patch
from urllib.parse import quote, urlencode
@@ -176,11 +176,11 @@ class InviteUserBase(ZulipTestCase):
invitee_emails: str,
stream_names: Sequence[str],
notify_referrer_on_join: bool = True,
- invite_expires_in_minutes: Optional[int] = INVITATION_LINK_VALIDITY_MINUTES,
+ invite_expires_in_minutes: int | None = INVITATION_LINK_VALIDITY_MINUTES,
body: str = "",
invite_as: int = PreregistrationUser.INVITE_AS["MEMBER"],
include_realm_default_subscriptions: bool = False,
- realm: Optional[Realm] = None,
+ realm: Realm | None = None,
) -> "TestHttpResponse":
"""
Invites the specified users to Zulip with the specified streams.
@@ -192,7 +192,7 @@ class InviteUserBase(ZulipTestCase):
"""
stream_ids = [self.get_stream_id(stream_name, realm=realm) for stream_name in stream_names]
- invite_expires_in: Union[str, Optional[int]] = invite_expires_in_minutes
+ invite_expires_in: str | int | None = invite_expires_in_minutes
if invite_expires_in is None:
invite_expires_in = orjson.dumps(None).decode()
@@ -258,7 +258,7 @@ class InviteUserTest(InviteUserBase):
new_realm_max: int,
realm_max: int,
open_realm_creation: bool = True,
- realm: Optional[Realm] = None,
+ realm: Realm | None = None,
stream_name: str = "Denmark",
) -> "TestHttpResponse":
if realm is None:
@@ -2446,8 +2446,8 @@ class MultiuseInviteTest(ZulipTestCase):
def generate_multiuse_invite_link(
self,
- streams: Optional[list[Stream]] = None,
- date_sent: Optional[datetime] = None,
+ streams: list[Stream] | None = None,
+ date_sent: datetime | None = None,
include_realm_default_subscriptions: bool = False,
) -> str:
invite = MultiuseInvite(
diff --git a/zerver/tests/test_link_embed.py b/zerver/tests/test_link_embed.py
index 9c587d406f1..7cce4570868 100644
--- a/zerver/tests/test_link_embed.py
+++ b/zerver/tests/test_link_embed.py
@@ -1,6 +1,6 @@
import re
from collections import OrderedDict
-from typing import Any, Optional, Union
+from typing import Any
from unittest import mock
from urllib.parse import parse_qsl, urlencode, urlsplit, urlunsplit
@@ -330,7 +330,7 @@ class PreviewTestCase(ZulipTestCase):
status: int = 200,
relative_url: bool = False,
content_type: str = "text/html",
- body: Optional[Union[str, ConnectionError]] = None,
+ body: str | ConnectionError | None = None,
) -> None:
if body is None:
body = cls.open_graph_html
diff --git a/zerver/tests/test_management_commands.py b/zerver/tests/test_management_commands.py
index c53f90a7afa..74cb1859ebf 100644
--- a/zerver/tests/test_management_commands.py
+++ b/zerver/tests/test_management_commands.py
@@ -1,7 +1,7 @@
import os
import re
from datetime import timedelta
-from typing import Any, Optional
+from typing import Any
from unittest import mock, skipUnless
from unittest.mock import MagicMock, call, patch
from urllib.parse import quote, quote_plus
@@ -89,7 +89,7 @@ class TestZulipBaseCommand(ZulipTestCase):
self.assertEqual(get_user_profile_by_email(email), user_profile)
def get_users_sorted(
- self, options: dict[str, Any], realm: Optional[Realm], **kwargs: Any
+ self, options: dict[str, Any], realm: Realm | None, **kwargs: Any
) -> list[UserProfile]:
user_profiles = self.command.get_users(options, realm, **kwargs)
return sorted(user_profiles, key=lambda x: x.email)
diff --git a/zerver/tests/test_markdown.py b/zerver/tests/test_markdown.py
index 505377514f4..565c9fe52a5 100644
--- a/zerver/tests/test_markdown.py
+++ b/zerver/tests/test_markdown.py
@@ -3,7 +3,7 @@ import os
import re
from html import escape
from textwrap import dedent
-from typing import Any, Optional
+from typing import Any
from unittest import mock
import orjson
@@ -75,7 +75,7 @@ class SimulatedFencedBlockPreprocessor(FencedBlockPreprocessor):
# Simulate code formatting.
@override
- def format_code(self, lang: Optional[str], code: str) -> str:
+ def format_code(self, lang: str | None, code: str) -> str:
return (lang or "") + ":" + code
@override
diff --git a/zerver/tests/test_message_delete.py b/zerver/tests/test_message_delete.py
index 2b5e310fb55..f06a722d2be 100644
--- a/zerver/tests/test_message_delete.py
+++ b/zerver/tests/test_message_delete.py
@@ -1,5 +1,5 @@
from datetime import timedelta
-from typing import TYPE_CHECKING, Optional, Union
+from typing import TYPE_CHECKING
from unittest import mock
import orjson
@@ -29,7 +29,7 @@ class DeleteMessageTest(ZulipTestCase):
def test_delete_message_by_user(self) -> None:
def set_message_deleting_params(
- delete_own_message_policy: int, message_content_delete_limit_seconds: Union[int, str]
+ delete_own_message_policy: int, message_content_delete_limit_seconds: int | str
) -> None:
self.login("iago")
result = self.client_patch(
@@ -136,7 +136,7 @@ class DeleteMessageTest(ZulipTestCase):
cordelia = self.example_user("cordelia")
def set_message_deleting_params(
- delete_own_message_policy: int, message_content_delete_limit_seconds: Union[int, str]
+ delete_own_message_policy: int, message_content_delete_limit_seconds: int | str
) -> None:
result = self.api_patch(
iago,
@@ -223,9 +223,7 @@ class DeleteMessageTest(ZulipTestCase):
self.assert_json_success(result)
def test_delete_message_according_to_delete_own_message_policy(self) -> None:
- def check_delete_message_by_sender(
- sender_name: str, error_msg: Optional[str] = None
- ) -> None:
+ def check_delete_message_by_sender(sender_name: str, error_msg: str | None = None) -> None:
sender = self.example_user(sender_name)
msg_id = self.send_stream_message(sender, "Verona")
self.login_user(sender)
diff --git a/zerver/tests/test_message_edit.py b/zerver/tests/test_message_edit.py
index 9300825e951..65ba813542d 100644
--- a/zerver/tests/test_message_edit.py
+++ b/zerver/tests/test_message_edit.py
@@ -1,6 +1,5 @@
from datetime import timedelta
from operator import itemgetter
-from typing import Union
from unittest import mock
import orjson
@@ -887,7 +886,7 @@ class EditMessageTest(ZulipTestCase):
def test_edit_message_content_limit(self) -> None:
def set_message_editing_params(
allow_message_editing: bool,
- message_content_edit_limit_seconds: Union[int, str],
+ message_content_edit_limit_seconds: int | str,
edit_topic_policy: int,
) -> None:
result = self.client_patch(
@@ -975,7 +974,7 @@ class EditMessageTest(ZulipTestCase):
def test_edit_topic_policy(self) -> None:
def set_message_editing_params(
allow_message_editing: bool,
- message_content_edit_limit_seconds: Union[int, str],
+ message_content_edit_limit_seconds: int | str,
edit_topic_policy: int,
) -> None:
self.login("iago")
diff --git a/zerver/tests/test_message_edit_notifications.py b/zerver/tests/test_message_edit_notifications.py
index f787c525992..006c6a74cb6 100644
--- a/zerver/tests/test_message_edit_notifications.py
+++ b/zerver/tests/test_message_edit_notifications.py
@@ -1,4 +1,4 @@
-from typing import Any, Mapping, Union
+from typing import Any, Mapping
from unittest import mock
from django.utils.timezone import now as timezone_now
@@ -121,7 +121,7 @@ class EditMessageSideEffectsTest(ZulipTestCase):
queue_messages = []
- def fake_publish(queue_name: str, event: Union[Mapping[str, Any], str], *args: Any) -> None:
+ def fake_publish(queue_name: str, event: Mapping[str, Any] | str, *args: Any) -> None:
queue_messages.append(
dict(
queue_name=queue_name,
diff --git a/zerver/tests/test_message_fetch.py b/zerver/tests/test_message_fetch.py
index 4afb36e9aee..de2a251d322 100644
--- a/zerver/tests/test_message_fetch.py
+++ b/zerver/tests/test_message_fetch.py
@@ -1,6 +1,6 @@
from dataclasses import dataclass
from datetime import timedelta
-from typing import TYPE_CHECKING, Any, Optional, Sequence, Union
+from typing import TYPE_CHECKING, Any, Sequence
from unittest import mock
import orjson
@@ -91,7 +91,7 @@ def get_sqlalchemy_query_params(query: ClauseElement) -> dict[str, object]:
return comp.params
-def get_recipient_id_for_channel_name(realm: Realm, channel_name: str) -> Optional[int]:
+def get_recipient_id_for_channel_name(realm: Realm, channel_name: str) -> int | None:
channel = get_stream(channel_name, realm)
return channel.recipient.id if channel.recipient is not None else None
@@ -715,7 +715,7 @@ class NarrowBuilderTest(ZulipTestCase):
)
def _do_add_term_test(
- self, term: NarrowParameter, where_clause: str, params: Optional[dict[str, Any]] = None
+ self, term: NarrowParameter, where_clause: str, params: dict[str, Any] | None = None
) -> None:
query = self._build_query(term)
if params is not None:
@@ -1794,9 +1794,9 @@ class PostProcessTest(ZulipTestCase):
class GetOldMessagesTest(ZulipTestCase):
def get_and_check_messages(
- self, modified_params: dict[str, Union[str, int]], **kwargs: Any
+ self, modified_params: dict[str, str | int], **kwargs: Any
) -> dict[str, Any]:
- post_params: dict[str, Union[str, int]] = {"anchor": 1, "num_before": 1, "num_after": 1}
+ post_params: dict[str, str | int] = {"anchor": 1, "num_before": 1, "num_after": 1}
post_params.update(modified_params)
payload = self.client_get("/json/messages", dict(post_params), **kwargs)
self.assert_json_success(payload)
@@ -1854,11 +1854,11 @@ class GetOldMessagesTest(ZulipTestCase):
for message in result["messages"]:
assert message["id"] in message_ids
- def get_query_ids(self) -> dict[str, Union[int, str]]:
+ def get_query_ids(self) -> dict[str, int | str]:
hamlet_user = self.example_user("hamlet")
othello_user = self.example_user("othello")
- query_ids: dict[str, Union[int, str]] = {}
+ query_ids: dict[str, int | str] = {}
scotland_channel = get_stream("Scotland", hamlet_user.realm)
assert scotland_channel.recipient_id is not None
@@ -1926,7 +1926,7 @@ class GetOldMessagesTest(ZulipTestCase):
self.login("hamlet")
- get_messages_params: dict[str, Union[int, str]] = {"anchor": "newest", "num_before": 1}
+ get_messages_params: dict[str, int | str] = {"anchor": "newest", "num_before": 1}
messages = self.get_and_check_messages(get_messages_params)["messages"]
self.assert_length(messages, 1)
message_id = messages[0]["id"]
@@ -1993,7 +1993,7 @@ class GetOldMessagesTest(ZulipTestCase):
self.check_unauthenticated_response(result, www_authenticate='Basic realm="zulip"')
# Successful access to web-public channel messages.
- web_public_channel_get_params: dict[str, Union[int, str, bool]] = {
+ web_public_channel_get_params: dict[str, int | str | bool] = {
**get_params,
"narrow": orjson.dumps([dict(operator="channels", operand="web-public")]).decode(),
}
@@ -2007,14 +2007,14 @@ class GetOldMessagesTest(ZulipTestCase):
self.assert_json_error(result, "Invalid subdomain", status_code=404)
# Cannot access direct messages without login.
- direct_messages_get_params: dict[str, Union[int, str, bool]] = {
+ direct_messages_get_params: dict[str, int | str | bool] = {
**get_params,
"narrow": orjson.dumps([dict(operator="is", operand="dm")]).decode(),
}
result = self.client_get("/json/messages", dict(direct_messages_get_params))
self.check_unauthenticated_response(result)
# "is:private" is a legacy alias for "is:dm".
- private_message_get_params: dict[str, Union[int, str, bool]] = {
+ private_message_get_params: dict[str, int | str | bool] = {
**get_params,
"narrow": orjson.dumps([dict(operator="is", operand="private")]).decode(),
}
@@ -2022,7 +2022,7 @@ class GetOldMessagesTest(ZulipTestCase):
self.check_unauthenticated_response(result)
# narrow should pass conditions in `is_spectator_compatible`.
- non_spectator_compatible_narrow_get_params: dict[str, Union[int, str, bool]] = {
+ non_spectator_compatible_narrow_get_params: dict[str, int | str | bool] = {
**get_params,
# "is:dm" is not a is_spectator_compatible narrow.
"narrow": orjson.dumps(
@@ -2047,7 +2047,7 @@ class GetOldMessagesTest(ZulipTestCase):
self.assert_json_success(result)
# Cannot access even web-public channels without channels:web-public narrow.
- non_web_public_channel_get_params: dict[str, Union[int, str, bool]] = {
+ non_web_public_channel_get_params: dict[str, int | str | bool] = {
**get_params,
"narrow": orjson.dumps([dict(operator="channel", operand="Rome")]).decode(),
}
@@ -2055,7 +2055,7 @@ class GetOldMessagesTest(ZulipTestCase):
self.check_unauthenticated_response(result)
# Verify that same request would work with channels:web-public added.
- rome_web_public_get_params: dict[str, Union[int, str, bool]] = {
+ rome_web_public_get_params: dict[str, int | str | bool] = {
**get_params,
"narrow": orjson.dumps(
[
@@ -2069,7 +2069,7 @@ class GetOldMessagesTest(ZulipTestCase):
self.assert_json_success(result)
# Cannot access non-web-public channel even with channels:web-public narrow.
- scotland_web_public_get_params: dict[str, Union[int, str, bool]] = {
+ scotland_web_public_get_params: dict[str, int | str | bool] = {
**get_params,
"narrow": orjson.dumps(
[
@@ -2127,7 +2127,7 @@ class GetOldMessagesTest(ZulipTestCase):
def test_unauthenticated_narrow_to_web_public_channels(self) -> None:
self.setup_web_public_test()
- post_params: dict[str, Union[int, str, bool]] = {
+ post_params: dict[str, int | str | bool] = {
"anchor": 1,
"num_before": 1,
"num_after": 1,
@@ -3216,7 +3216,7 @@ class GetOldMessagesTest(ZulipTestCase):
'<p>今<span class="highlight">朝は</span>ごはんを食<span class="highlight">べました</span>。</p>',
)
- def search(operand: str, link: Optional[str], highlight: str) -> None:
+ def search(operand: str, link: str | None, highlight: str) -> None:
narrow = [dict(operator="search", operand=operand)]
link_search_result: dict[str, Any] = self.get_and_check_messages(
dict(
diff --git a/zerver/tests/test_message_flags.py b/zerver/tests/test_message_flags.py
index c71a2d10d01..70c52321ab9 100644
--- a/zerver/tests/test_message_flags.py
+++ b/zerver/tests/test_message_flags.py
@@ -1,4 +1,4 @@
-from typing import TYPE_CHECKING, Any, Optional
+from typing import TYPE_CHECKING, Any
from unittest import mock
import orjson
@@ -281,8 +281,8 @@ class UnreadCountTests(ZulipTestCase):
*,
user_id: int,
message_ids: list[int],
- flagattr: Optional[int] = None,
- flag_target: Optional[int] = None,
+ flagattr: int | None = None,
+ flag_target: int | None = None,
) -> None:
UserMessage.objects.create(
user_profile_id=user_id, message_id=message_ids[0], flags=DEFAULT_HISTORICAL_FLAGS
diff --git a/zerver/tests/test_message_move_stream.py b/zerver/tests/test_message_move_stream.py
index 421d1c31423..f092bfb83cd 100644
--- a/zerver/tests/test_message_move_stream.py
+++ b/zerver/tests/test_message_move_stream.py
@@ -1,5 +1,4 @@
from datetime import timedelta
-from typing import Optional, Union
import orjson
@@ -42,7 +41,7 @@ class MessageMoveStreamTest(ZulipTestCase):
old_stream: str,
new_stream: str,
topic_name: str,
- language: Optional[str] = None,
+ language: str | None = None,
) -> tuple[UserProfile, Stream, Stream, int, int]:
user_profile = self.example_user(user_email)
if language is not None:
@@ -136,10 +135,10 @@ class MessageMoveStreamTest(ZulipTestCase):
old_stream = denmark
def test_moving_all_topic_messages(
- new_topic_name: Optional[str] = None, new_stream: Optional[Stream] = None
+ new_topic_name: str | None = None, new_stream: Stream | None = None
) -> None:
self.login("hamlet")
- params_dict: dict[str, Union[str, int]] = {
+ params_dict: dict[str, str | int] = {
"propagate_mode": "change_all",
"send_notification_to_new_thread": "false",
}
@@ -913,7 +912,7 @@ class MessageMoveStreamTest(ZulipTestCase):
old_stream: Stream,
new_stream: Stream,
*,
- expect_error_message: Optional[str] = None,
+ expect_error_message: str | None = None,
) -> None:
self.login_user(user)
result = self.client_patch(
@@ -976,7 +975,7 @@ class MessageMoveStreamTest(ZulipTestCase):
acting_user=None,
)
- def check_move_message_to_stream(role: int, error_msg: Optional[str] = None) -> None:
+ def check_move_message_to_stream(role: int, error_msg: str | None = None) -> None:
do_change_user_role(user_profile, role, acting_user=None)
result = self.client_patch(
@@ -1193,8 +1192,8 @@ class MessageMoveStreamTest(ZulipTestCase):
*,
has_user_message: bool,
has_access: bool,
- stream: Optional[Stream] = None,
- is_subscribed: Optional[bool] = None,
+ stream: Stream | None = None,
+ is_subscribed: bool | None = None,
) -> None:
self.assertEqual(
UserMessage.objects.filter(
diff --git a/zerver/tests/test_message_notification_emails.py b/zerver/tests/test_message_notification_emails.py
index 59c49205f1f..f37c0a5a453 100644
--- a/zerver/tests/test_message_notification_emails.py
+++ b/zerver/tests/test_message_notification_emails.py
@@ -1,7 +1,7 @@
import random
import re
from email.headerregistry import Address
-from typing import Optional, Sequence, Union
+from typing import Sequence
from unittest import mock
from unittest.mock import patch
@@ -89,7 +89,7 @@ class TestMessageNotificationEmails(ZulipTestCase):
)
m.assert_not_called()
- def normalize_string(self, s: Union[str, StrPromise]) -> str:
+ def normalize_string(self, s: str | StrPromise) -> str:
s = s.strip()
return re.sub(r"\s+", " ", s)
@@ -105,7 +105,7 @@ class TestMessageNotificationEmails(ZulipTestCase):
show_message_content: bool = True,
verify_body_does_not_include: Sequence[str] = [],
trigger: str = "",
- mentioned_user_group_id: Optional[int] = None,
+ mentioned_user_group_id: int | None = None,
) -> None:
hamlet = self.example_user("hamlet")
tokens = self._get_tokens()
diff --git a/zerver/tests/test_message_send.py b/zerver/tests/test_message_send.py
index 0f2fc709a7a..ad60af2d665 100644
--- a/zerver/tests/test_message_send.py
+++ b/zerver/tests/test_message_send.py
@@ -1,6 +1,6 @@
from datetime import timedelta
from email.headerregistry import Address
-from typing import Any, Optional
+from typing import Any
from unittest import mock
import orjson
@@ -76,7 +76,7 @@ from zerver.views.message_send import InvalidMirrorInputError
class MessagePOSTTest(ZulipTestCase):
def _send_and_verify_message(
- self, user: UserProfile, stream_name: str, error_msg: Optional[str] = None
+ self, user: UserProfile, stream_name: str, error_msg: str | None = None
) -> None:
if error_msg is None:
msg_id = self.send_stream_message(user, stream_name)
diff --git a/zerver/tests/test_openapi.py b/zerver/tests/test_openapi.py
index bdae5069dc4..764e95fdfa6 100644
--- a/zerver/tests/test_openapi.py
+++ b/zerver/tests/test_openapi.py
@@ -2,7 +2,7 @@ import inspect
import os
import types
from collections import abc
-from typing import Any, Callable, Mapping, Optional, Sequence, Union, get_args, get_origin
+from typing import Any, Callable, Mapping, Sequence, Union, get_args, get_origin
from unittest.mock import MagicMock, patch
import yaml
@@ -47,9 +47,7 @@ VARMAP = {
}
-def schema_type(
- schema: dict[str, Any], defs: Mapping[str, Any] = {}
-) -> Union[type, tuple[type, object]]:
+def schema_type(schema: dict[str, Any], defs: Mapping[str, Any] = {}) -> type | tuple[type, object]:
if "oneOf" in schema:
# Hack: Just use the type of the first value
# Ideally, we'd turn this into a Union type.
@@ -279,7 +277,7 @@ class OpenAPIArgumentsTest(ZulipTestCase):
buggy_documentation_endpoints: set[str] = set()
def ensure_no_documentation_if_intentionally_undocumented(
- self, url_pattern: str, method: str, msg: Optional[str] = None
+ self, url_pattern: str, method: str, msg: str | None = None
) -> None:
try:
get_openapi_parameters(url_pattern, method)
@@ -312,8 +310,8 @@ so maybe we shouldn't mark it as intentionally undocumented in the URLs.
raise AssertionError(msg)
def get_type_by_priority(
- self, types: Sequence[Union[type, tuple[type, object]]]
- ) -> Union[type, tuple[type, object]]:
+ self, types: Sequence[type | tuple[type, object]]
+ ) -> type | tuple[type, object]:
priority = {list: 1, dict: 2, str: 3, int: 4, bool: 5}
tyiroirp = {1: list, 2: dict, 3: str, 4: int, 5: bool}
val = 6
@@ -325,7 +323,7 @@ so maybe we shouldn't mark it as intentionally undocumented in the URLs.
val = v
return tyiroirp.get(val, types[0])
- def get_standardized_argument_type(self, t: Any) -> Union[type, tuple[type, object]]:
+ def get_standardized_argument_type(self, t: Any) -> type | tuple[type, object]:
"""Given a type from the typing module such as List[str] or Union[str, int],
convert it into a corresponding Python type. Unions are mapped to a canonical
choice among the options.
@@ -351,9 +349,9 @@ so maybe we shouldn't mark it as intentionally undocumented in the URLs.
def render_openapi_type_exception(
self,
function: Callable[..., HttpResponse],
- openapi_params: set[tuple[str, Union[type, tuple[type, object]]]],
- function_params: set[tuple[str, Union[type, tuple[type, object]]]],
- diff: set[tuple[str, Union[type, tuple[type, object]]]],
+ openapi_params: set[tuple[str, type | tuple[type, object]]],
+ function_params: set[tuple[str, type | tuple[type, object]]],
+ diff: set[tuple[str, type | tuple[type, object]]],
) -> None: # nocoverage
"""Print a *VERY* clear and verbose error message for when the types
(between the OpenAPI documentation and the function declaration) don't match."""
@@ -483,8 +481,8 @@ do not match the types declared in the implementation of {function.__name__}.\n"
if use_endpoint_decorator:
return self.validate_json_schema(function, openapi_parameters)
- openapi_params: set[tuple[str, Union[type, tuple[type, object]]]] = set()
- json_params: dict[str, Union[type, tuple[type, object]]] = {}
+ openapi_params: set[tuple[str, type | tuple[type, object]]] = set()
+ json_params: dict[str, type | tuple[type, object]] = {}
for openapi_parameter in openapi_parameters:
name = openapi_parameter.name
if openapi_parameter.json_encoded:
@@ -502,7 +500,7 @@ do not match the types declared in the implementation of {function.__name__}.\n"
continue
openapi_params.add((name, schema_type(openapi_parameter.value_schema)))
- function_params: set[tuple[str, Union[type, tuple[type, object]]]] = set()
+ function_params: set[tuple[str, type | tuple[type, object]]] = set()
for pname, defval in inspect.signature(function).parameters.items():
defval = defval.default
diff --git a/zerver/tests/test_outgoing_webhook_system.py b/zerver/tests/test_outgoing_webhook_system.py
index 9d977fca50e..099e98c02ee 100644
--- a/zerver/tests/test_outgoing_webhook_system.py
+++ b/zerver/tests/test_outgoing_webhook_system.py
@@ -1,4 +1,4 @@
-from typing import Any, Optional
+from typing import Any
from unittest import mock
import orjson
@@ -81,7 +81,7 @@ class DoRestCallTests(ZulipTestCase):
mock_event = self.mock_event(bot_user)
service_handler = GenericOutgoingWebhookService("token", bot_user, "service")
- def _helper(content: Optional[str]) -> None:
+ def _helper(content: str | None) -> None:
expect_send_response = mock.patch("zerver.lib.outgoing_webhook.send_response_message")
with mock.patch.object(
service_handler, "session"
diff --git a/zerver/tests/test_push_notifications.py b/zerver/tests/test_push_notifications.py
index ccceb11be49..1d1b3437f65 100644
--- a/zerver/tests/test_push_notifications.py
+++ b/zerver/tests/test_push_notifications.py
@@ -4,7 +4,7 @@ import logging
import uuid
from contextlib import contextmanager
from datetime import datetime, timedelta, timezone
-from typing import Any, Iterator, Mapping, Optional, Union
+from typing import Any, Iterator, Mapping
from unittest import mock, skipUnless
import aioapns
@@ -2231,7 +2231,7 @@ class AnalyticsBouncerTest(BouncerTestCase):
def transform_realmauditlog_extra_data(
method: str,
endpoint: str,
- post_data: Union[bytes, Mapping[str, Union[str, int, None, bytes]]],
+ post_data: bytes | Mapping[str, str | int | None | bytes],
extra_headers: Mapping[str, str] = {},
) -> dict[str, Any]:
if endpoint == "server/analytics":
@@ -2507,7 +2507,7 @@ class AnalyticsBouncerTest(BouncerTestCase):
dummy_remote_server_customer_plan = mock.MagicMock()
dummy_remote_server_customer_plan.status = CustomerPlan.ACTIVE
- def get_current_plan_by_customer(customer: mock.MagicMock) -> Optional[mock.MagicMock]:
+ def get_current_plan_by_customer(customer: mock.MagicMock) -> mock.MagicMock | None:
assert customer in [dummy_remote_realm_customer, dummy_remote_server_customer]
if customer == dummy_remote_server_customer:
return dummy_remote_server_customer_plan
@@ -3793,7 +3793,7 @@ class TestAPNs(PushNotificationTest):
def send(
self,
- devices: Optional[list[Union[PushDeviceToken, RemotePushDeviceToken]]] = None,
+ devices: list[PushDeviceToken | RemotePushDeviceToken] | None = None,
payload_data: Mapping[str, Any] = {},
) -> None:
send_apple_push_notification(
@@ -4321,8 +4321,8 @@ class TestGetGCMPayload(PushNotificationTest):
def _test_get_message_payload_gcm_stream_message(
self,
truncate_content: bool = False,
- mentioned_user_group_id: Optional[int] = None,
- mentioned_user_group_name: Optional[str] = None,
+ mentioned_user_group_id: int | None = None,
+ mentioned_user_group_name: str | None = None,
) -> None:
stream = Stream.objects.filter(name="Verona").get()
message = self.get_message(Recipient.STREAM, stream.id, stream.realm_id)
diff --git a/zerver/tests/test_queue_worker.py b/zerver/tests/test_queue_worker.py
index e841c316a18..67e6151ab5a 100644
--- a/zerver/tests/test_queue_worker.py
+++ b/zerver/tests/test_queue_worker.py
@@ -5,7 +5,7 @@ import time
from collections import defaultdict
from contextlib import contextmanager, suppress
from datetime import datetime, timedelta, timezone
-from typing import Any, Callable, Iterator, Mapping, Optional
+from typing import Any, Callable, Iterator, Mapping
from unittest.mock import MagicMock, patch
import orjson
@@ -52,7 +52,7 @@ class FakeClient:
queue_name: str,
callback: Callable[[list[dict[str, Any]]], None],
batch_size: int = 1,
- timeout: Optional[int] = None,
+ timeout: int | None = None,
) -> None:
chunk: list[dict[str, Any]] = []
queue = self.queues[queue_name]
@@ -279,16 +279,16 @@ class WorkerTest(ZulipTestCase):
def check_row(
row: ScheduledMessageNotificationEmail,
scheduled_timestamp: datetime,
- mentioned_user_group_id: Optional[int],
+ mentioned_user_group_id: int | None,
) -> None:
self.assertEqual(row.trigger, NotificationTriggers.DIRECT_MESSAGE)
self.assertEqual(row.scheduled_timestamp, scheduled_timestamp)
self.assertEqual(row.mentioned_user_group_id, mentioned_user_group_id)
- def advance() -> Optional[float]:
+ def advance() -> float | None:
mmw.stopping = False
- def inner(check: Callable[[], bool], timeout: Optional[float]) -> bool:
+ def inner(check: Callable[[], bool], timeout: float | None) -> bool:
# The check should never pass, since we've just (with
# the lock) ascertained above the cv.wait that its
# conditions are not met.
@@ -660,7 +660,7 @@ class WorkerTest(ZulipTestCase):
fake_client.enqueue("email_senders", data)
def fake_publish(
- queue_name: str, event: dict[str, Any], processor: Optional[Callable[[Any], None]]
+ queue_name: str, event: dict[str, Any], processor: Callable[[Any], None] | None
) -> None:
fake_client.enqueue(queue_name, event)
diff --git a/zerver/tests/test_realm.py b/zerver/tests/test_realm.py
index 5a7fac5c8a1..85b51224a3b 100644
--- a/zerver/tests/test_realm.py
+++ b/zerver/tests/test_realm.py
@@ -4,7 +4,7 @@ import random
import re
import string
from datetime import datetime, timedelta
-from typing import Any, Union
+from typing import Any
from unittest import mock, skipUnless
import orjson
@@ -1529,7 +1529,7 @@ class RealmAPITest(ZulipTestCase):
super().setUp()
self.login("desdemona")
- def update_with_api(self, name: str, value: Union[int, str]) -> Realm:
+ def update_with_api(self, name: str, value: int | str) -> Realm:
if not isinstance(value, str):
value = orjson.dumps(value).decode()
result = self.client_patch("/json/realm", {name: value})
diff --git a/zerver/tests/test_realm_export.py b/zerver/tests/test_realm_export.py
index dfaef7e8264..4d4160ee38f 100644
--- a/zerver/tests/test_realm_export.py
+++ b/zerver/tests/test_realm_export.py
@@ -1,5 +1,4 @@
import os
-from typing import Optional
from unittest.mock import patch
import botocore.exceptions
@@ -118,10 +117,10 @@ class RealmExportTest(ZulipTestCase):
realm: Realm,
output_dir: str,
threads: int,
- exportable_user_ids: Optional[set[int]] = None,
+ exportable_user_ids: set[int] | None = None,
public_only: bool = False,
- consent_message_id: Optional[int] = None,
- export_as_active: Optional[bool] = None,
+ consent_message_id: int | None = None,
+ export_as_active: bool | None = None,
) -> str:
self.assertEqual(realm, admin.realm)
self.assertEqual(public_only, True)
diff --git a/zerver/tests/test_retention.py b/zerver/tests/test_retention.py
index 90be76f117a..0c5928767a7 100644
--- a/zerver/tests/test_retention.py
+++ b/zerver/tests/test_retention.py
@@ -1,5 +1,5 @@
from datetime import datetime, timedelta
-from typing import Any, Optional
+from typing import Any
from unittest import mock
import time_machine
@@ -122,7 +122,7 @@ class ArchiveMessagesTestingBase(RetentionTestingBase):
realm.save()
def _set_stream_message_retention_value(
- self, stream: Stream, retention_period: Optional[int]
+ self, stream: Stream, retention_period: int | None
) -> None:
stream.message_retention_days = retention_period
stream.save()
diff --git a/zerver/tests/test_scheduled_messages.py b/zerver/tests/test_scheduled_messages.py
index f7188641522..ab71ab171b3 100644
--- a/zerver/tests/test_scheduled_messages.py
+++ b/zerver/tests/test_scheduled_messages.py
@@ -2,7 +2,7 @@ import re
import time
from datetime import timedelta
from io import StringIO
-from typing import TYPE_CHECKING, Any, Union
+from typing import TYPE_CHECKING, Any
from unittest import mock
import orjson
@@ -33,7 +33,7 @@ class ScheduledMessageTest(ZulipTestCase):
def do_schedule_message(
self,
msg_type: str,
- to: Union[int, list[str], list[int]],
+ to: int | list[str] | list[int],
msg: str,
scheduled_delivery_timestamp: int,
) -> "TestHttpResponse":
diff --git a/zerver/tests/test_service_bot_system.py b/zerver/tests/test_service_bot_system.py
index cbf93fd8a10..0c783d63859 100644
--- a/zerver/tests/test_service_bot_system.py
+++ b/zerver/tests/test_service_bot_system.py
@@ -1,5 +1,5 @@
from functools import wraps
-from typing import Any, Callable, Optional
+from typing import Any, Callable
from unittest import mock
import orjson
@@ -492,7 +492,7 @@ class TestServiceBotEventTriggers(ZulipTestCase):
def check_values_passed(
queue_name: Any,
trigger_event: dict[str, Any],
- processor: Optional[Callable[[Any], None]] = None,
+ processor: Callable[[Any], None] | None = None,
) -> None:
assert self.bot_profile.bot_type
self.assertEqual(queue_name, BOT_TYPE_TO_QUEUE_NAME[self.bot_profile.bot_type])
@@ -535,7 +535,7 @@ class TestServiceBotEventTriggers(ZulipTestCase):
def check_values_passed(
queue_name: Any,
trigger_event: dict[str, Any],
- processor: Optional[Callable[[Any], None]] = None,
+ processor: Callable[[Any], None] | None = None,
) -> None:
assert self.bot_profile.bot_type
self.assertEqual(queue_name, BOT_TYPE_TO_QUEUE_NAME[self.bot_profile.bot_type])
@@ -579,7 +579,7 @@ class TestServiceBotEventTriggers(ZulipTestCase):
def check_values_passed(
queue_name: Any,
trigger_event: dict[str, Any],
- processor: Optional[Callable[[Any], None]] = None,
+ processor: Callable[[Any], None] | None = None,
) -> None:
assert self.bot_profile.bot_type
self.assertEqual(queue_name, BOT_TYPE_TO_QUEUE_NAME[self.bot_profile.bot_type])
diff --git a/zerver/tests/test_signup.py b/zerver/tests/test_signup.py
index 1deabbb0723..71f9d5ba5a1 100644
--- a/zerver/tests/test_signup.py
+++ b/zerver/tests/test_signup.py
@@ -1,7 +1,7 @@
import re
import time
from datetime import timedelta
-from typing import TYPE_CHECKING, Any, Optional, Sequence, Union
+from typing import TYPE_CHECKING, Any, Sequence, Union
from unittest.mock import MagicMock, patch
from urllib.parse import quote, quote_plus, urlencode, urlsplit
@@ -926,7 +926,7 @@ class LoginTest(ZulipTestCase):
def test_login_bad_password(self) -> None:
user = self.example_user("hamlet")
- password: Optional[str] = "wrongpassword"
+ password: str | None = "wrongpassword"
result = self.login_with_return(user.delivery_email, password=password)
self.assert_in_success_response([user.delivery_email], result)
self.assert_logged_in_user_id(None)
@@ -2228,10 +2228,10 @@ class UserSignUpTest(ZulipTestCase):
self,
*,
email: str = "[email protected]",
- password: Optional[str] = "newpassword",
+ password: str | None = "newpassword",
full_name: str = "New user's name",
- realm: Optional[Realm] = None,
- subdomain: Optional[str] = None,
+ realm: Realm | None = None,
+ subdomain: str | None = None,
) -> Union[UserProfile, "TestHttpResponse"]:
"""Common test function for signup tests. It is a goal to use this
common function for all signup tests to avoid code duplication; doing
diff --git a/zerver/tests/test_subs.py b/zerver/tests/test_subs.py
index 45f5f3970f9..56c2acf0902 100644
--- a/zerver/tests/test_subs.py
+++ b/zerver/tests/test_subs.py
@@ -2,7 +2,7 @@ import hashlib
import random
from datetime import timedelta
from io import StringIO
-from typing import TYPE_CHECKING, Any, Optional, Sequence, Union
+from typing import TYPE_CHECKING, Any, Sequence
from unittest import mock
import orjson
@@ -2568,7 +2568,7 @@ class StreamAdminTest(ZulipTestCase):
self,
target_users: list[UserProfile],
query_count: int,
- cache_count: Optional[int] = None,
+ cache_count: int | None = None,
is_realm_admin: bool = False,
is_subbed: bool = True,
invite_only: bool = False,
@@ -4688,7 +4688,7 @@ class SubscriptionAPITest(ZulipTestCase):
def assert_adding_subscriptions_for_principal(
self,
- invitee_data: Union[str, int],
+ invitee_data: str | int,
invitee_realm: Realm,
streams: list[str],
policy_name: str,
@@ -6018,7 +6018,7 @@ class GetSubscribersTest(ZulipTestCase):
self.assertEqual(sorted(result["subscribers"]), sorted(true_subscribers))
def make_subscriber_request(
- self, stream_id: int, user: Optional[UserProfile] = None
+ self, stream_id: int, user: UserProfile | None = None
) -> "TestHttpResponse":
if user is None:
user = self.user_profile
diff --git a/zerver/tests/test_tornado.py b/zerver/tests/test_tornado.py
index b5a2f31a571..9cb253866f4 100644
--- a/zerver/tests/test_tornado.py
+++ b/zerver/tests/test_tornado.py
@@ -1,7 +1,7 @@
import asyncio
import socket
from functools import wraps
-from typing import Any, Awaitable, Callable, Optional, TypeVar
+from typing import Any, Awaitable, Callable, TypeVar
from unittest import TestResult, mock
from urllib.parse import urlencode
@@ -51,7 +51,7 @@ class TornadoWebTestCase(ZulipTestCase):
self.http_client = AsyncHTTPClient()
signals.request_started.disconnect(close_old_connections)
signals.request_finished.disconnect(close_old_connections)
- self.session_cookie: Optional[dict[str, str]] = None
+ self.session_cookie: dict[str, str] | None = None
@async_to_sync_decorator
@override
@@ -61,7 +61,7 @@ class TornadoWebTestCase(ZulipTestCase):
super().tearDown()
@override
- def run(self, result: Optional[TestResult] = None) -> Optional[TestResult]:
+ def run(self, result: TestResult | None = None) -> TestResult | None:
return async_to_sync(
sync_to_async(super().run, thread_sensitive=False), force_new_loop=True
)(result)
diff --git a/zerver/tests/test_typed_endpoint.py b/zerver/tests/test_typed_endpoint.py
index def6661f44f..7a7b9851317 100644
--- a/zerver/tests/test_typed_endpoint.py
+++ b/zerver/tests/test_typed_endpoint.py
@@ -1,4 +1,4 @@
-from typing import Any, Callable, Literal, Optional, TypeVar, Union, cast
+from typing import Any, Callable, Literal, TypeVar, cast
import orjson
from django.core.exceptions import ValidationError as DjangoValidationError
@@ -42,7 +42,7 @@ class TestEndpoint(ZulipTestCase):
"""This test is only needed because we don't
have coverage of is_optional in Python 3.11.
"""
- self.assertTrue(is_optional(cast(type[Optional[str]], Optional[str])))
+ self.assertTrue(is_optional(cast(type[str | None], str | None)))
self.assertFalse(is_optional(str))
def test_coerce(self) -> None:
@@ -79,10 +79,10 @@ class TestEndpoint(ZulipTestCase):
json_int: Json[int],
json_str: Json[str],
json_data: Json[Foo],
- json_optional: Optional[Json[Union[int, None]]] = None,
+ json_optional: Json[int | None] | None = None,
json_default: Json[Foo] = Foo(10, 10),
non_json: str = "ok",
- non_json_optional: Optional[str] = None,
+ non_json_optional: str | None = None,
) -> HttpResponse:
return MutableJsonResponse(
data={
@@ -396,7 +396,7 @@ class TestEndpoint(ZulipTestCase):
request: HttpRequest,
*,
bar: Annotated[
- Optional[str],
+ str | None,
StringConstraints(strip_whitespace=True, max_length=3),
ApiParamConfig("test"),
] = None,
@@ -410,7 +410,7 @@ class TestEndpoint(ZulipTestCase):
def nesting_with_config(
request: HttpRequest,
*,
- invalid_param: Optional[Annotated[str, ApiParamConfig("test")]] = None,
+ invalid_param: Annotated[str, ApiParamConfig("test")] | None = None,
) -> None:
raise AssertionError
@@ -425,7 +425,7 @@ class TestEndpoint(ZulipTestCase):
def nesting_without_config(
request: HttpRequest,
*,
- bar: Optional[Annotated[str, StringConstraints(max_length=3)]] = None,
+ bar: Annotated[str, StringConstraints(max_length=3)] | None = None,
) -> None:
raise AssertionError
@@ -540,11 +540,11 @@ class TestEndpoint(ZulipTestCase):
# all. The only possible way for val to be None is through the default
# value (if it has one).
@typed_endpoint
- def foo(request: HttpRequest, *, val: Optional[Json[int]]) -> None: ...
+ def foo(request: HttpRequest, *, val: Json[int] | None) -> None: ...
# Json[Optional[int]] however, allows client specified None value.
@typed_endpoint
- def bar(request: HttpRequest, *, val: Json[Optional[int]]) -> None: ...
+ def bar(request: HttpRequest, *, val: Json[int | None]) -> None: ...
with self.assertRaisesMessage(ApiParamValidationError, "val is not an integer"):
call_endpoint(foo, HostRequestMock({"val": orjson.dumps(None).decode()}))
diff --git a/zerver/tests/test_user_groups.py b/zerver/tests/test_user_groups.py
index 339d2e0f7cd..6d809477b2b 100644
--- a/zerver/tests/test_user_groups.py
+++ b/zerver/tests/test_user_groups.py
@@ -1,5 +1,5 @@
from datetime import timedelta
-from typing import Iterable, Optional
+from typing import Iterable
from unittest import mock
import orjson
@@ -1310,7 +1310,7 @@ class UserGroupAPITestCase(UserGroupTestCase):
hamlet = self.example_user("hamlet")
realm = hamlet.realm
- def check_create_user_group(acting_user: str, error_msg: Optional[str] = None) -> None:
+ def check_create_user_group(acting_user: str, error_msg: str | None = None) -> None:
self.login(acting_user)
params = {
"name": "support",
@@ -1325,7 +1325,7 @@ class UserGroupAPITestCase(UserGroupTestCase):
else:
self.assert_json_error(result, error_msg)
- def check_delete_user_group(acting_user: str, error_msg: Optional[str] = None) -> None:
+ def check_delete_user_group(acting_user: str, error_msg: str | None = None) -> None:
self.login(acting_user)
user_group = NamedUserGroup.objects.get(name="support")
with transaction.atomic():
@@ -1423,7 +1423,7 @@ class UserGroupAPITestCase(UserGroupTestCase):
new_name: str,
new_description: str,
acting_user: str,
- error_msg: Optional[str] = None,
+ error_msg: str | None = None,
) -> None:
self.login(acting_user)
params = {
@@ -1517,9 +1517,7 @@ class UserGroupAPITestCase(UserGroupTestCase):
othello = self.example_user("othello")
cordelia = self.example_user("cordelia")
- def check_adding_members_to_group(
- acting_user: str, error_msg: Optional[str] = None
- ) -> None:
+ def check_adding_members_to_group(acting_user: str, error_msg: str | None = None) -> None:
self.login(acting_user)
params = {"add": orjson.dumps([aaron.id]).decode()}
self.assert_user_membership(user_group, [othello])
@@ -1531,7 +1529,7 @@ class UserGroupAPITestCase(UserGroupTestCase):
self.assert_json_error(result, error_msg)
def check_removing_members_from_group(
- acting_user: str, error_msg: Optional[str] = None
+ acting_user: str, error_msg: str | None = None
) -> None:
self.login(acting_user)
params = {"delete": orjson.dumps([aaron.id]).decode()}
diff --git a/zerver/tests/test_user_status.py b/zerver/tests/test_user_status.py
index 5a5df9ab6e1..fb62181b4a6 100644
--- a/zerver/tests/test_user_status.py
+++ b/zerver/tests/test_user_status.py
@@ -1,4 +1,4 @@
-from typing import Any, Optional
+from typing import Any
import orjson
@@ -13,7 +13,7 @@ from zerver.models import UserProfile, UserStatus
from zerver.models.clients import get_client
-def user_status_info(user: UserProfile, acting_user: Optional[UserProfile] = None) -> UserInfoDict:
+def user_status_info(user: UserProfile, acting_user: UserProfile | None = None) -> UserInfoDict:
if acting_user is None:
acting_user = user
user_dict = get_all_users_status_dict(user.realm, acting_user)
diff --git a/zerver/tests/test_users.py b/zerver/tests/test_users.py
index 8cda6ebf934..ca3fc2e3394 100644
--- a/zerver/tests/test_users.py
+++ b/zerver/tests/test_users.py
@@ -1,6 +1,6 @@
from datetime import timedelta
from email.headerregistry import Address
-from typing import Any, Iterable, Optional, TypeVar, Union
+from typing import Any, Iterable, TypeVar
from unittest import mock
import orjson
@@ -797,7 +797,7 @@ class PermissionTest(ZulipTestCase):
empty_profile_data = []
for field_name in fields:
field = CustomProfileField.objects.get(name=field_name, realm=realm)
- value: Union[str, None, list[Any]] = ""
+ value: str | None | list[Any] = ""
if field.field_type == CustomProfileField.USER:
value = []
empty_profile_data.append(
@@ -2371,7 +2371,7 @@ class BulkUsersTest(ZulipTestCase):
hamlet = self.example_user("hamlet")
- def get_hamlet_avatar(client_gravatar: bool) -> Optional[str]:
+ def get_hamlet_avatar(client_gravatar: bool) -> str | None:
data = dict(client_gravatar=orjson.dumps(client_gravatar).decode())
result = self.client_get("/json/users", data)
rows = self.assert_json_success(result)["members"]
diff --git a/zerver/tornado/descriptors.py b/zerver/tornado/descriptors.py
index 532b62d08db..03154b276f9 100644
--- a/zerver/tornado/descriptors.py
+++ b/zerver/tornado/descriptors.py
@@ -20,10 +20,10 @@ def clear_descriptor_by_handler_id(handler_id: int) -> None:
del descriptors_by_handler_id[handler_id]
-current_port: Optional[int] = None
+current_port: int | None = None
-def is_current_port(port: int) -> Optional[int]:
+def is_current_port(port: int) -> int | None:
return settings.TEST_SUITE or current_port == port
diff --git a/zerver/tornado/django_api.py b/zerver/tornado/django_api.py
index c5bc19e7761..fb3dde96f36 100644
--- a/zerver/tornado/django_api.py
+++ b/zerver/tornado/django_api.py
@@ -1,6 +1,6 @@
from collections import defaultdict
from functools import lru_cache
-from typing import Any, Iterable, Mapping, Optional, Sequence, Union
+from typing import Any, Iterable, Mapping, Sequence
from urllib.parse import urlsplit
import orjson
@@ -37,10 +37,10 @@ class TornadoAdapter(HTTPAdapter):
self,
request: PreparedRequest,
stream: bool = False,
- timeout: Union[None, float, tuple[float, float], tuple[float, None]] = 0.5,
- verify: Union[bool, str] = True,
- cert: Union[None, bytes, str, tuple[Union[bytes, str], Union[bytes, str]]] = None,
- proxies: Optional[Mapping[str, str]] = None,
+ timeout: None | float | tuple[float, float] | tuple[float, None] = 0.5,
+ verify: bool | str = True,
+ cert: None | bytes | str | tuple[bytes | str, bytes | str] = None,
+ proxies: Mapping[str, str] | None = None,
) -> Response:
# Don't talk to Tornado through proxies, which only allow
# requests to external hosts.
@@ -80,7 +80,7 @@ def request_event_queue(
client_gravatar: bool,
slim_presence: bool,
queue_lifespan_secs: int,
- event_types: Optional[Sequence[str]] = None,
+ event_types: Sequence[str] | None = None,
all_public_streams: bool = False,
narrow: Iterable[Sequence[str]] = [],
bulk_message_deletion: bool = False,
@@ -89,7 +89,7 @@ def request_event_queue(
pronouns_field_type_supported: bool = True,
linkifier_url_template: bool = False,
user_list_incomplete: bool = False,
-) -> Optional[str]:
+) -> str | None:
if not settings.USING_TORNADO:
return None
@@ -176,7 +176,7 @@ def send_notification_http(port: int, data: Mapping[str, Any]) -> None:
#
# See https://zulip.readthedocs.io/en/latest/subsystems/events-system.html
def send_event(
- realm: Realm, event: Mapping[str, Any], users: Union[Iterable[int], Iterable[Mapping[str, Any]]]
+ realm: Realm, event: Mapping[str, Any], users: Iterable[int] | Iterable[Mapping[str, Any]]
) -> None:
"""`users` is a list of user IDs, or in some special cases like message
send/update or embeds, dictionaries containing extra data."""
@@ -198,6 +198,6 @@ def send_event(
def send_event_on_commit(
- realm: Realm, event: Mapping[str, Any], users: Union[Iterable[int], Iterable[Mapping[str, Any]]]
+ realm: Realm, event: Mapping[str, Any], users: Iterable[int] | Iterable[Mapping[str, Any]]
) -> None:
transaction.on_commit(lambda: send_event(realm, event, users))
diff --git a/zerver/tornado/event_queue.py b/zerver/tornado/event_queue.py
index 7b46d4595d3..637144e2346 100644
--- a/zerver/tornado/event_queue.py
+++ b/zerver/tornado/event_queue.py
@@ -19,10 +19,8 @@ from typing import (
Literal,
Mapping,
MutableMapping,
- Optional,
Sequence,
TypedDict,
- Union,
cast,
)
@@ -76,7 +74,7 @@ class ClientDescriptor:
user_profile_id: int,
realm_id: int,
event_queue: "EventQueue",
- event_types: Optional[Sequence[str]],
+ event_types: Sequence[str] | None,
client_type_name: str,
apply_markdown: bool = True,
client_gravatar: bool = True,
@@ -101,8 +99,8 @@ class ClientDescriptor:
# Additionally, the to_dict and from_dict methods must be updated
self.user_profile_id = user_profile_id
self.realm_id = realm_id
- self.current_handler_id: Optional[int] = None
- self.current_client_name: Optional[str] = None
+ self.current_handler_id: int | None = None
+ self.current_client_name: str | None = None
self.event_queue = event_queue
self.event_types = event_types
self.last_connection_time = time.time()
@@ -317,7 +315,7 @@ class EventQueue:
self.queue: deque[dict[str, Any]] = deque()
self.next_event_id: int = 0
# will only be None for migration from old versions
- self.newest_pruned_id: Optional[int] = -1
+ self.newest_pruned_id: int | None = -1
self.id: str = id
self.virtual_events: dict[str, dict[str, Any]] = {}
@@ -663,7 +661,7 @@ def mark_clients_to_reload(queue_ids: Iterable[str]) -> None:
web_reload_clients[qid] = True
-def send_web_reload_client_events(immediate: bool = False, count: Optional[int] = None) -> int:
+def send_web_reload_client_events(immediate: bool = False, count: int | None = None) -> int:
event: dict[str, Any] = dict(
type="web_reload_client",
immediate=immediate,
@@ -699,11 +697,11 @@ async def setup_event_queue(
def fetch_events(
- queue_id: Optional[str],
+ queue_id: str | None,
dont_block: bool,
- last_event_id: Optional[int],
+ last_event_id: int | None,
user_profile_id: int,
- new_queue_data: Optional[MutableMapping[str, Any]],
+ new_queue_data: MutableMapping[str, Any] | None,
client_type_name: str,
handler_id: int,
) -> dict[str, Any]:
@@ -933,7 +931,7 @@ def maybe_enqueue_notifications(
user_notifications_data: UserMessageNotificationsData,
acting_user_id: int,
message_id: int,
- mentioned_user_group_id: Optional[int],
+ mentioned_user_group_id: int | None,
idle: bool,
already_notified: dict[str, bool],
) -> dict[str, bool]:
@@ -998,7 +996,7 @@ def get_client_info_for_message_event(
send_to_clients: dict[str, ClientInfo] = {}
- sender_queue_id: Optional[str] = event_template.get("sender_queue_id", None)
+ sender_queue_id: str | None = event_template.get("sender_queue_id", None)
def is_sender_client(client: ClientDescriptor) -> bool:
return (sender_queue_id is not None) and client.event_queue.id == sender_queue_id
@@ -1129,7 +1127,7 @@ def process_message_event(
for user_data in users:
user_profile_id: int = user_data["id"]
flags: Collection[str] = user_data.get("flags", [])
- mentioned_user_group_id: Optional[int] = user_data.get("mentioned_user_group_id")
+ mentioned_user_group_id: int | None = user_data.get("mentioned_user_group_id")
# If the recipient was offline and the message was a (1:1 or group) direct message
# to them or they were @-notified potentially notify more immediately
@@ -1188,7 +1186,7 @@ def process_message_event(
client = client_data["client"]
flags = client_data["flags"]
is_sender: bool = client_data.get("is_sender", False)
- extra_data: Optional[Mapping[str, bool]] = extra_user_data.get(client.user_profile_id, None)
+ extra_data: Mapping[str, bool] | None = extra_user_data.get(client.user_profile_id, None)
if not client.accepts_messages():
# The actual check is the accepts_event() check below;
@@ -1525,7 +1523,7 @@ def maybe_enqueue_notifications_for_message_update(
def reformat_legacy_send_message_event(
- event: Mapping[str, Any], users: Union[list[int], list[Mapping[str, Any]]]
+ event: Mapping[str, Any], users: list[int] | list[Mapping[str, Any]]
) -> tuple[MutableMapping[str, Any], Collection[MutableMapping[str, Any]]]:
# do_send_messages used to send events with users in dict format, with the
# dict containing the user_id and other data. We later trimmed down the user
@@ -1570,7 +1568,7 @@ def reformat_legacy_send_message_event(
def process_notification(notice: Mapping[str, Any]) -> None:
event: Mapping[str, Any] = notice["event"]
- users: Union[list[int], list[Mapping[str, Any]]] = notice["users"]
+ users: list[int] | list[Mapping[str, Any]] = notice["users"]
start_time = time.perf_counter()
if event["type"] == "message":
diff --git a/zerver/tornado/handlers.py b/zerver/tornado/handlers.py
index fb25c82b7fc..82f0db2f55f 100644
--- a/zerver/tornado/handlers.py
+++ b/zerver/tornado/handlers.py
@@ -104,7 +104,7 @@ class AsyncDjangoHandler(tornado.web.RequestHandler):
# on_finish and on_connection_close.
self.handler_id = allocate_handler_id(self)
- self._request: Optional[HttpRequest] = None
+ self._request: HttpRequest | None = None
@override
def on_finish(self) -> None:
diff --git a/zerver/tornado/sharding.py b/zerver/tornado/sharding.py
index 5792995e388..c3b006a81b6 100644
--- a/zerver/tornado/sharding.py
+++ b/zerver/tornado/sharding.py
@@ -1,14 +1,14 @@
import json
import os
import re
-from typing import Pattern, Union
+from typing import Pattern
from django.conf import settings
from zerver.models import Realm, UserProfile
-shard_map: dict[str, Union[int, list[int]]] = {}
-shard_regexes: list[tuple[Pattern[str], Union[int, list[int]]]] = []
+shard_map: dict[str, int | list[int]] = {}
+shard_regexes: list[tuple[Pattern[str], int | list[int]]] = []
if os.path.exists("/etc/zulip/sharding.json"):
with open("/etc/zulip/sharding.json") as f:
data = json.loads(f.read())
diff --git a/zerver/tornado/views.py b/zerver/tornado/views.py
index 3276e05115b..2deff01eda8 100644
--- a/zerver/tornado/views.py
+++ b/zerver/tornado/views.py
@@ -1,5 +1,5 @@
import time
-from typing import Any, Callable, Mapping, Optional, Sequence, TypeVar
+from typing import Any, Callable, Mapping, Sequence, TypeVar
from asgiref.sync import async_to_sync
from django.conf import settings
@@ -61,7 +61,7 @@ def notify(
def web_reload_clients(
request: HttpRequest,
*,
- client_count: Optional[Json[int]] = None,
+ client_count: Json[int] | None = None,
immediate: Json[bool] = False,
) -> HttpResponse:
sent_events = in_tornado_thread(send_web_reload_client_events)(
@@ -142,11 +142,11 @@ def get_events_backend(
user_profile: UserProfile,
# user_client is intended only for internal Django=>Tornado requests
# and thus shouldn't be documented for external use.
- user_client: Optional[Client] = REQ(
+ user_client: Client | None = REQ(
converter=lambda var_name, s: get_client(s), default=None, intentionally_undocumented=True
),
- last_event_id: Optional[int] = REQ(json_validator=check_int, default=None),
- queue_id: Optional[str] = REQ(default=None),
+ last_event_id: int | None = REQ(json_validator=check_int, default=None),
+ queue_id: str | None = REQ(default=None),
# apply_markdown, client_gravatar, all_public_streams, and various
# other parameters are only used when registering a new queue via this
# endpoint. This is a feature used primarily by get_events_internal
@@ -163,7 +163,7 @@ def get_events_backend(
all_public_streams: bool = REQ(
default=False, json_validator=check_bool, intentionally_undocumented=True
),
- event_types: Optional[Sequence[str]] = REQ(
+ event_types: Sequence[str] | None = REQ(
default=None, json_validator=check_list(check_string), intentionally_undocumented=True
),
dont_block: bool = REQ(default=False, json_validator=check_bool),
diff --git a/zerver/transaction_tests/test_user_groups.py b/zerver/transaction_tests/test_user_groups.py
index df70d1ed3c5..85920db4cb4 100644
--- a/zerver/transaction_tests/test_user_groups.py
+++ b/zerver/transaction_tests/test_user_groups.py
@@ -1,5 +1,5 @@
import threading
-from typing import Any, Optional
+from typing import Any
from unittest import mock
import orjson
@@ -16,14 +16,14 @@ from zerver.models import NamedUserGroup, Realm, UserGroup, UserProfile
from zerver.models.realms import get_realm
from zerver.views.user_groups import update_subgroups_of_user_group
-BARRIER: Optional[threading.Barrier] = None
+BARRIER: threading.Barrier | None = None
def dev_update_subgroups(
request: HttpRequest,
user_profile: UserProfile,
user_group_id: int,
-) -> Optional[str]:
+) -> str | None:
# The test is expected to set up the barrier before accessing this endpoint.
assert BARRIER is not None
try:
@@ -105,7 +105,7 @@ class UserGroupRaceConditionTestCase(ZulipTransactionTestCase):
supergroup_id: int,
) -> None:
threading.Thread.__init__(self)
- self.response: Optional[str] = None
+ self.response: str | None = None
self.subgroup_ids = subgroup_ids
self.supergroup_id = supergroup_id
diff --git a/zerver/views/auth.py b/zerver/views/auth.py
index e2e0da27cc8..ad7bd1348a8 100644
--- a/zerver/views/auth.py
+++ b/zerver/views/auth.py
@@ -1,7 +1,7 @@
import logging
import secrets
from functools import wraps
-from typing import TYPE_CHECKING, Any, Callable, Mapping, Optional, cast
+from typing import TYPE_CHECKING, Any, Callable, Mapping, cast
from urllib.parse import urlencode, urljoin
import jwt
@@ -102,7 +102,7 @@ if TYPE_CHECKING:
from django.http.request import _ImmutableQueryDict
ParamT = ParamSpec("ParamT")
-ExtraContext: TypeAlias = Optional[dict[str, Any]]
+ExtraContext: TypeAlias = dict[str, Any] | None
EXPIRABLE_SESSION_VAR_DEFAULT_EXPIRY_SECS = 3600
@@ -120,11 +120,11 @@ def get_safe_redirect_to(url: str, redirect_host: str) -> str:
def create_preregistration_user(
email: str,
- realm: Optional[Realm],
+ realm: Realm | None,
password_required: bool = True,
- full_name: Optional[str] = None,
+ full_name: str | None = None,
full_name_validated: bool = False,
- multiuse_invite: Optional[MultiuseInvite] = None,
+ multiuse_invite: MultiuseInvite | None = None,
) -> PreregistrationUser:
return PreregistrationUser.objects.create(
email=email,
@@ -156,12 +156,12 @@ def maybe_send_to_registration(
request: HttpRequest,
email: str,
full_name: str = "",
- mobile_flow_otp: Optional[str] = None,
- desktop_flow_otp: Optional[str] = None,
+ mobile_flow_otp: str | None = None,
+ desktop_flow_otp: str | None = None,
is_signup: bool = False,
multiuse_object_key: str = "",
full_name_validated: bool = False,
- params_to_store_in_authenticated_session: Optional[dict[str, str]] = None,
+ params_to_store_in_authenticated_session: dict[str, str] | None = None,
) -> HttpResponse:
"""Given a successful authentication for an email address (i.e. we've
confirmed the user controls the email address) that does not
@@ -213,11 +213,11 @@ def maybe_send_to_registration(
try:
# TODO: This should use get_realm_from_request, but a bunch of tests
# rely on mocking get_subdomain here, so they'll need to be tweaked first.
- realm: Optional[Realm] = get_realm(get_subdomain(request))
+ realm: Realm | None = get_realm(get_subdomain(request))
except Realm.DoesNotExist:
realm = None
- multiuse_obj: Optional[MultiuseInvite] = None
+ multiuse_obj: MultiuseInvite | None = None
from_multiuse_invite = False
if multiuse_object_key:
from_multiuse_invite = True
@@ -409,7 +409,7 @@ def finish_desktop_flow(
request: HttpRequest,
user_profile: UserProfile,
otp: str,
- params_to_store_in_authenticated_session: Optional[dict[str, str]] = None,
+ params_to_store_in_authenticated_session: dict[str, str] | None = None,
) -> HttpResponse:
"""
The desktop otp flow returns to the app (through the clipboard)
@@ -492,13 +492,13 @@ def create_response_for_otp_flow(
@has_request_variables
def remote_user_sso(
request: HttpRequest,
- mobile_flow_otp: Optional[str] = REQ(default=None),
- desktop_flow_otp: Optional[str] = REQ(default=None),
+ mobile_flow_otp: str | None = REQ(default=None),
+ desktop_flow_otp: str | None = REQ(default=None),
next: str = REQ(default="/"),
) -> HttpResponse:
subdomain = get_subdomain(request)
try:
- realm: Optional[Realm] = get_realm(subdomain)
+ realm: Realm | None = get_realm(subdomain)
except Realm.DoesNotExist:
realm = None
@@ -599,10 +599,10 @@ def oauth_redirect_to_root(
sso_type: str,
is_signup: bool = False,
extra_url_params: Mapping[str, str] = {},
- next: Optional[str] = REQ(default=None),
+ next: str | None = REQ(default=None),
multiuse_object_key: str = REQ(default=""),
- mobile_flow_otp: Optional[str] = REQ(default=None),
- desktop_flow_otp: Optional[str] = REQ(default=None),
+ mobile_flow_otp: str | None = REQ(default=None),
+ desktop_flow_otp: str | None = REQ(default=None),
) -> HttpResponse:
main_site_url = settings.ROOT_DOMAIN_URI + url
if settings.SOCIAL_AUTH_SUBDOMAIN is not None and sso_type == "social":
@@ -668,7 +668,7 @@ def start_remote_user_sso(request: HttpRequest) -> HttpResponse:
def start_social_login(
request: HttpRequest,
backend: str,
- extra_arg: Optional[str] = None,
+ extra_arg: str | None = None,
) -> HttpResponse:
backend_url = reverse("social:begin", args=[backend])
extra_url_params: dict[str, str] = {}
@@ -704,7 +704,7 @@ def start_social_login(
def start_social_signup(
request: HttpRequest,
backend: str,
- extra_arg: Optional[str] = None,
+ extra_arg: str | None = None,
) -> HttpResponse:
backend_url = reverse("social:begin", args=[backend])
extra_url_params: dict[str, str] = {}
diff --git a/zerver/views/custom_profile_fields.py b/zerver/views/custom_profile_fields.py
index 145d9126f93..9d8295fe453 100644
--- a/zerver/views/custom_profile_fields.py
+++ b/zerver/views/custom_profile_fields.py
@@ -1,4 +1,4 @@
-from typing import Annotated, Optional
+from typing import Annotated
import orjson
from django.core.exceptions import ValidationError
@@ -109,10 +109,10 @@ def validate_custom_profile_field(
def validate_custom_profile_field_update(
field: CustomProfileField,
- display_in_profile_summary: Optional[bool] = None,
- field_data: Optional[ProfileFieldData] = None,
- name: Optional[str] = None,
- hint: Optional[str] = None,
+ display_in_profile_summary: bool | None = None,
+ field_data: ProfileFieldData | None = None,
+ name: str | None = None,
+ hint: str | None = None,
) -> None:
if name is None:
name = field.name
@@ -140,9 +140,9 @@ def validate_custom_profile_field_update(
def update_only_display_in_profile_summary(
existing_field: CustomProfileField,
- requested_field_data: Optional[ProfileFieldData] = None,
- requested_name: Optional[str] = None,
- requested_hint: Optional[str] = None,
+ requested_field_data: ProfileFieldData | None = None,
+ requested_name: str | None = None,
+ requested_hint: str | None = None,
) -> bool:
if (
(requested_name is not None and requested_name != existing_field.name)
@@ -157,7 +157,7 @@ def update_only_display_in_profile_summary(
def display_in_profile_summary_limit_reached(
- realm: Realm, profile_field_id: Optional[int] = None
+ realm: Realm, profile_field_id: int | None = None
) -> bool:
query = CustomProfileField.objects.filter(realm=realm, display_in_profile_summary=True)
if profile_field_id is not None:
@@ -173,7 +173,7 @@ def create_realm_custom_profile_field(
*,
name: Annotated[str, StringConstraints(strip_whitespace=True)] = "",
hint: str = "",
- field_data: Optional[Json[ProfileFieldData]] = None,
+ field_data: Json[ProfileFieldData] | None = None,
field_type: Json[int],
display_in_profile_summary: Json[bool] = False,
required: Json[bool] = False,
@@ -232,11 +232,11 @@ def update_realm_custom_profile_field(
user_profile: UserProfile,
*,
field_id: PathOnly[int],
- name: Optional[Annotated[str, StringConstraints(strip_whitespace=True)]] = None,
- hint: Optional[str] = None,
- field_data: Optional[Json[ProfileFieldData]] = None,
- required: Optional[Json[bool]] = None,
- display_in_profile_summary: Optional[Json[bool]] = None,
+ name: Annotated[str, StringConstraints(strip_whitespace=True)] | None = None,
+ hint: str | None = None,
+ field_data: Json[ProfileFieldData] | None = None,
+ required: Json[bool] | None = None,
+ display_in_profile_summary: Json[bool] | None = None,
) -> HttpResponse:
realm = user_profile.realm
try:
diff --git a/zerver/views/development/dev_login.py b/zerver/views/development/dev_login.py
index 92caec38f4e..2ebfd47e4e8 100644
--- a/zerver/views/development/dev_login.py
+++ b/zerver/views/development/dev_login.py
@@ -1,4 +1,4 @@
-from typing import Any, Optional
+from typing import Any
from django.conf import settings
from django.contrib.auth import authenticate
@@ -27,7 +27,7 @@ from zerver.views.errors import config_error
from zproject.backends import dev_auth_enabled
-def get_dev_users(realm: Optional[Realm] = None, extra_users_count: int = 10) -> list[UserProfile]:
+def get_dev_users(realm: Realm | None = None, extra_users_count: int = 10) -> list[UserProfile]:
# Development environments usually have only a few users, but
# it still makes sense to limit how many extra users we render to
# support performance testing with DevAuthBackend.
@@ -48,7 +48,7 @@ def get_dev_users(realm: Optional[Realm] = None, extra_users_count: int = 10) ->
return users
-def add_dev_login_context(realm: Optional[Realm], context: dict[str, Any]) -> None:
+def add_dev_login_context(realm: Realm | None, context: dict[str, Any]) -> None:
users = get_dev_users(realm)
context["current_realm"] = realm
context["all_realms"] = Realm.objects.all()
diff --git a/zerver/views/development/email_log.py b/zerver/views/development/email_log.py
index 28c80be8119..69199e732f3 100644
--- a/zerver/views/development/email_log.py
+++ b/zerver/views/development/email_log.py
@@ -1,6 +1,5 @@
import os
from contextlib import suppress
-from typing import Optional
from urllib.parse import urlencode
import orjson
@@ -27,7 +26,7 @@ ZULIP_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)), "../../")
@typed_endpoint
-def email_page(request: HttpRequest, *, forward_address: Optional[str] = None) -> HttpResponse:
+def email_page(request: HttpRequest, *, forward_address: str | None = None) -> HttpResponse:
if request.method == "POST":
assert forward_address is not None
set_forward_address(forward_address)
diff --git a/zerver/views/development/integrations.py b/zerver/views/development/integrations.py
index 3124183140f..aed1b279d7f 100644
--- a/zerver/views/development/integrations.py
+++ b/zerver/views/development/integrations.py
@@ -1,6 +1,6 @@
import os
from contextlib import suppress
-from typing import TYPE_CHECKING, Any, Optional
+from typing import TYPE_CHECKING, Any
import orjson
from django.http import HttpRequest, HttpResponse
@@ -27,7 +27,7 @@ def get_webhook_integrations() -> list[str]:
return [integration.name for integration in WEBHOOK_INTEGRATIONS]
-def get_valid_integration_name(name: str) -> Optional[str]:
+def get_valid_integration_name(name: str) -> str | None:
for integration_name in get_webhook_integrations():
if name == integration_name:
return integration_name
diff --git a/zerver/views/documentation.py b/zerver/views/documentation.py
index 02d4c0980ba..801142f935c 100644
--- a/zerver/views/documentation.py
+++ b/zerver/views/documentation.py
@@ -3,7 +3,7 @@ import random
import re
from collections import OrderedDict
from dataclasses import dataclass
-from typing import Any, Callable, Optional
+from typing import Any, Callable
from django.conf import settings
from django.http import HttpRequest, HttpResponse, HttpResponseNotFound
@@ -37,8 +37,8 @@ from zerver.openapi.openapi import get_endpoint_from_operationid, get_openapi_su
class DocumentationArticle:
article_path: str
article_http_status: int
- endpoint_path: Optional[str]
- endpoint_method: Optional[str]
+ endpoint_path: str | None
+ endpoint_method: str | None
def add_api_url_context(context: dict[str, Any], request: HttpRequest) -> None:
@@ -85,10 +85,10 @@ class MarkdownDirectoryView(ApiURLView):
def __init__(self, **kwargs: Any) -> None:
super().__init__(**kwargs)
- self._post_render_callbacks: list[Callable[[HttpResponse], Optional[HttpResponse]]] = []
+ self._post_render_callbacks: list[Callable[[HttpResponse], HttpResponse | None]] = []
def add_post_render_callback(
- self, callback: Callable[[HttpResponse], Optional[HttpResponse]]
+ self, callback: Callable[[HttpResponse], HttpResponse | None]
) -> None:
self._post_render_callbacks.append(callback)
diff --git a/zerver/views/errors.py b/zerver/views/errors.py
index 3a745ad29e5..f8a342f46a0 100644
--- a/zerver/views/errors.py
+++ b/zerver/views/errors.py
@@ -1,5 +1,3 @@
-from typing import Optional
-
from django.conf import settings
from django.http import HttpRequest, HttpResponse
from django.shortcuts import render
@@ -9,8 +7,8 @@ def config_error(
request: HttpRequest,
error_name: str,
*,
- go_back_to_url: Optional[str] = None,
- go_back_to_url_name: Optional[str] = None,
+ go_back_to_url: str | None = None,
+ go_back_to_url_name: str | None = None,
) -> HttpResponse:
assert "/" not in error_name
context = {
diff --git a/zerver/views/events_register.py b/zerver/views/events_register.py
index ad4eb5bba13..7fb12ee7b80 100644
--- a/zerver/views/events_register.py
+++ b/zerver/views/events_register.py
@@ -1,4 +1,4 @@
-from typing import Optional, Sequence, Union
+from typing import Sequence
from django.conf import settings
from django.contrib.auth.models import AnonymousUser
@@ -17,9 +17,7 @@ from zerver.lib.validator import check_bool, check_dict, check_int, check_list,
from zerver.models import Stream, UserProfile
-def _default_all_public_streams(
- user_profile: UserProfile, all_public_streams: Optional[bool]
-) -> bool:
+def _default_all_public_streams(user_profile: UserProfile, all_public_streams: bool | None) -> bool:
if all_public_streams is not None:
return all_public_streams
else:
@@ -29,7 +27,7 @@ def _default_all_public_streams(
def _default_narrow(
user_profile: UserProfile, narrow: Sequence[Sequence[str]]
) -> Sequence[Sequence[str]]:
- default_stream: Optional[Stream] = user_profile.default_events_register_stream
+ default_stream: Stream | None = user_profile.default_events_register_stream
if not narrow and default_stream is not None:
narrow = [["stream", default_stream.name]]
return narrow
@@ -41,15 +39,15 @@ NarrowT: TypeAlias = Sequence[Sequence[str]]
@has_request_variables
def events_register_backend(
request: HttpRequest,
- maybe_user_profile: Union[UserProfile, AnonymousUser],
+ maybe_user_profile: UserProfile | AnonymousUser,
apply_markdown: bool = REQ(default=False, json_validator=check_bool),
- client_gravatar_raw: Optional[bool] = REQ(
+ client_gravatar_raw: bool | None = REQ(
"client_gravatar", default=None, json_validator=check_bool
),
slim_presence: bool = REQ(default=False, json_validator=check_bool),
- all_public_streams: Optional[bool] = REQ(default=None, json_validator=check_bool),
+ all_public_streams: bool | None = REQ(default=None, json_validator=check_bool),
include_subscribers: bool = REQ(default=False, json_validator=check_bool),
- client_capabilities: Optional[dict[str, bool]] = REQ(
+ client_capabilities: dict[str, bool] | None = REQ(
json_validator=check_dict(
[
# This field was accidentally made required when it was added in v2.0.0-781;
@@ -70,10 +68,8 @@ def events_register_backend(
),
default=None,
),
- event_types: Optional[Sequence[str]] = REQ(
- json_validator=check_list(check_string), default=None
- ),
- fetch_event_types: Optional[Sequence[str]] = REQ(
+ event_types: Sequence[str] | None = REQ(json_validator=check_list(check_string), default=None),
+ fetch_event_types: Sequence[str] | None = REQ(
json_validator=check_list(check_string), default=None
),
narrow: NarrowT = REQ(
diff --git a/zerver/views/home.py b/zerver/views/home.py
index f258d920fd7..d0cc4b2e7cf 100644
--- a/zerver/views/home.py
+++ b/zerver/views/home.py
@@ -1,6 +1,5 @@
import logging
import secrets
-from typing import Optional
from django.conf import settings
from django.http import HttpRequest, HttpResponse
@@ -21,7 +20,7 @@ from zerver.lib.subdomains import get_subdomain
from zerver.models import Realm, RealmUserDefault, Stream, UserProfile
-def need_accept_tos(user_profile: Optional[UserProfile]) -> bool:
+def need_accept_tos(user_profile: UserProfile | None) -> bool:
if user_profile is None:
return False
@@ -101,8 +100,8 @@ def accounts_accept_terms(request: HttpRequest) -> HttpResponse:
def detect_narrowed_window(
- request: HttpRequest, user_profile: Optional[UserProfile]
-) -> tuple[list[NarrowTerm], Optional[Stream], Optional[str]]:
+ request: HttpRequest, user_profile: UserProfile | None
+) -> tuple[list[NarrowTerm], Stream | None, str | None]:
"""This function implements Zulip's support for a mini Zulip window
that just handles messages from a single narrow"""
if user_profile is None:
@@ -126,7 +125,7 @@ def detect_narrowed_window(
return narrow, narrow_stream, narrow_topic_name
-def update_last_reminder(user_profile: Optional[UserProfile]) -> None:
+def update_last_reminder(user_profile: UserProfile | None) -> None:
"""Reset our don't-spam-users-with-email counter since the
user has since logged in
"""
diff --git a/zerver/views/invite.py b/zerver/views/invite.py
index 7dfe8fce768..2efcd06ce4e 100644
--- a/zerver/views/invite.py
+++ b/zerver/views/invite.py
@@ -1,5 +1,5 @@
import re
-from typing import Optional, Sequence
+from typing import Sequence
from django.conf import settings
from django.http import HttpRequest, HttpResponse
@@ -27,7 +27,7 @@ from zerver.models import MultiuseInvite, PreregistrationUser, Stream, UserProfi
# Because mypy fails to correctly infer the type of the validator, we want this constant
# to be Optional[int] to avoid a mypy error when using it as the default value.
# https://github.com/python/mypy/issues/13234
-INVITATION_LINK_VALIDITY_MINUTES: Optional[int] = 24 * 60 * settings.INVITATION_LINK_VALIDITY_DAYS
+INVITATION_LINK_VALIDITY_MINUTES: int | None = 24 * 60 * settings.INVITATION_LINK_VALIDITY_DAYS
def check_role_based_permissions(
@@ -49,7 +49,7 @@ def invite_users_backend(
request: HttpRequest,
user_profile: UserProfile,
invitee_emails_raw: str = REQ("invitee_emails"),
- invite_expires_in_minutes: Optional[int] = REQ(
+ invite_expires_in_minutes: int | None = REQ(
json_validator=check_none_or(check_int), default=INVITATION_LINK_VALIDITY_MINUTES
),
invite_as: int = REQ(
@@ -209,7 +209,7 @@ def resend_user_invite_email(
def generate_multiuse_invite_backend(
request: HttpRequest,
user_profile: UserProfile,
- invite_expires_in_minutes: Optional[int] = REQ(
+ invite_expires_in_minutes: int | None = REQ(
json_validator=check_none_or(check_int), default=INVITATION_LINK_VALIDITY_MINUTES
),
invite_as: int = REQ(
diff --git a/zerver/views/message_edit.py b/zerver/views/message_edit.py
index a243e23b6cb..e300d04d56c 100644
--- a/zerver/views/message_edit.py
+++ b/zerver/views/message_edit.py
@@ -1,5 +1,5 @@
from datetime import timedelta
-from typing import Literal, Optional, Union
+from typing import Literal
import orjson
from django.contrib.auth.models import AnonymousUser
@@ -121,12 +121,12 @@ def update_message_backend(
user_profile: UserProfile,
*,
message_id: PathOnly[NonNegativeInt],
- stream_id: Optional[Json[NonNegativeInt]] = None,
+ stream_id: Json[NonNegativeInt] | None = None,
topic_name: OptionalTopic = None,
propagate_mode: Literal["change_later", "change_one", "change_all"] = "change_one",
send_notification_to_old_thread: Json[bool] = False,
send_notification_to_new_thread: Json[bool] = True,
- content: Optional[str] = None,
+ content: str | None = None,
) -> HttpResponse:
number_changed = check_update_message(
user_profile,
@@ -158,7 +158,7 @@ def validate_can_delete_message(user_profile: UserProfile, message: Message) ->
# Only user with roles as allowed by delete_own_message_policy can delete message.
raise JsonableError(_("You don't have permission to delete this message"))
- deadline_seconds: Optional[int] = user_profile.realm.message_content_delete_limit_seconds
+ deadline_seconds: int | None = user_profile.realm.message_content_delete_limit_seconds
if deadline_seconds is None:
# None means no time limit to delete message
return
@@ -192,7 +192,7 @@ def delete_message_backend(
@typed_endpoint
def json_fetch_raw_message(
request: HttpRequest,
- maybe_user_profile: Union[UserProfile, AnonymousUser],
+ maybe_user_profile: UserProfile | AnonymousUser,
*,
message_id: PathOnly[NonNegativeInt],
apply_markdown: Json[bool] = True,
diff --git a/zerver/views/message_fetch.py b/zerver/views/message_fetch.py
index b0044d0ea22..09f2c842b9d 100644
--- a/zerver/views/message_fetch.py
+++ b/zerver/views/message_fetch.py
@@ -1,4 +1,4 @@
-from typing import Iterable, Optional, Union
+from typing import Iterable
from django.conf import settings
from django.contrib.auth.models import AnonymousUser
@@ -84,8 +84,8 @@ def get_search_fields(
def clean_narrow_for_web_public_api(
- narrow: Optional[list[NarrowParameter]],
-) -> Optional[list[NarrowParameter]]:
+ narrow: list[NarrowParameter] | None,
+) -> list[NarrowParameter] | None:
if narrow is None:
return None
@@ -102,13 +102,13 @@ def clean_narrow_for_web_public_api(
@typed_endpoint
def get_messages_backend(
request: HttpRequest,
- maybe_user_profile: Union[UserProfile, AnonymousUser],
+ maybe_user_profile: UserProfile | AnonymousUser,
*,
- anchor_val: Annotated[Optional[str], ApiParamConfig("anchor")] = None,
+ anchor_val: Annotated[str | None, ApiParamConfig("anchor")] = None,
include_anchor: Json[bool] = True,
num_before: Json[NonNegativeInt],
num_after: Json[NonNegativeInt],
- narrow: Json[Optional[list[NarrowParameter]]] = None,
+ narrow: Json[list[NarrowParameter] | None] = None,
use_first_unread_anchor_val: Annotated[
Json[bool], ApiParamConfig("use_first_unread_anchor")
] = False,
@@ -150,7 +150,7 @@ def get_messages_backend(
# We use None to indicate unauthenticated requests as it's more
# readable than using AnonymousUser, and the lack of Django
# stubs means that mypy can't check AnonymousUser well.
- user_profile: Optional[UserProfile] = None
+ user_profile: UserProfile | None = None
is_web_public_query = True
else:
assert isinstance(maybe_user_profile, UserProfile)
diff --git a/zerver/views/message_flags.py b/zerver/views/message_flags.py
index fbb2950d036..9e5c3288ea2 100644
--- a/zerver/views/message_flags.py
+++ b/zerver/views/message_flags.py
@@ -1,5 +1,3 @@
-from typing import Optional
-
from django.http import HttpRequest, HttpResponse
from django.utils.translation import gettext as _
from pydantic import Json, NonNegativeInt
@@ -24,7 +22,7 @@ from zerver.lib.typed_endpoint import (
from zerver.models import UserActivity, UserProfile
-def get_latest_update_message_flag_activity(user_profile: UserProfile) -> Optional[UserActivity]:
+def get_latest_update_message_flag_activity(user_profile: UserProfile) -> UserActivity | None:
return (
UserActivity.objects.filter(
user_profile=user_profile,
@@ -77,7 +75,7 @@ def update_message_flags_for_narrow(
include_anchor: Json[bool] = True,
num_before: Json[NonNegativeInt],
num_after: Json[NonNegativeInt],
- narrow: Json[Optional[list[NarrowParameter]]],
+ narrow: Json[list[NarrowParameter] | None],
operation: Annotated[str, ApiParamConfig("op")],
flag: str,
) -> HttpResponse:
diff --git a/zerver/views/message_send.py b/zerver/views/message_send.py
index a38e1c8f190..490233e993f 100644
--- a/zerver/views/message_send.py
+++ b/zerver/views/message_send.py
@@ -1,5 +1,5 @@
from email.headerregistry import Address
-from typing import Iterable, Optional, Sequence, Union, cast
+from typing import Iterable, Sequence, cast
from django.core import validators
from django.core.exceptions import ValidationError
@@ -128,16 +128,16 @@ def send_message_backend(
request: HttpRequest,
user_profile: UserProfile,
req_type: str = REQ("type", str_validator=check_string_in(Message.API_RECIPIENT_TYPES)),
- req_to: Optional[str] = REQ("to", default=None),
- req_sender: Optional[str] = REQ("sender", default=None, documentation_pending=True),
- forged_str: Optional[str] = REQ("forged", default=None, documentation_pending=True),
- topic_name: Optional[str] = REQ_topic(),
+ req_to: str | None = REQ("to", default=None),
+ req_sender: str | None = REQ("sender", default=None, documentation_pending=True),
+ forged_str: str | None = REQ("forged", default=None, documentation_pending=True),
+ topic_name: str | None = REQ_topic(),
message_content: str = REQ("content"),
- widget_content: Optional[str] = REQ(default=None, documentation_pending=True),
- local_id: Optional[str] = REQ(default=None),
- queue_id: Optional[str] = REQ(default=None),
- time: Optional[float] = REQ(default=None, converter=to_float, documentation_pending=True),
- read_by_sender: Optional[bool] = REQ(json_validator=check_bool, default=None),
+ widget_content: str | None = REQ(default=None, documentation_pending=True),
+ local_id: str | None = REQ(default=None),
+ queue_id: str | None = REQ(default=None),
+ time: float | None = REQ(default=None, converter=to_float, documentation_pending=True),
+ read_by_sender: bool | None = REQ(json_validator=check_bool, default=None),
) -> HttpResponse:
recipient_type_name = req_type
if recipient_type_name == "direct":
@@ -153,7 +153,7 @@ def send_message_backend(
# If req_to is None, then we default to an
# empty list of recipients.
- message_to: Union[Sequence[int], Sequence[str]] = []
+ message_to: Sequence[int] | Sequence[str] = []
if req_to is not None:
if recipient_type_name == "stream":
diff --git a/zerver/views/presence.py b/zerver/views/presence.py
index 6702836fa35..de797903276 100644
--- a/zerver/views/presence.py
+++ b/zerver/views/presence.py
@@ -1,5 +1,5 @@
from datetime import timedelta
-from typing import Any, Optional
+from typing import Any
from django.conf import settings
from django.http import HttpRequest, HttpResponse
@@ -80,16 +80,16 @@ def update_user_status_backend(
request: HttpRequest,
user_profile: UserProfile,
*,
- away: Optional[Json[bool]] = None,
+ away: Json[bool] | None = None,
status_text: Annotated[
- Optional[str], StringConstraints(strip_whitespace=True, max_length=60)
+ str | None, StringConstraints(strip_whitespace=True, max_length=60)
] = None,
- emoji_name: Optional[str] = None,
- emoji_code: Optional[str] = None,
+ emoji_name: str | None = None,
+ emoji_code: str | None = None,
# TODO: emoji_type is the more appropriate name for this parameter, but changing
# that requires nontrivial work on the API documentation, since it's not clear
# that the reactions endpoint would prefer such a change.
- emoji_type: Annotated[Optional[str], ApiParamConfig("reaction_type")] = None,
+ emoji_type: Annotated[str | None, ApiParamConfig("reaction_type")] = None,
) -> HttpResponse:
if status_text is not None:
status_text = status_text.strip()
@@ -154,7 +154,7 @@ def update_active_status_backend(
ping_only: Json[bool] = False,
new_user_input: Json[bool] = False,
slim_presence: Json[bool] = False,
- last_update_id: Optional[Json[int]] = None,
+ last_update_id: Json[int] | None = None,
) -> HttpResponse:
if last_update_id is not None:
# This param being submitted by the client, means they want to use
diff --git a/zerver/views/push_notifications.py b/zerver/views/push_notifications.py
index 46b58004730..c344ec5dd6f 100644
--- a/zerver/views/push_notifications.py
+++ b/zerver/views/push_notifications.py
@@ -1,5 +1,3 @@
-from typing import Optional
-
from django.conf import settings
from django.http import HttpRequest, HttpResponse, HttpResponseRedirect
from django.shortcuts import render
@@ -92,7 +90,7 @@ def remove_android_reg_id(
@human_users_only
@typed_endpoint
def send_test_push_notification_api(
- request: HttpRequest, user_profile: UserProfile, *, token: Optional[str] = None
+ request: HttpRequest, user_profile: UserProfile, *, token: str | None = None
) -> HttpResponse:
# If a token is specified in the request, the test notification is supposed to be sent
# to that device. If no token is provided, the test notification should be sent to
@@ -111,7 +109,7 @@ def send_test_push_notification_api(
def self_hosting_auth_view_common(
- request: HttpRequest, user_profile: UserProfile, next_page: Optional[str] = None
+ request: HttpRequest, user_profile: UserProfile, next_page: str | None = None
) -> str:
if not user_profile.has_billing_access:
# We may want to replace this with an html error page at some point,
@@ -167,7 +165,7 @@ def self_hosting_auth_view_common(
def self_hosting_auth_redirect_endpoint(
request: HttpRequest,
*,
- next_page: Optional[str] = None,
+ next_page: str | None = None,
) -> HttpResponse:
"""
This endpoint is used by the web app running in the browser. We serve HTML
@@ -198,7 +196,7 @@ def self_hosting_auth_json_endpoint(
request: HttpRequest,
user_profile: UserProfile,
*,
- next_page: Optional[str] = None,
+ next_page: str | None = None,
) -> HttpResponse:
"""
This endpoint is used by the desktop application. It makes an API request here,
diff --git a/zerver/views/reactions.py b/zerver/views/reactions.py
index 1bab5071670..c1b9c92597b 100644
--- a/zerver/views/reactions.py
+++ b/zerver/views/reactions.py
@@ -1,5 +1,3 @@
-from typing import Optional
-
from django.db import transaction
from django.http import HttpRequest, HttpResponse
from django.utils.translation import gettext as _
@@ -22,8 +20,8 @@ def add_reaction(
message_id: int,
*,
emoji_name: str,
- emoji_code: Optional[str] = None,
- reaction_type: Optional[str] = None,
+ emoji_code: str | None = None,
+ reaction_type: str | None = None,
) -> HttpResponse:
check_add_reaction(user_profile, message_id, emoji_name, emoji_code, reaction_type)
@@ -38,8 +36,8 @@ def remove_reaction(
user_profile: UserProfile,
message_id: int,
*,
- emoji_name: Optional[str] = None,
- emoji_code: Optional[str] = None,
+ emoji_name: str | None = None,
+ emoji_code: str | None = None,
reaction_type: str = "unicode_emoji",
) -> HttpResponse:
message = access_message(user_profile, message_id, lock_message=True)
diff --git a/zerver/views/realm.py b/zerver/views/realm.py
index f72bf29adf3..4f3295899b3 100644
--- a/zerver/views/realm.py
+++ b/zerver/views/realm.py
@@ -1,4 +1,4 @@
-from typing import Any, Mapping, Optional, Union
+from typing import Any, Mapping
from django.core.exceptions import ValidationError
from django.db import transaction
@@ -67,9 +67,7 @@ from zerver.models.realms import (
from zerver.views.user_settings import check_settings_values
-def parse_jitsi_server_url(
- value: str, special_values_map: Mapping[str, Optional[str]]
-) -> Optional[str]:
+def parse_jitsi_server_url(value: str, special_values_map: Mapping[str, str | None]) -> str | None:
if value in special_values_map:
return special_values_map[value]
@@ -99,91 +97,87 @@ def update_realm(
request: HttpRequest,
user_profile: UserProfile,
*,
- name: Annotated[
- Optional[str], StringConstraints(max_length=Realm.MAX_REALM_NAME_LENGTH)
- ] = None,
+ name: Annotated[str | None, StringConstraints(max_length=Realm.MAX_REALM_NAME_LENGTH)] = None,
description: Annotated[
- Optional[str], StringConstraints(max_length=Realm.MAX_REALM_DESCRIPTION_LENGTH)
+ str | None, StringConstraints(max_length=Realm.MAX_REALM_DESCRIPTION_LENGTH)
] = None,
- emails_restricted_to_domains: Optional[Json[bool]] = None,
- disallow_disposable_email_addresses: Optional[Json[bool]] = None,
- invite_required: Optional[Json[bool]] = None,
- invite_to_realm_policy: Optional[Json[InviteToRealmPolicyEnum]] = None,
+ emails_restricted_to_domains: Json[bool] | None = None,
+ disallow_disposable_email_addresses: Json[bool] | None = None,
+ invite_required: Json[bool] | None = None,
+ invite_to_realm_policy: Json[InviteToRealmPolicyEnum] | None = None,
create_multiuse_invite_group_id: Annotated[
- Optional[Json[int]], ApiParamConfig(whence="create_multiuse_invite_group")
+ Json[int] | None, ApiParamConfig(whence="create_multiuse_invite_group")
] = None,
- require_unique_names: Optional[Json[bool]] = None,
- name_changes_disabled: Optional[Json[bool]] = None,
- email_changes_disabled: Optional[Json[bool]] = None,
- avatar_changes_disabled: Optional[Json[bool]] = None,
- inline_image_preview: Optional[Json[bool]] = None,
- inline_url_embed_preview: Optional[Json[bool]] = None,
- add_custom_emoji_policy: Optional[Json[CommonPolicyEnum]] = None,
- delete_own_message_policy: Optional[Json[CommonMessagePolicyEnum]] = None,
+ require_unique_names: Json[bool] | None = None,
+ name_changes_disabled: Json[bool] | None = None,
+ email_changes_disabled: Json[bool] | None = None,
+ avatar_changes_disabled: Json[bool] | None = None,
+ inline_image_preview: Json[bool] | None = None,
+ inline_url_embed_preview: Json[bool] | None = None,
+ add_custom_emoji_policy: Json[CommonPolicyEnum] | None = None,
+ delete_own_message_policy: Json[CommonMessagePolicyEnum] | None = None,
message_content_delete_limit_seconds_raw: Annotated[
- Optional[Json[Union[int, str]]],
+ Json[int | str] | None,
ApiParamConfig("message_content_delete_limit_seconds"),
] = None,
- allow_message_editing: Optional[Json[bool]] = None,
- edit_topic_policy: Optional[Json[EditTopicPolicyEnum]] = None,
- mandatory_topics: Optional[Json[bool]] = None,
+ allow_message_editing: Json[bool] | None = None,
+ edit_topic_policy: Json[EditTopicPolicyEnum] | None = None,
+ mandatory_topics: Json[bool] | None = None,
message_content_edit_limit_seconds_raw: Annotated[
- Optional[Json[Union[int, str]]], ApiParamConfig("message_content_edit_limit_seconds")
+ Json[int | str] | None, ApiParamConfig("message_content_edit_limit_seconds")
] = None,
- allow_edit_history: Optional[Json[bool]] = None,
- default_language: Optional[str] = None,
- waiting_period_threshold: Optional[Json[NonNegativeInt]] = None,
- authentication_methods: Optional[Json[dict[str, Any]]] = None,
+ allow_edit_history: Json[bool] | None = None,
+ default_language: str | None = None,
+ waiting_period_threshold: Json[NonNegativeInt] | None = None,
+ authentication_methods: Json[dict[str, Any]] | None = None,
# Note: push_notifications_enabled and push_notifications_enabled_end_timestamp
# are not offered here as it is maintained by the server, not via the API.
- new_stream_announcements_stream_id: Optional[Json[int]] = None,
- signup_announcements_stream_id: Optional[Json[int]] = None,
- zulip_update_announcements_stream_id: Optional[Json[int]] = None,
+ new_stream_announcements_stream_id: Json[int] | None = None,
+ signup_announcements_stream_id: Json[int] | None = None,
+ zulip_update_announcements_stream_id: Json[int] | None = None,
message_retention_days_raw: Annotated[
- Optional[Json[Union[int, str]]], ApiParamConfig("message_retention_days")
- ] = None,
- send_welcome_emails: Optional[Json[bool]] = None,
- digest_emails_enabled: Optional[Json[bool]] = None,
- message_content_allowed_in_email_notifications: Optional[Json[bool]] = None,
- bot_creation_policy: Optional[Json[BotCreationPolicyEnum]] = None,
- can_create_public_channel_group: Optional[Json[GroupSettingChangeRequest]] = None,
- can_create_private_channel_group: Optional[Json[GroupSettingChangeRequest]] = None,
- direct_message_initiator_group: Optional[Json[GroupSettingChangeRequest]] = None,
- direct_message_permission_group: Optional[Json[GroupSettingChangeRequest]] = None,
- create_web_public_stream_policy: Optional[Json[CreateWebPublicStreamPolicyEnum]] = None,
- invite_to_stream_policy: Optional[Json[CommonPolicyEnum]] = None,
- move_messages_between_streams_policy: Optional[
- Json[MoveMessagesBetweenStreamsPolicyEnum]
+ Json[int | str] | None, ApiParamConfig("message_retention_days")
] = None,
- user_group_edit_policy: Optional[Json[CommonPolicyEnum]] = None,
- wildcard_mention_policy: Optional[Json[WildcardMentionPolicyEnum]] = None,
- video_chat_provider: Optional[Json[int]] = None,
+ send_welcome_emails: Json[bool] | None = None,
+ digest_emails_enabled: Json[bool] | None = None,
+ message_content_allowed_in_email_notifications: Json[bool] | None = None,
+ bot_creation_policy: Json[BotCreationPolicyEnum] | None = None,
+ can_create_public_channel_group: Json[GroupSettingChangeRequest] | None = None,
+ can_create_private_channel_group: Json[GroupSettingChangeRequest] | None = None,
+ direct_message_initiator_group: Json[GroupSettingChangeRequest] | None = None,
+ direct_message_permission_group: Json[GroupSettingChangeRequest] | None = None,
+ create_web_public_stream_policy: Json[CreateWebPublicStreamPolicyEnum] | None = None,
+ invite_to_stream_policy: Json[CommonPolicyEnum] | None = None,
+ move_messages_between_streams_policy: Json[MoveMessagesBetweenStreamsPolicyEnum] | None = None,
+ user_group_edit_policy: Json[CommonPolicyEnum] | None = None,
+ wildcard_mention_policy: Json[WildcardMentionPolicyEnum] | None = None,
+ video_chat_provider: Json[int] | None = None,
jitsi_server_url_raw: Annotated[
- Optional[Json[str]],
+ Json[str] | None,
AfterValidator(lambda val: check_jitsi_url(val)),
ApiParamConfig("jitsi_server_url"),
] = None,
- giphy_rating: Optional[Json[int]] = None,
- default_code_block_language: Optional[str] = None,
- digest_weekday: Optional[Json[DigestWeekdayEnum]] = None,
+ giphy_rating: Json[int] | None = None,
+ default_code_block_language: str | None = None,
+ digest_weekday: Json[DigestWeekdayEnum] | None = None,
string_id: Annotated[
- Optional[str], StringConstraints(max_length=Realm.MAX_REALM_SUBDOMAIN_LENGTH)
+ str | None, StringConstraints(max_length=Realm.MAX_REALM_SUBDOMAIN_LENGTH)
] = None,
- org_type: Optional[Json[OrgTypeEnum]] = None,
- enable_spectator_access: Optional[Json[bool]] = None,
- want_advertise_in_communities_directory: Optional[Json[bool]] = None,
- enable_read_receipts: Optional[Json[bool]] = None,
+ org_type: Json[OrgTypeEnum] | None = None,
+ enable_spectator_access: Json[bool] | None = None,
+ want_advertise_in_communities_directory: Json[bool] | None = None,
+ enable_read_receipts: Json[bool] | None = None,
move_messages_within_stream_limit_seconds_raw: Annotated[
- Optional[Json[Union[int, str]]],
+ Json[int | str] | None,
ApiParamConfig("move_messages_within_stream_limit_seconds"),
] = None,
move_messages_between_streams_limit_seconds_raw: Annotated[
- Optional[Json[Union[int, str]]],
+ Json[int | str] | None,
ApiParamConfig("move_messages_between_streams_limit_seconds"),
] = None,
- enable_guest_user_indicator: Optional[Json[bool]] = None,
+ enable_guest_user_indicator: Json[bool] | None = None,
can_access_all_users_group_id: Annotated[
- Optional[Json[int]], ApiParamConfig("can_access_all_users_group")
+ Json[int] | None, ApiParamConfig("can_access_all_users_group")
] = None,
) -> HttpResponse:
realm = user_profile.realm
@@ -216,7 +210,7 @@ def update_realm(
_("Invalid giphy_rating {giphy_rating}").format(giphy_rating=giphy_rating)
)
- message_retention_days: Optional[int] = None
+ message_retention_days: int | None = None
if message_retention_days_raw is not None:
if not user_profile.is_realm_owner:
raise OrganizationOwnerRequiredError
@@ -248,7 +242,7 @@ def update_realm(
data: dict[str, Any] = {}
- message_content_delete_limit_seconds: Optional[int] = None
+ message_content_delete_limit_seconds: int | None = None
if message_content_delete_limit_seconds_raw is not None:
(
message_content_delete_limit_seconds,
@@ -263,7 +257,7 @@ def update_realm(
if setting_value_changed:
data["message_content_delete_limit_seconds"] = message_content_delete_limit_seconds
- message_content_edit_limit_seconds: Optional[int] = None
+ message_content_edit_limit_seconds: int | None = None
if message_content_edit_limit_seconds_raw is not None:
(
message_content_edit_limit_seconds,
@@ -278,7 +272,7 @@ def update_realm(
if setting_value_changed:
data["message_content_edit_limit_seconds"] = message_content_edit_limit_seconds
- move_messages_within_stream_limit_seconds: Optional[int] = None
+ move_messages_within_stream_limit_seconds: int | None = None
if move_messages_within_stream_limit_seconds_raw is not None:
(
move_messages_within_stream_limit_seconds,
@@ -295,7 +289,7 @@ def update_realm(
move_messages_within_stream_limit_seconds
)
- move_messages_between_streams_limit_seconds: Optional[int] = None
+ move_messages_between_streams_limit_seconds: int | None = None
if move_messages_between_streams_limit_seconds_raw is not None:
(
move_messages_between_streams_limit_seconds,
@@ -312,7 +306,7 @@ def update_realm(
move_messages_between_streams_limit_seconds
)
- jitsi_server_url: Optional[str] = None
+ jitsi_server_url: str | None = None
if jitsi_server_url_raw is not None:
jitsi_server_url = parse_jitsi_server_url(
jitsi_server_url_raw,
@@ -535,78 +529,66 @@ web_home_view_options = ["recent_topics", "inbox", "all_messages"]
def update_realm_user_settings_defaults(
request: HttpRequest,
user_profile: UserProfile,
- dense_mode: Optional[bool] = REQ(json_validator=check_bool, default=None),
- web_mark_read_on_scroll_policy: Optional[int] = REQ(
+ dense_mode: bool | None = REQ(json_validator=check_bool, default=None),
+ web_mark_read_on_scroll_policy: int | None = REQ(
json_validator=check_int_in(UserProfile.WEB_MARK_READ_ON_SCROLL_POLICY_CHOICES),
default=None,
),
- web_channel_default_view: Optional[int] = REQ(
+ web_channel_default_view: int | None = REQ(
json_validator=check_int_in(UserProfile.WEB_CHANNEL_DEFAULT_VIEW_CHOICES),
default=None,
),
- starred_message_counts: Optional[bool] = REQ(json_validator=check_bool, default=None),
- receives_typing_notifications: Optional[bool] = REQ(json_validator=check_bool, default=None),
- web_stream_unreads_count_display_policy: Optional[int] = REQ(
+ starred_message_counts: bool | None = REQ(json_validator=check_bool, default=None),
+ receives_typing_notifications: bool | None = REQ(json_validator=check_bool, default=None),
+ web_stream_unreads_count_display_policy: int | None = REQ(
json_validator=check_int_in(UserProfile.WEB_STREAM_UNREADS_COUNT_DISPLAY_POLICY_CHOICES),
default=None,
),
- fluid_layout_width: Optional[bool] = REQ(json_validator=check_bool, default=None),
- high_contrast_mode: Optional[bool] = REQ(json_validator=check_bool, default=None),
- color_scheme: Optional[int] = REQ(
+ fluid_layout_width: bool | None = REQ(json_validator=check_bool, default=None),
+ high_contrast_mode: bool | None = REQ(json_validator=check_bool, default=None),
+ color_scheme: int | None = REQ(
json_validator=check_int_in(UserProfile.COLOR_SCHEME_CHOICES), default=None
),
- web_font_size_px: Optional[int] = REQ(json_validator=check_int, default=None),
- web_line_height_percent: Optional[int] = REQ(json_validator=check_int, default=None),
- translate_emoticons: Optional[bool] = REQ(json_validator=check_bool, default=None),
- display_emoji_reaction_users: Optional[bool] = REQ(json_validator=check_bool, default=None),
- web_home_view: Optional[str] = REQ(
+ web_font_size_px: int | None = REQ(json_validator=check_int, default=None),
+ web_line_height_percent: int | None = REQ(json_validator=check_int, default=None),
+ translate_emoticons: bool | None = REQ(json_validator=check_bool, default=None),
+ display_emoji_reaction_users: bool | None = REQ(json_validator=check_bool, default=None),
+ web_home_view: str | None = REQ(
str_validator=check_string_in(web_home_view_options), default=None
),
- web_escape_navigates_to_home_view: Optional[bool] = REQ(
- json_validator=check_bool, default=None
- ),
- left_side_userlist: Optional[bool] = REQ(json_validator=check_bool, default=None),
- emojiset: Optional[str] = REQ(str_validator=check_string_in(emojiset_choices), default=None),
- demote_inactive_streams: Optional[int] = REQ(
+ web_escape_navigates_to_home_view: bool | None = REQ(json_validator=check_bool, default=None),
+ left_side_userlist: bool | None = REQ(json_validator=check_bool, default=None),
+ emojiset: str | None = REQ(str_validator=check_string_in(emojiset_choices), default=None),
+ demote_inactive_streams: int | None = REQ(
json_validator=check_int_in(UserProfile.DEMOTE_STREAMS_CHOICES), default=None
),
- enable_stream_desktop_notifications: Optional[bool] = REQ(
- json_validator=check_bool, default=None
- ),
- enable_stream_email_notifications: Optional[bool] = REQ(
- json_validator=check_bool, default=None
- ),
- enable_stream_push_notifications: Optional[bool] = REQ(json_validator=check_bool, default=None),
- enable_stream_audible_notifications: Optional[bool] = REQ(
- json_validator=check_bool, default=None
- ),
- wildcard_mentions_notify: Optional[bool] = REQ(json_validator=check_bool, default=None),
- enable_followed_topic_desktop_notifications: Optional[bool] = REQ(
- json_validator=check_bool, default=None
- ),
- enable_followed_topic_email_notifications: Optional[bool] = REQ(
- json_validator=check_bool, default=None
- ),
- enable_followed_topic_push_notifications: Optional[bool] = REQ(
+ enable_stream_desktop_notifications: bool | None = REQ(json_validator=check_bool, default=None),
+ enable_stream_email_notifications: bool | None = REQ(json_validator=check_bool, default=None),
+ enable_stream_push_notifications: bool | None = REQ(json_validator=check_bool, default=None),
+ enable_stream_audible_notifications: bool | None = REQ(json_validator=check_bool, default=None),
+ wildcard_mentions_notify: bool | None = REQ(json_validator=check_bool, default=None),
+ enable_followed_topic_desktop_notifications: bool | None = REQ(
json_validator=check_bool, default=None
),
- enable_followed_topic_audible_notifications: Optional[bool] = REQ(
+ enable_followed_topic_email_notifications: bool | None = REQ(
json_validator=check_bool, default=None
),
- enable_followed_topic_wildcard_mentions_notify: Optional[bool] = REQ(
+ enable_followed_topic_push_notifications: bool | None = REQ(
json_validator=check_bool, default=None
),
- notification_sound: Optional[str] = REQ(default=None),
- enable_desktop_notifications: Optional[bool] = REQ(json_validator=check_bool, default=None),
- enable_sounds: Optional[bool] = REQ(json_validator=check_bool, default=None),
- enable_offline_email_notifications: Optional[bool] = REQ(
+ enable_followed_topic_audible_notifications: bool | None = REQ(
json_validator=check_bool, default=None
),
- enable_offline_push_notifications: Optional[bool] = REQ(
+ enable_followed_topic_wildcard_mentions_notify: bool | None = REQ(
json_validator=check_bool, default=None
),
- enable_online_push_notifications: Optional[bool] = REQ(json_validator=check_bool, default=None),
- enable_digest_emails: Optional[bool] = REQ(json_validator=check_bool, default=None),
+ notification_sound: str | None = REQ(default=None),
+ enable_desktop_notifications: bool | None = REQ(json_validator=check_bool, default=None),
+ enable_sounds: bool | None = REQ(json_validator=check_bool, default=None),
+ enable_offline_email_notifications: bool | None = REQ(json_validator=check_bool, default=None),
+ enable_offline_push_notifications: bool | None = REQ(json_validator=check_bool, default=None),
+ enable_online_push_notifications: bool | None = REQ(json_validator=check_bool, default=None),
+ enable_digest_emails: bool | None = REQ(json_validator=check_bool, default=None),
# enable_login_emails is not included here, because we don't want
# security-related settings to be controlled by organization administrators.
# enable_marketing_emails is not included here, since we don't at
@@ -615,49 +597,45 @@ def update_realm_user_settings_defaults(
#
# We may want to change this model in the future, since some SSO signups
# do not offer an opportunity to prompt the user at all during signup.
- message_content_in_email_notifications: Optional[bool] = REQ(
+ message_content_in_email_notifications: bool | None = REQ(
json_validator=check_bool, default=None
),
- pm_content_in_desktop_notifications: Optional[bool] = REQ(
- json_validator=check_bool, default=None
- ),
- desktop_icon_count_display: Optional[int] = REQ(
+ pm_content_in_desktop_notifications: bool | None = REQ(json_validator=check_bool, default=None),
+ desktop_icon_count_display: int | None = REQ(
json_validator=check_int_in(UserProfile.DESKTOP_ICON_COUNT_DISPLAY_CHOICES), default=None
),
- realm_name_in_email_notifications_policy: Optional[int] = REQ(
+ realm_name_in_email_notifications_policy: int | None = REQ(
json_validator=check_int_in(UserProfile.REALM_NAME_IN_EMAIL_NOTIFICATIONS_POLICY_CHOICES),
default=None,
),
- automatically_follow_topics_policy: Optional[int] = REQ(
+ automatically_follow_topics_policy: int | None = REQ(
json_validator=check_int_in(UserProfile.AUTOMATICALLY_CHANGE_VISIBILITY_POLICY_CHOICES),
default=None,
),
- automatically_unmute_topics_in_muted_streams_policy: Optional[int] = REQ(
+ automatically_unmute_topics_in_muted_streams_policy: int | None = REQ(
json_validator=check_int_in(UserProfile.AUTOMATICALLY_CHANGE_VISIBILITY_POLICY_CHOICES),
default=None,
),
- automatically_follow_topics_where_mentioned: Optional[bool] = REQ(
+ automatically_follow_topics_where_mentioned: bool | None = REQ(
json_validator=check_bool, default=None
),
- presence_enabled: Optional[bool] = REQ(json_validator=check_bool, default=None),
- enter_sends: Optional[bool] = REQ(json_validator=check_bool, default=None),
- enable_drafts_synchronization: Optional[bool] = REQ(json_validator=check_bool, default=None),
- email_notifications_batching_period_seconds: Optional[int] = REQ(
+ presence_enabled: bool | None = REQ(json_validator=check_bool, default=None),
+ enter_sends: bool | None = REQ(json_validator=check_bool, default=None),
+ enable_drafts_synchronization: bool | None = REQ(json_validator=check_bool, default=None),
+ email_notifications_batching_period_seconds: int | None = REQ(
json_validator=check_int, default=None
),
- twenty_four_hour_time: Optional[bool] = REQ(json_validator=check_bool, default=None),
- send_stream_typing_notifications: Optional[bool] = REQ(json_validator=check_bool, default=None),
- send_private_typing_notifications: Optional[bool] = REQ(
- json_validator=check_bool, default=None
- ),
- send_read_receipts: Optional[bool] = REQ(json_validator=check_bool, default=None),
- user_list_style: Optional[int] = REQ(
+ twenty_four_hour_time: bool | None = REQ(json_validator=check_bool, default=None),
+ send_stream_typing_notifications: bool | None = REQ(json_validator=check_bool, default=None),
+ send_private_typing_notifications: bool | None = REQ(json_validator=check_bool, default=None),
+ send_read_receipts: bool | None = REQ(json_validator=check_bool, default=None),
+ user_list_style: int | None = REQ(
json_validator=check_int_in(UserProfile.USER_LIST_STYLE_CHOICES), default=None
),
- email_address_visibility: Optional[int] = REQ(
+ email_address_visibility: int | None = REQ(
json_validator=check_int_in(UserProfile.EMAIL_ADDRESS_VISIBILITY_TYPES), default=None
),
- web_navigate_to_sent_message: Optional[bool] = REQ(json_validator=check_bool, default=None),
+ web_navigate_to_sent_message: bool | None = REQ(json_validator=check_bool, default=None),
) -> HttpResponse:
if notification_sound is not None or email_notifications_batching_period_seconds is not None:
check_settings_values(notification_sound, email_notifications_batching_period_seconds)
diff --git a/zerver/views/registration.py b/zerver/views/registration.py
index 417e36cae78..0053dfbb9df 100644
--- a/zerver/views/registration.py
+++ b/zerver/views/registration.py
@@ -1,6 +1,6 @@
import logging
from contextlib import suppress
-from typing import Any, Iterable, Optional, Union
+from typing import Any, Iterable
from urllib.parse import urlencode, urljoin
import orjson
@@ -120,7 +120,7 @@ if settings.BILLING_ENABLED:
@has_request_variables
def get_prereg_key_and_redirect(
- request: HttpRequest, confirmation_key: str, full_name: Optional[str] = REQ(default=None)
+ request: HttpRequest, confirmation_key: str, full_name: str | None = REQ(default=None)
) -> HttpResponse:
"""
The purpose of this little endpoint is primarily to take a GET
@@ -159,7 +159,7 @@ def get_prereg_key_and_redirect(
def check_prereg_key(
request: HttpRequest, confirmation_key: str
-) -> tuple[Union[PreregistrationUser, PreregistrationRealm], bool]:
+) -> tuple[PreregistrationUser | PreregistrationRealm, bool]:
"""
Checks if the Confirmation key is valid, returning the PreregistrationUser or
PreregistrationRealm object in case of success and raising an appropriate
@@ -193,7 +193,7 @@ def check_prereg_key(
return prereg_object, realm_creation
-def get_selected_realm_type_name(prereg_realm: Optional[PreregistrationRealm]) -> Optional[str]:
+def get_selected_realm_type_name(prereg_realm: PreregistrationRealm | None) -> str | None:
if prereg_realm is None:
# We show the selected realm type only when creating new realm.
return None
@@ -202,8 +202,8 @@ def get_selected_realm_type_name(prereg_realm: Optional[PreregistrationRealm]) -
def get_selected_realm_default_language_name(
- prereg_realm: Optional[PreregistrationRealm],
-) -> Optional[str]:
+ prereg_realm: PreregistrationRealm | None,
+) -> str | None:
if prereg_realm is None:
# We show the selected realm language only when creating new realm.
return None
@@ -227,12 +227,12 @@ def registration_helper(
request: HttpRequest,
key: str = REQ(default=""),
timezone: str = REQ(default="", converter=to_timezone_or_empty),
- from_confirmation: Optional[str] = REQ(default=None),
- form_full_name: Optional[str] = REQ("full_name", default=None),
- source_realm_id: Optional[int] = REQ(
+ from_confirmation: str | None = REQ(default=None),
+ form_full_name: str | None = REQ("full_name", default=None),
+ source_realm_id: int | None = REQ(
default=None, converter=to_converted_or_fallback(to_non_negative_int, None)
),
- form_is_demo_organization: Optional[str] = REQ("is_demo_organization", default=None),
+ form_is_demo_organization: str | None = REQ("is_demo_organization", default=None),
) -> HttpResponse:
try:
prereg_object, realm_creation = check_prereg_key(request, key)
@@ -521,21 +521,19 @@ def registration_helper(
if source_realm_id is not None:
# Non-integer realm_id values like "string" are treated
# like the "Do not import" value of "".
- source_profile: Optional[UserProfile] = get_source_profile(email, source_realm_id)
+ source_profile: UserProfile | None = get_source_profile(email, source_realm_id)
else:
source_profile = None
if not realm_creation:
try:
- existing_user_profile: Optional[UserProfile] = get_user_by_delivery_email(
- email, realm
- )
+ existing_user_profile: UserProfile | None = get_user_by_delivery_email(email, realm)
except UserProfile.DoesNotExist:
existing_user_profile = None
else:
existing_user_profile = None
- user_profile: Optional[UserProfile] = None
+ user_profile: UserProfile | None = None
return_data: dict[str, bool] = {}
if ldap_auth_enabled(realm):
# If the user was authenticated using an external SSO
@@ -764,11 +762,11 @@ def prepare_activation_url(
email: str,
session: SessionBase,
*,
- realm: Optional[Realm],
- streams: Optional[Iterable[Stream]] = None,
- invited_as: Optional[int] = None,
- include_realm_default_subscriptions: Optional[bool] = None,
- multiuse_invite: Optional[MultiuseInvite] = None,
+ realm: Realm | None,
+ streams: Iterable[Stream] | None = None,
+ invited_as: int | None = None,
+ include_realm_default_subscriptions: bool | None = None,
+ multiuse_invite: MultiuseInvite | None = None,
) -> str:
"""
Send an email with a confirmation link to the provided e-mail so the user
@@ -818,10 +816,10 @@ def send_confirm_registration_email(
email: str,
activation_url: str,
*,
- realm: Optional[Realm] = None,
- realm_subdomain: Optional[str] = None,
- realm_type: Optional[int] = None,
- request: Optional[HttpRequest] = None,
+ realm: Realm | None = None,
+ realm_subdomain: str | None = None,
+ realm_type: int | None = None,
+ request: HttpRequest | None = None,
) -> None:
org_url = ""
org_type = ""
@@ -856,7 +854,7 @@ def redirect_to_email_login_url(email: str) -> HttpResponseRedirect:
@add_google_analytics
-def create_realm(request: HttpRequest, creation_key: Optional[str] = None) -> HttpResponse:
+def create_realm(request: HttpRequest, creation_key: str | None = None) -> HttpResponse:
try:
key_record = validate_key(creation_key)
except RealmCreationKey.InvalidError:
@@ -1010,7 +1008,7 @@ def new_realm_send_confirm(
def accounts_home(
request: HttpRequest,
multiuse_object_key: str = "",
- multiuse_object: Optional[MultiuseInvite] = None,
+ multiuse_object: MultiuseInvite | None = None,
) -> HttpResponse:
try:
realm = get_realm(get_subdomain(request))
@@ -1096,7 +1094,7 @@ def accounts_home(
def accounts_home_from_multiuse_invite(request: HttpRequest, confirmation_key: str) -> HttpResponse:
realm = get_realm_from_request(request)
- multiuse_object: Optional[MultiuseInvite] = None
+ multiuse_object: MultiuseInvite | None = None
try:
confirmation_obj = get_object_from_key(
confirmation_key, [Confirmation.MULTIUSE_INVITE], mark_object_used=False
diff --git a/zerver/views/scheduled_messages.py b/zerver/views/scheduled_messages.py
index cc01ef047ff..cc1360be5ea 100644
--- a/zerver/views/scheduled_messages.py
+++ b/zerver/views/scheduled_messages.py
@@ -1,5 +1,3 @@
-from typing import Optional
-
from django.http import HttpRequest, HttpResponse
from django.utils.timezone import now as timezone_now
from django.utils.translation import gettext as _
@@ -42,13 +40,13 @@ def update_scheduled_message_backend(
request: HttpRequest,
user_profile: UserProfile,
scheduled_message_id: int = REQ(converter=to_non_negative_int, path_only=True),
- req_type: Optional[str] = REQ(
+ req_type: str | None = REQ(
"type", str_validator=check_string_in(Message.API_RECIPIENT_TYPES), default=None
),
- req_to: Optional[str] = REQ("to", default=None),
- topic_name: Optional[str] = REQ_topic(),
- message_content: Optional[str] = REQ("content", default=None),
- scheduled_delivery_timestamp: Optional[int] = REQ(json_validator=check_int, default=None),
+ req_to: str | None = REQ("to", default=None),
+ topic_name: str | None = REQ_topic(),
+ message_content: str | None = REQ("content", default=None),
+ scheduled_delivery_timestamp: int | None = REQ(json_validator=check_int, default=None),
) -> HttpResponse:
if (
req_type is None
@@ -118,10 +116,10 @@ def create_scheduled_message_backend(
user_profile: UserProfile,
req_type: str = REQ("type", str_validator=check_string_in(Message.API_RECIPIENT_TYPES)),
req_to: str = REQ("to"),
- topic_name: Optional[str] = REQ_topic(),
+ topic_name: str | None = REQ_topic(),
message_content: str = REQ("content"),
scheduled_delivery_timestamp: int = REQ(json_validator=check_int),
- read_by_sender: Optional[bool] = REQ(json_validator=check_bool, default=None),
+ read_by_sender: bool | None = REQ(json_validator=check_bool, default=None),
) -> HttpResponse:
recipient_type_name = req_type
if recipient_type_name == "direct":
diff --git a/zerver/views/storage.py b/zerver/views/storage.py
index 6c3ca5ad5d3..ba0b92ad681 100644
--- a/zerver/views/storage.py
+++ b/zerver/views/storage.py
@@ -1,5 +1,3 @@
-from typing import Optional
-
from django.http import HttpRequest, HttpResponse
from pydantic import Json
@@ -35,7 +33,7 @@ def get_storage(
request: HttpRequest,
user_profile: UserProfile,
*,
- keys: Json[Optional[list[str]]] = None,
+ keys: Json[list[str] | None] = None,
) -> HttpResponse:
if keys is None:
keys = get_keys_in_bot_storage(user_profile)
@@ -51,7 +49,7 @@ def remove_storage(
request: HttpRequest,
user_profile: UserProfile,
*,
- keys: Json[Optional[list[str]]] = None,
+ keys: Json[list[str] | None] = None,
) -> HttpResponse:
if keys is None:
keys = get_keys_in_bot_storage(user_profile)
diff --git a/zerver/views/streams.py b/zerver/views/streams.py
index a6bcefcc8cb..287ed0a7b9d 100644
--- a/zerver/views/streams.py
+++ b/zerver/views/streams.py
@@ -1,6 +1,6 @@
import time
from collections import defaultdict
-from typing import Any, Callable, Mapping, Optional, Sequence, Union
+from typing import Any, Callable, Mapping, Sequence
import orjson
from django.conf import settings
@@ -94,7 +94,7 @@ from zerver.models import NamedUserGroup, Realm, Stream, UserProfile
from zerver.models.users import get_system_bot
-def principal_to_user_profile(agent: UserProfile, principal: Union[str, int]) -> UserProfile:
+def principal_to_user_profile(agent: UserProfile, principal: str | int) -> UserProfile:
if isinstance(principal, str):
return access_user_by_email(
agent, principal, allow_deactivated=False, allow_bots=True, for_admin=False
@@ -158,8 +158,8 @@ def update_default_stream_group_info(
request: HttpRequest,
user_profile: UserProfile,
group_id: int,
- new_group_name: Optional[str] = REQ(default=None),
- new_description: Optional[str] = REQ(default=None),
+ new_group_name: str | None = REQ(default=None),
+ new_description: str | None = REQ(default=None),
) -> HttpResponse:
if not new_group_name and not new_description:
raise JsonableError(_('You must pass "new_description" or "new_group_name".'))
@@ -225,22 +225,22 @@ def update_stream_backend(
request: HttpRequest,
user_profile: UserProfile,
stream_id: int,
- description: Optional[str] = REQ(
+ description: str | None = REQ(
str_validator=check_capped_string(Stream.MAX_DESCRIPTION_LENGTH), default=None
),
- is_private: Optional[bool] = REQ(json_validator=check_bool, default=None),
- is_announcement_only: Optional[bool] = REQ(json_validator=check_bool, default=None),
- is_default_stream: Optional[bool] = REQ(json_validator=check_bool, default=None),
- stream_post_policy: Optional[int] = REQ(
+ is_private: bool | None = REQ(json_validator=check_bool, default=None),
+ is_announcement_only: bool | None = REQ(json_validator=check_bool, default=None),
+ is_default_stream: bool | None = REQ(json_validator=check_bool, default=None),
+ stream_post_policy: int | None = REQ(
json_validator=check_int_in(Stream.STREAM_POST_POLICY_TYPES), default=None
),
- history_public_to_subscribers: Optional[bool] = REQ(json_validator=check_bool, default=None),
- is_web_public: Optional[bool] = REQ(json_validator=check_bool, default=None),
- new_name: Optional[str] = REQ(default=None),
- message_retention_days: Optional[Union[int, str]] = REQ(
+ history_public_to_subscribers: bool | None = REQ(json_validator=check_bool, default=None),
+ is_web_public: bool | None = REQ(json_validator=check_bool, default=None),
+ new_name: str | None = REQ(default=None),
+ message_retention_days: int | str | None = REQ(
json_validator=check_string_or_int, default=None
),
- can_remove_subscribers_group_id: Optional[int] = REQ(
+ can_remove_subscribers_group_id: int | None = REQ(
"can_remove_subscribers_group", json_validator=check_int, default=None
),
) -> HttpResponse:
@@ -458,7 +458,7 @@ def compose_views(thunks: list[Callable[[], HttpResponse]]) -> dict[str, Any]:
return json_dict
-check_principals: Validator[Union[list[str], list[int]]] = check_union(
+check_principals: Validator[list[str] | list[int]] = check_union(
[check_list(check_string), check_list(check_int)],
)
@@ -468,9 +468,7 @@ def remove_subscriptions_backend(
request: HttpRequest,
user_profile: UserProfile,
streams_raw: Sequence[str] = REQ("subscriptions", json_validator=remove_subscriptions_schema),
- principals: Optional[Union[list[str], list[int]]] = REQ(
- json_validator=check_principals, default=None
- ),
+ principals: list[str] | list[int] | None = REQ(json_validator=check_principals, default=None),
) -> HttpResponse:
realm = user_profile.realm
@@ -529,8 +527,8 @@ def you_were_just_subscribed_message(
return message
-RETENTION_DEFAULT: Union[str, int] = "realm_default"
-EMPTY_PRINCIPALS: Union[Sequence[str], Sequence[int]] = []
+RETENTION_DEFAULT: str | int = "realm_default"
+EMPTY_PRINCIPALS: Sequence[str] | Sequence[int] = []
@transaction.atomic(savepoint=False)
@@ -549,15 +547,15 @@ def add_subscriptions_backend(
json_validator=check_int_in(Stream.STREAM_POST_POLICY_TYPES),
default=Stream.STREAM_POST_POLICY_EVERYONE,
),
- history_public_to_subscribers: Optional[bool] = REQ(json_validator=check_bool, default=None),
- message_retention_days: Union[str, int] = REQ(
+ history_public_to_subscribers: bool | None = REQ(json_validator=check_bool, default=None),
+ message_retention_days: str | int = REQ(
json_validator=check_string_or_int, default=RETENTION_DEFAULT
),
- can_remove_subscribers_group_id: Optional[int] = REQ(
+ can_remove_subscribers_group_id: int | None = REQ(
"can_remove_subscribers_group", json_validator=check_int, default=None
),
announce: bool = REQ(json_validator=check_bool, default=False),
- principals: Union[Sequence[str], Sequence[int]] = REQ(
+ principals: Sequence[str] | Sequence[int] = REQ(
json_validator=check_principals,
default=EMPTY_PRINCIPALS,
),
@@ -872,12 +870,12 @@ def get_stream_backend(
@has_request_variables
def get_topics_backend(
request: HttpRequest,
- maybe_user_profile: Union[UserProfile, AnonymousUser],
+ maybe_user_profile: UserProfile | AnonymousUser,
stream_id: int = REQ(converter=to_non_negative_int, path_only=True),
) -> HttpResponse:
if not maybe_user_profile.is_authenticated:
is_web_public_query = True
- user_profile: Optional[UserProfile] = None
+ user_profile: UserProfile | None = None
else:
is_web_public_query = False
assert isinstance(maybe_user_profile, UserProfile)
diff --git a/zerver/views/thumbnail.py b/zerver/views/thumbnail.py
index 824a6ed3826..b9938c6c7e5 100644
--- a/zerver/views/thumbnail.py
+++ b/zerver/views/thumbnail.py
@@ -1,5 +1,3 @@
-from typing import Optional, Union
-
from django.contrib.auth.models import AnonymousUser
from django.http import HttpRequest, HttpResponse, HttpResponseForbidden
from django.shortcuts import redirect
@@ -14,9 +12,9 @@ from zerver.models import Realm, UserProfile
def validate_thumbnail_request(
realm: Realm,
- maybe_user_profile: Union[UserProfile, AnonymousUser],
+ maybe_user_profile: UserProfile | AnonymousUser,
path: str,
-) -> Optional[bool]:
+) -> bool | None:
# path here does not have a leading / as it is parsed from request hitting the
# thumbnail endpoint (defined in urls.py) that way.
if path.startswith("user_uploads/"):
@@ -30,7 +28,7 @@ def validate_thumbnail_request(
@typed_endpoint
def backend_serve_thumbnail(
request: HttpRequest,
- maybe_user_profile: Union[UserProfile, AnonymousUser],
+ maybe_user_profile: UserProfile | AnonymousUser,
*,
url: str,
size: str,
diff --git a/zerver/views/typing.py b/zerver/views/typing.py
index 10281a2967d..3e146302ff2 100644
--- a/zerver/views/typing.py
+++ b/zerver/views/typing.py
@@ -1,5 +1,3 @@
-from typing import Optional
-
from django.http import HttpRequest, HttpResponse
from django.utils.translation import gettext as _
from pydantic import Json
@@ -20,8 +18,8 @@ def send_notification_backend(
*,
req_type: Annotated[Literal["direct", "stream", "channel"], ApiParamConfig("type")] = "direct",
operator: Annotated[Literal["start", "stop"], ApiParamConfig("op")],
- notification_to: Annotated[Json[Optional[list[int]]], ApiParamConfig("to")] = None,
- stream_id: Json[Optional[int]] = None,
+ notification_to: Annotated[Json[list[int] | None], ApiParamConfig("to")] = None,
+ stream_id: Json[int | None] = None,
topic: OptionalTopic = None,
) -> HttpResponse:
recipient_type_name = req_type
diff --git a/zerver/views/upload.py b/zerver/views/upload.py
index feeb3d76ffe..d941b1f72ab 100644
--- a/zerver/views/upload.py
+++ b/zerver/views/upload.py
@@ -2,7 +2,6 @@ import base64
import binascii
import os
from datetime import timedelta
-from typing import Optional, Union
from urllib.parse import quote, urlsplit
from django.conf import settings
@@ -49,7 +48,7 @@ def patch_disposition_header(response: HttpResponse, url: str, is_attachment: bo
response.headers["Content-Disposition"] = content_disposition
-def internal_nginx_redirect(internal_path: str, content_type: Optional[str] = None) -> HttpResponse:
+def internal_nginx_redirect(internal_path: str, content_type: str | None = None) -> HttpResponse:
# The following headers from this initial response are
# _preserved_, if present, and sent unmodified to the client;
# all other headers are overridden by the redirected URL:
@@ -142,7 +141,7 @@ def serve_local(
def serve_file_download_backend(
request: HttpRequest,
- maybe_user_profile: Union[UserProfile, AnonymousUser],
+ maybe_user_profile: UserProfile | AnonymousUser,
realm_id_str: str,
filename: str,
) -> HttpResponseBase:
@@ -153,7 +152,7 @@ def serve_file_download_backend(
def serve_file_backend(
request: HttpRequest,
- maybe_user_profile: Union[UserProfile, AnonymousUser],
+ maybe_user_profile: UserProfile | AnonymousUser,
realm_id_str: str,
filename: str,
) -> HttpResponseBase:
@@ -171,7 +170,7 @@ def serve_file_url_backend(
return serve_file(request, user_profile, realm_id_str, filename, url_only=True)
-def preferred_accept(request: HttpRequest, served_types: list[str]) -> Optional[str]:
+def preferred_accept(request: HttpRequest, served_types: list[str]) -> str | None:
# Returns the first of the served_types which the browser will
# accept, based on the browser's stated quality preferences.
# Returns None if none of the served_types are accepted by the
@@ -190,7 +189,7 @@ def preferred_accept(request: HttpRequest, served_types: list[str]) -> Optional[
def serve_file(
request: HttpRequest,
- maybe_user_profile: Union[UserProfile, AnonymousUser],
+ maybe_user_profile: UserProfile | AnonymousUser,
realm_id_str: str,
filename: str,
url_only: bool = False,
@@ -245,7 +244,7 @@ def generate_unauthed_file_access_url(path_id: str) -> str:
return reverse("file_unauthed_from_token", args=[token, filename])
-def get_file_path_id_from_token(token: str) -> Optional[str]:
+def get_file_path_id_from_token(token: str) -> str | None:
signer = TimestampSigner(salt=USER_UPLOADS_ACCESS_TOKEN_SALT)
try:
signed_data = base64.b16decode(token).decode()
diff --git a/zerver/views/user_groups.py b/zerver/views/user_groups.py
index f056769a2ce..175b59fa9b7 100644
--- a/zerver/views/user_groups.py
+++ b/zerver/views/user_groups.py
@@ -1,4 +1,4 @@
-from typing import Optional, Sequence, Union
+from typing import Sequence
from django.conf import settings
from django.db import transaction
@@ -58,7 +58,7 @@ def add_user_group(
name: str,
members: Json[Sequence[int]],
description: str,
- can_mention_group: Optional[Json[Union[int, AnonymousSettingGroupDict]]] = None,
+ can_mention_group: Json[int | AnonymousSettingGroupDict] | None = None,
) -> HttpResponse:
user_profiles = user_ids_to_users(members, user_profile.realm)
name = check_user_group_name(name)
@@ -107,9 +107,9 @@ def edit_user_group(
user_profile: UserProfile,
*,
user_group_id: PathOnly[int],
- name: Optional[str] = None,
- description: Optional[str] = None,
- can_mention_group: Optional[Json[GroupSettingChangeRequest]] = None,
+ name: str | None = None,
+ description: str | None = None,
+ can_mention_group: Json[GroupSettingChangeRequest] | None = None,
) -> HttpResponse:
if name is None and description is None and can_mention_group is None:
raise JsonableError(_("No new data supplied"))
diff --git a/zerver/views/user_settings.py b/zerver/views/user_settings.py
index 98ee5bb8294..1fbf95cb60a 100644
--- a/zerver/views/user_settings.py
+++ b/zerver/views/user_settings.py
@@ -1,5 +1,5 @@
from email.headerregistry import Address
-from typing import Any, Optional
+from typing import Any
from django.conf import settings
from django.contrib.auth import authenticate, update_session_auth_hash
@@ -159,9 +159,9 @@ web_home_view_options = ["recent_topics", "inbox", "all_messages"]
def check_settings_values(
- notification_sound: Optional[str],
- email_notifications_batching_period_seconds: Optional[int],
- default_language: Optional[str] = None,
+ notification_sound: str | None,
+ email_notifications_batching_period_seconds: int | None,
+ default_language: str | None = None,
) -> None:
# We can't use REQ for this widget because
# get_available_language_codes requires provisioning to be
@@ -197,129 +197,113 @@ def check_settings_values(
def json_change_settings(
request: HttpRequest,
user_profile: UserProfile,
- full_name: Optional[str] = REQ(default=None),
- email: Optional[str] = REQ(default=None),
- old_password: Optional[str] = REQ(default=None),
- new_password: Optional[str] = REQ(default=None),
- twenty_four_hour_time: Optional[bool] = REQ(json_validator=check_bool, default=None),
- dense_mode: Optional[bool] = REQ(json_validator=check_bool, default=None),
- web_mark_read_on_scroll_policy: Optional[int] = REQ(
+ full_name: str | None = REQ(default=None),
+ email: str | None = REQ(default=None),
+ old_password: str | None = REQ(default=None),
+ new_password: str | None = REQ(default=None),
+ twenty_four_hour_time: bool | None = REQ(json_validator=check_bool, default=None),
+ dense_mode: bool | None = REQ(json_validator=check_bool, default=None),
+ web_mark_read_on_scroll_policy: int | None = REQ(
json_validator=check_int_in(UserProfile.WEB_MARK_READ_ON_SCROLL_POLICY_CHOICES),
default=None,
),
- web_channel_default_view: Optional[int] = REQ(
+ web_channel_default_view: int | None = REQ(
json_validator=check_int_in(UserProfile.WEB_CHANNEL_DEFAULT_VIEW_CHOICES),
default=None,
),
- starred_message_counts: Optional[bool] = REQ(json_validator=check_bool, default=None),
- receives_typing_notifications: Optional[bool] = REQ(json_validator=check_bool, default=None),
- fluid_layout_width: Optional[bool] = REQ(json_validator=check_bool, default=None),
- high_contrast_mode: Optional[bool] = REQ(json_validator=check_bool, default=None),
- color_scheme: Optional[int] = REQ(
+ starred_message_counts: bool | None = REQ(json_validator=check_bool, default=None),
+ receives_typing_notifications: bool | None = REQ(json_validator=check_bool, default=None),
+ fluid_layout_width: bool | None = REQ(json_validator=check_bool, default=None),
+ high_contrast_mode: bool | None = REQ(json_validator=check_bool, default=None),
+ color_scheme: int | None = REQ(
json_validator=check_int_in(UserProfile.COLOR_SCHEME_CHOICES), default=None
),
- web_font_size_px: Optional[int] = REQ(json_validator=check_int, default=None),
- web_line_height_percent: Optional[int] = REQ(json_validator=check_int, default=None),
- translate_emoticons: Optional[bool] = REQ(json_validator=check_bool, default=None),
- display_emoji_reaction_users: Optional[bool] = REQ(json_validator=check_bool, default=None),
- default_language: Optional[str] = REQ(default=None),
- web_home_view: Optional[str] = REQ(
+ web_font_size_px: int | None = REQ(json_validator=check_int, default=None),
+ web_line_height_percent: int | None = REQ(json_validator=check_int, default=None),
+ translate_emoticons: bool | None = REQ(json_validator=check_bool, default=None),
+ display_emoji_reaction_users: bool | None = REQ(json_validator=check_bool, default=None),
+ default_language: str | None = REQ(default=None),
+ web_home_view: str | None = REQ(
str_validator=check_string_in(web_home_view_options), default=None
),
- web_escape_navigates_to_home_view: Optional[bool] = REQ(
- json_validator=check_bool, default=None
- ),
- left_side_userlist: Optional[bool] = REQ(json_validator=check_bool, default=None),
- emojiset: Optional[str] = REQ(str_validator=check_string_in(emojiset_choices), default=None),
- demote_inactive_streams: Optional[int] = REQ(
+ web_escape_navigates_to_home_view: bool | None = REQ(json_validator=check_bool, default=None),
+ left_side_userlist: bool | None = REQ(json_validator=check_bool, default=None),
+ emojiset: str | None = REQ(str_validator=check_string_in(emojiset_choices), default=None),
+ demote_inactive_streams: int | None = REQ(
json_validator=check_int_in(UserProfile.DEMOTE_STREAMS_CHOICES), default=None
),
- web_stream_unreads_count_display_policy: Optional[int] = REQ(
+ web_stream_unreads_count_display_policy: int | None = REQ(
json_validator=check_int_in(UserProfile.WEB_STREAM_UNREADS_COUNT_DISPLAY_POLICY_CHOICES),
default=None,
),
- timezone: Optional[str] = REQ(str_validator=check_timezone, default=None),
- email_notifications_batching_period_seconds: Optional[int] = REQ(
+ timezone: str | None = REQ(str_validator=check_timezone, default=None),
+ email_notifications_batching_period_seconds: int | None = REQ(
json_validator=check_int, default=None
),
- enable_drafts_synchronization: Optional[bool] = REQ(json_validator=check_bool, default=None),
- enable_stream_desktop_notifications: Optional[bool] = REQ(
- json_validator=check_bool, default=None
- ),
- enable_stream_email_notifications: Optional[bool] = REQ(
- json_validator=check_bool, default=None
- ),
- enable_stream_push_notifications: Optional[bool] = REQ(json_validator=check_bool, default=None),
- enable_stream_audible_notifications: Optional[bool] = REQ(
- json_validator=check_bool, default=None
- ),
- wildcard_mentions_notify: Optional[bool] = REQ(json_validator=check_bool, default=None),
- enable_followed_topic_desktop_notifications: Optional[bool] = REQ(
+ enable_drafts_synchronization: bool | None = REQ(json_validator=check_bool, default=None),
+ enable_stream_desktop_notifications: bool | None = REQ(json_validator=check_bool, default=None),
+ enable_stream_email_notifications: bool | None = REQ(json_validator=check_bool, default=None),
+ enable_stream_push_notifications: bool | None = REQ(json_validator=check_bool, default=None),
+ enable_stream_audible_notifications: bool | None = REQ(json_validator=check_bool, default=None),
+ wildcard_mentions_notify: bool | None = REQ(json_validator=check_bool, default=None),
+ enable_followed_topic_desktop_notifications: bool | None = REQ(
json_validator=check_bool, default=None
),
- enable_followed_topic_email_notifications: Optional[bool] = REQ(
+ enable_followed_topic_email_notifications: bool | None = REQ(
json_validator=check_bool, default=None
),
- enable_followed_topic_push_notifications: Optional[bool] = REQ(
+ enable_followed_topic_push_notifications: bool | None = REQ(
json_validator=check_bool, default=None
),
- enable_followed_topic_audible_notifications: Optional[bool] = REQ(
+ enable_followed_topic_audible_notifications: bool | None = REQ(
json_validator=check_bool, default=None
),
- enable_followed_topic_wildcard_mentions_notify: Optional[bool] = REQ(
+ enable_followed_topic_wildcard_mentions_notify: bool | None = REQ(
json_validator=check_bool, default=None
),
- notification_sound: Optional[str] = REQ(default=None),
- enable_desktop_notifications: Optional[bool] = REQ(json_validator=check_bool, default=None),
- enable_sounds: Optional[bool] = REQ(json_validator=check_bool, default=None),
- enable_offline_email_notifications: Optional[bool] = REQ(
+ notification_sound: str | None = REQ(default=None),
+ enable_desktop_notifications: bool | None = REQ(json_validator=check_bool, default=None),
+ enable_sounds: bool | None = REQ(json_validator=check_bool, default=None),
+ enable_offline_email_notifications: bool | None = REQ(json_validator=check_bool, default=None),
+ enable_offline_push_notifications: bool | None = REQ(json_validator=check_bool, default=None),
+ enable_online_push_notifications: bool | None = REQ(json_validator=check_bool, default=None),
+ enable_digest_emails: bool | None = REQ(json_validator=check_bool, default=None),
+ enable_login_emails: bool | None = REQ(json_validator=check_bool, default=None),
+ enable_marketing_emails: bool | None = REQ(json_validator=check_bool, default=None),
+ message_content_in_email_notifications: bool | None = REQ(
json_validator=check_bool, default=None
),
- enable_offline_push_notifications: Optional[bool] = REQ(
- json_validator=check_bool, default=None
- ),
- enable_online_push_notifications: Optional[bool] = REQ(json_validator=check_bool, default=None),
- enable_digest_emails: Optional[bool] = REQ(json_validator=check_bool, default=None),
- enable_login_emails: Optional[bool] = REQ(json_validator=check_bool, default=None),
- enable_marketing_emails: Optional[bool] = REQ(json_validator=check_bool, default=None),
- message_content_in_email_notifications: Optional[bool] = REQ(
- json_validator=check_bool, default=None
- ),
- pm_content_in_desktop_notifications: Optional[bool] = REQ(
- json_validator=check_bool, default=None
- ),
- desktop_icon_count_display: Optional[int] = REQ(
+ pm_content_in_desktop_notifications: bool | None = REQ(json_validator=check_bool, default=None),
+ desktop_icon_count_display: int | None = REQ(
json_validator=check_int_in(UserProfile.DESKTOP_ICON_COUNT_DISPLAY_CHOICES), default=None
),
- realm_name_in_email_notifications_policy: Optional[int] = REQ(
+ realm_name_in_email_notifications_policy: int | None = REQ(
json_validator=check_int_in(UserProfile.REALM_NAME_IN_EMAIL_NOTIFICATIONS_POLICY_CHOICES),
default=None,
),
- automatically_follow_topics_policy: Optional[int] = REQ(
+ automatically_follow_topics_policy: int | None = REQ(
json_validator=check_int_in(UserProfile.AUTOMATICALLY_CHANGE_VISIBILITY_POLICY_CHOICES),
default=None,
),
- automatically_unmute_topics_in_muted_streams_policy: Optional[int] = REQ(
+ automatically_unmute_topics_in_muted_streams_policy: int | None = REQ(
json_validator=check_int_in(UserProfile.AUTOMATICALLY_CHANGE_VISIBILITY_POLICY_CHOICES),
default=None,
),
- automatically_follow_topics_where_mentioned: Optional[bool] = REQ(
- json_validator=check_bool, default=None
- ),
- presence_enabled: Optional[bool] = REQ(json_validator=check_bool, default=None),
- enter_sends: Optional[bool] = REQ(json_validator=check_bool, default=None),
- send_private_typing_notifications: Optional[bool] = REQ(
+ automatically_follow_topics_where_mentioned: bool | None = REQ(
json_validator=check_bool, default=None
),
- send_stream_typing_notifications: Optional[bool] = REQ(json_validator=check_bool, default=None),
- send_read_receipts: Optional[bool] = REQ(json_validator=check_bool, default=None),
- user_list_style: Optional[int] = REQ(
+ presence_enabled: bool | None = REQ(json_validator=check_bool, default=None),
+ enter_sends: bool | None = REQ(json_validator=check_bool, default=None),
+ send_private_typing_notifications: bool | None = REQ(json_validator=check_bool, default=None),
+ send_stream_typing_notifications: bool | None = REQ(json_validator=check_bool, default=None),
+ send_read_receipts: bool | None = REQ(json_validator=check_bool, default=None),
+ user_list_style: int | None = REQ(
json_validator=check_int_in(UserProfile.USER_LIST_STYLE_CHOICES), default=None
),
- email_address_visibility: Optional[int] = REQ(
+ email_address_visibility: int | None = REQ(
json_validator=check_int_in(UserProfile.EMAIL_ADDRESS_VISIBILITY_TYPES), default=None
),
- web_navigate_to_sent_message: Optional[bool] = REQ(json_validator=check_bool, default=None),
+ web_navigate_to_sent_message: bool | None = REQ(json_validator=check_bool, default=None),
) -> HttpResponse:
if (
default_language is not None
diff --git a/zerver/views/user_topics.py b/zerver/views/user_topics.py
index d900702a72f..9ce044e2eb8 100644
--- a/zerver/views/user_topics.py
+++ b/zerver/views/user_topics.py
@@ -1,5 +1,4 @@
from datetime import datetime
-from typing import Optional
from django.http import HttpRequest, HttpResponse
from django.utils.timezone import now as timezone_now
@@ -24,8 +23,8 @@ from zerver.models.constants import MAX_TOPIC_NAME_LENGTH
def mute_topic(
user_profile: UserProfile,
- stream_id: Optional[int],
- stream_name: Optional[str],
+ stream_id: int | None,
+ stream_name: str | None,
topic_name: str,
date_muted: datetime,
) -> None:
@@ -46,8 +45,8 @@ def mute_topic(
def unmute_topic(
user_profile: UserProfile,
- stream_id: Optional[int],
- stream_name: Optional[str],
+ stream_id: int | None,
+ stream_name: str | None,
topic_name: str,
) -> None:
error = _("Topic is not muted")
@@ -68,8 +67,8 @@ def update_muted_topic(
request: HttpRequest,
user_profile: UserProfile,
*,
- stream_id: Optional[Json[int]] = None,
- stream: Optional[str] = None,
+ stream_id: Json[int] | None = None,
+ stream: str | None = None,
topic: Annotated[str, StringConstraints(max_length=MAX_TOPIC_NAME_LENGTH)],
op: Literal["add", "remove"],
) -> HttpResponse:
diff --git a/zerver/views/users.py b/zerver/views/users.py
index 91cf0c33029..815dfd18b92 100644
--- a/zerver/views/users.py
+++ b/zerver/views/users.py
@@ -1,5 +1,5 @@
from email.headerregistry import Address
-from typing import Any, Mapping, Optional, TypeAlias, Union
+from typing import Any, Mapping, TypeAlias
from django.conf import settings
from django.contrib.auth.models import AnonymousUser
@@ -118,9 +118,8 @@ def deactivate_user_backend(
user_profile: UserProfile,
*,
user_id: PathOnly[int],
- deactivation_notification_comment: Optional[
- Annotated[str, StringConstraints(max_length=2000)]
- ] = None,
+ deactivation_notification_comment: Annotated[str, StringConstraints(max_length=2000)]
+ | None = None,
) -> HttpResponse:
target = access_user_by_id(user_profile, user_id, for_admin=True)
if target.is_realm_owner and not user_profile.is_realm_owner:
@@ -161,7 +160,7 @@ def _deactivate_user_profile_backend(
user_profile: UserProfile,
target: UserProfile,
*,
- deactivation_notification_comment: Optional[str],
+ deactivation_notification_comment: str | None,
) -> HttpResponse:
do_deactivate_user(target, acting_user=user_profile)
@@ -197,7 +196,7 @@ def reactivate_user_backend(
class ProfileDataElement(BaseModel):
id: int
- value: Optional[Union[str, list[int]]]
+ value: str | list[int] | None
@typed_endpoint
@@ -206,9 +205,9 @@ def update_user_backend(
user_profile: UserProfile,
*,
user_id: PathOnly[int],
- full_name: Optional[str] = None,
- role: Optional[Json[RoleParamType]] = None,
- profile_data: Optional[Json[list[ProfileDataElement]]] = None,
+ full_name: str | None = None,
+ role: Json[RoleParamType] | None = None,
+ profile_data: Json[list[ProfileDataElement]] | None = None,
) -> HttpResponse:
target = access_user_by_id(
user_profile, user_id, allow_deactivated=True, allow_bots=True, for_admin=True
@@ -258,7 +257,7 @@ def update_user_backend(
def avatar(
request: HttpRequest,
- maybe_user_profile: Union[UserProfile, AnonymousUser],
+ maybe_user_profile: UserProfile | AnonymousUser,
email_or_id: str,
medium: bool = False,
) -> HttpResponse:
@@ -297,7 +296,7 @@ def avatar(
int(email_or_id), realm
)
- url: Optional[str] = None
+ url: str | None = None
if maybe_user_profile.is_authenticated and not check_can_access_user(
avatar_user_profile, maybe_user_profile
):
@@ -319,12 +318,12 @@ def avatar(
def avatar_medium(
- request: HttpRequest, maybe_user_profile: Union[UserProfile, AnonymousUser], email_or_id: str
+ request: HttpRequest, maybe_user_profile: UserProfile | AnonymousUser, email_or_id: str
) -> HttpResponse:
return avatar(request, maybe_user_profile, email_or_id, medium=True)
-def get_stream_name(stream: Optional[Stream]) -> Optional[str]:
+def get_stream_name(stream: Stream | None) -> str | None:
if stream:
return stream.name
return None
@@ -337,15 +336,15 @@ def patch_bot_backend(
user_profile: UserProfile,
*,
bot_id: PathOnly[int],
- full_name: Optional[str] = None,
- role: Optional[Json[RoleParamType]] = None,
- bot_owner_id: Optional[Json[int]] = None,
- config_data: Optional[Json[dict[str, str]]] = None,
- service_payload_url: Optional[Json[Annotated[str, AfterValidator(check_url)]]] = None,
+ full_name: str | None = None,
+ role: Json[RoleParamType] | None = None,
+ bot_owner_id: Json[int] | None = None,
+ config_data: Json[dict[str, str]] | None = None,
+ service_payload_url: Json[Annotated[str, AfterValidator(check_url)]] | None = None,
service_interface: Json[int] = 1,
- default_sending_stream: Optional[str] = None,
- default_events_register_stream: Optional[str] = None,
- default_all_public_streams: Optional[Json[bool]] = None,
+ default_sending_stream: str | None = None,
+ default_events_register_stream: str | None = None,
+ default_all_public_streams: Json[bool] | None = None,
) -> HttpResponse:
bot = access_bot_by_id(user_profile, bot_id)
@@ -377,7 +376,7 @@ def patch_bot_backend(
if default_sending_stream is not None:
if default_sending_stream == "":
- stream: Optional[Stream] = None
+ stream: Stream | None = None
else:
(stream, sub) = access_stream_by_name(user_profile, default_sending_stream)
do_change_default_sending_stream(bot, stream, acting_user=user_profile)
@@ -455,16 +454,16 @@ def add_bot_backend(
short_name_raw: Annotated[str, ApiParamConfig("short_name")],
bot_type: Json[int] = UserProfile.DEFAULT_BOT,
payload_url: Json[Annotated[str, AfterValidator(check_url)]] = "",
- service_name: Optional[str] = None,
- config_data: Optional[Json[Mapping[str, str]]] = None,
+ service_name: str | None = None,
+ config_data: Json[Mapping[str, str]] | None = None,
interface_type: Json[int] = Service.GENERIC,
default_sending_stream_name: Annotated[
- Optional[str], ApiParamConfig("default_sending_stream")
+ str | None, ApiParamConfig("default_sending_stream")
] = None,
default_events_register_stream_name: Annotated[
- Optional[str], ApiParamConfig("default_events_register_stream")
+ str | None, ApiParamConfig("default_events_register_stream")
] = None,
- default_all_public_streams: Optional[Json[bool]] = None,
+ default_all_public_streams: Json[bool] | None = None,
) -> HttpResponse:
if config_data is None:
config_data = {}
@@ -622,7 +621,7 @@ def get_user_data(
user_profile: UserProfile,
include_custom_profile_fields: bool,
client_gravatar: bool,
- target_user: Optional[UserProfile] = None,
+ target_user: UserProfile | None = None,
) -> dict[str, Any]:
"""
The client_gravatar field here is set to True by default assuming that clients
@@ -653,7 +652,7 @@ def get_user_data(
def get_members_backend(
request: HttpRequest,
user_profile: UserProfile,
- user_id: Optional[int] = None,
+ user_id: int | None = None,
*,
include_custom_profile_fields: Json[bool] = False,
client_gravatar: Json[bool] = True,
diff --git a/zerver/views/zephyr.py b/zerver/views/zephyr.py
index 40d8a1a7034..794f941a0ac 100644
--- a/zerver/views/zephyr.py
+++ b/zerver/views/zephyr.py
@@ -4,7 +4,6 @@ import re
import shlex
import subprocess
from email.headerregistry import Address
-from typing import Optional
import orjson
from django.conf import settings
@@ -30,7 +29,7 @@ kerberos_alter_egos = {
@authenticated_json_view
@typed_endpoint
def webathena_kerberos_login(
- request: HttpRequest, user_profile: UserProfile, *, cred: Optional[str] = None
+ request: HttpRequest, user_profile: UserProfile, *, cred: str | None = None
) -> HttpResponse:
if cred is None:
raise JsonableError(_("Could not find Kerberos credential"))
diff --git a/zerver/webhooks/azuredevops/view.py b/zerver/webhooks/azuredevops/view.py
index 920a03fd1a3..caeb658dcf0 100644
--- a/zerver/webhooks/azuredevops/view.py
+++ b/zerver/webhooks/azuredevops/view.py
@@ -1,4 +1,4 @@
-from typing import Callable, Optional
+from typing import Callable
from django.http import HttpRequest, HttpResponse
@@ -139,7 +139,7 @@ def get_topic_based_on_event(payload: WildValue, event: str) -> str:
return get_code_repository_name(payload) # nocoverage
-def get_event_name(payload: WildValue, branches: Optional[str]) -> Optional[str]:
+def get_event_name(payload: WildValue, branches: str | None) -> str | None:
event_name = payload["eventType"].tame(check_string)
if event_name == "git.push" and branches is not None:
branch = get_code_push_branch_name(payload)
@@ -175,7 +175,7 @@ def api_azuredevops_webhook(
user_profile: UserProfile,
*,
payload: JsonBodyPayload[WildValue],
- branches: Optional[str] = None,
+ branches: str | None = None,
) -> HttpResponse:
event = get_event_name(payload, branches)
if event is None:
diff --git a/zerver/webhooks/beanstalk/view.py b/zerver/webhooks/beanstalk/view.py
index ee8dd8729a5..ac416dffbfe 100644
--- a/zerver/webhooks/beanstalk/view.py
+++ b/zerver/webhooks/beanstalk/view.py
@@ -1,6 +1,5 @@
# Webhooks for external integrations.
import re
-from typing import Optional
from django.http import HttpRequest, HttpResponse
from pydantic import Json
@@ -23,8 +22,8 @@ def build_message_from_gitlog(
after: str,
url: str,
pusher: str,
- forced: Optional[str] = None,
- created: Optional[str] = None,
+ forced: str | None = None,
+ created: str | None = None,
deleted: bool = False,
) -> tuple[str, str]:
short_ref = re.sub(r"^refs/heads/", "", ref)
@@ -60,7 +59,7 @@ def api_beanstalk_webhook(
user_profile: UserProfile,
*,
payload: Json[WildValue],
- branches: Optional[str] = None,
+ branches: str | None = None,
) -> HttpResponse:
# Beanstalk supports both SVN and Git repositories
# We distinguish between the two by checking for a
diff --git a/zerver/webhooks/bitbucket/view.py b/zerver/webhooks/bitbucket/view.py
index 05ddd47038a..96e3f53a2f6 100644
--- a/zerver/webhooks/bitbucket/view.py
+++ b/zerver/webhooks/bitbucket/view.py
@@ -1,5 +1,3 @@
-from typing import Optional
-
from django.http import HttpRequest, HttpResponse
from zerver.decorator import authenticated_rest_api_view
@@ -18,7 +16,7 @@ def api_bitbucket_webhook(
user_profile: UserProfile,
*,
payload: JsonBodyPayload[WildValue],
- branches: Optional[str] = None,
+ branches: str | None = None,
) -> HttpResponse:
repository = payload["repository"]
diff --git a/zerver/webhooks/bitbucket2/view.py b/zerver/webhooks/bitbucket2/view.py
index 73ff7016b19..e288e10bf05 100644
--- a/zerver/webhooks/bitbucket2/view.py
+++ b/zerver/webhooks/bitbucket2/view.py
@@ -1,7 +1,7 @@
# Webhooks for external integrations.
import re
import string
-from typing import Optional, Protocol
+from typing import Protocol
from django.http import HttpRequest, HttpResponse
@@ -83,7 +83,7 @@ def api_bitbucket2_webhook(
user_profile: UserProfile,
*,
payload: JsonBodyPayload[WildValue],
- branches: Optional[str] = None,
+ branches: str | None = None,
user_specified_topic: OptionalUserSpecifiedTopicStr = None,
) -> HttpResponse:
type = get_type(request, payload)
@@ -119,7 +119,7 @@ def api_bitbucket2_webhook(
def get_topic_for_branch_specified_events(
- payload: WildValue, branch_name: Optional[str] = None
+ payload: WildValue, branch_name: str | None = None
) -> str:
return TOPIC_WITH_BRANCH_TEMPLATE.format(
repo=get_repository_name(payload["repository"]),
@@ -525,7 +525,7 @@ def get_actor_info(request: HttpRequest, payload: WildValue) -> str:
return get_user_info(request, actor)
-def get_branch_name_for_push_event(payload: WildValue) -> Optional[str]:
+def get_branch_name_for_push_event(payload: WildValue) -> str | None:
change = payload["push"]["changes"][-1]
potential_tag = (change["new"] or change["old"])["type"].tame(check_string)
if potential_tag == "tag":
diff --git a/zerver/webhooks/bitbucket3/view.py b/zerver/webhooks/bitbucket3/view.py
index cd7204bc18b..62f8b731fe5 100644
--- a/zerver/webhooks/bitbucket3/view.py
+++ b/zerver/webhooks/bitbucket3/view.py
@@ -1,5 +1,5 @@
import string
-from typing import Optional, Protocol
+from typing import Protocol
from django.http import HttpRequest, HttpResponse
@@ -72,8 +72,8 @@ def get_user_name(payload: WildValue) -> str:
def ping_handler(
payload: WildValue,
- branches: Optional[str],
- include_title: Optional[str],
+ branches: str | None,
+ include_title: str | None,
) -> list[dict[str, str]]:
if include_title:
topic_name = include_title
@@ -86,8 +86,8 @@ def ping_handler(
def repo_comment_handler(
action: str,
payload: WildValue,
- branches: Optional[str],
- include_title: Optional[str],
+ branches: str | None,
+ include_title: str | None,
) -> list[dict[str, str]]:
repo_name = payload["repository"]["name"].tame(check_string)
topic_name = BITBUCKET_TOPIC_TEMPLATE.format(repository_name=repo_name)
@@ -111,8 +111,8 @@ def repo_comment_handler(
def repo_forked_handler(
payload: WildValue,
- branches: Optional[str],
- include_title: Optional[str],
+ branches: str | None,
+ include_title: str | None,
) -> list[dict[str, str]]:
repo_name = payload["repository"]["origin"]["name"].tame(check_string)
topic_name = BITBUCKET_TOPIC_TEMPLATE.format(repository_name=repo_name)
@@ -127,8 +127,8 @@ def repo_forked_handler(
def repo_modified_handler(
payload: WildValue,
- branches: Optional[str],
- include_title: Optional[str],
+ branches: str | None,
+ include_title: str | None,
) -> list[dict[str, str]]:
topic_name_new = BITBUCKET_TOPIC_TEMPLATE.format(
repository_name=payload["new"]["name"].tame(check_string)
@@ -195,8 +195,8 @@ def repo_push_tag_data(payload: WildValue, change: WildValue) -> dict[str, str]:
def repo_push_handler(
payload: WildValue,
- branches: Optional[str],
- include_title: Optional[str],
+ branches: str | None,
+ include_title: str | None,
) -> list[dict[str, str]]:
data = []
for change in payload["changes"]:
@@ -216,7 +216,7 @@ def repo_push_handler(
return data
-def get_assignees_string(pr: WildValue) -> Optional[str]:
+def get_assignees_string(pr: WildValue) -> str | None:
reviewers = []
for reviewer in pr["reviewers"]:
name = reviewer["user"]["name"].tame(check_string)
@@ -235,7 +235,7 @@ def get_pr_topic(repo: str, type: str, id: int, title: str) -> str:
return TOPIC_WITH_PR_OR_ISSUE_INFO_TEMPLATE.format(repo=repo, type=type, id=id, title=title)
-def get_simple_pr_body(payload: WildValue, action: str, include_title: Optional[str]) -> str:
+def get_simple_pr_body(payload: WildValue, action: str, include_title: str | None) -> str:
pr = payload["pullRequest"]
return get_pull_request_event_message(
user_name=get_user_name(payload),
@@ -247,7 +247,7 @@ def get_simple_pr_body(payload: WildValue, action: str, include_title: Optional[
def get_pr_opened_or_modified_body(
- payload: WildValue, action: str, include_title: Optional[str]
+ payload: WildValue, action: str, include_title: str | None
) -> str:
pr = payload["pullRequest"]
description = pr.get("description").tame(check_none_or(check_string))
@@ -271,7 +271,7 @@ def get_pr_opened_or_modified_body(
)
-def get_pr_merged_body(payload: WildValue, action: str, include_title: Optional[str]) -> str:
+def get_pr_merged_body(payload: WildValue, action: str, include_title: str | None) -> str:
pr = payload["pullRequest"]
return get_pull_request_event_message(
user_name=get_user_name(payload),
@@ -284,7 +284,7 @@ def get_pr_merged_body(payload: WildValue, action: str, include_title: Optional[
)
-def get_pr_needs_work_body(payload: WildValue, include_title: Optional[str]) -> str:
+def get_pr_needs_work_body(payload: WildValue, include_title: str | None) -> str:
pr = payload["pullRequest"]
if not include_title:
return PULL_REQUEST_MARKED_AS_NEEDS_WORK_TEMPLATE.format(
@@ -300,7 +300,7 @@ def get_pr_needs_work_body(payload: WildValue, include_title: Optional[str]) ->
)
-def get_pr_reassigned_body(payload: WildValue, include_title: Optional[str]) -> str:
+def get_pr_reassigned_body(payload: WildValue, include_title: str | None) -> str:
pr = payload["pullRequest"]
assignees_string = get_assignees_string(pr)
if not assignees_string:
@@ -338,8 +338,8 @@ def get_pr_reassigned_body(payload: WildValue, include_title: Optional[str]) ->
def pr_handler(
action: str,
payload: WildValue,
- branches: Optional[str],
- include_title: Optional[str],
+ branches: str | None,
+ include_title: str | None,
) -> list[dict[str, str]]:
pr = payload["pullRequest"]
topic_name = get_pr_topic(
@@ -365,8 +365,8 @@ def pr_handler(
def pr_comment_handler(
action: str,
payload: WildValue,
- branches: Optional[str],
- include_title: Optional[str],
+ branches: str | None,
+ include_title: str | None,
) -> list[dict[str, str]]:
pr = payload["pullRequest"]
topic_name = get_pr_topic(
@@ -392,7 +392,7 @@ def pr_comment_handler(
class EventHandler(Protocol):
def __call__(
- self, payload: WildValue, branches: Optional[str], include_title: Optional[str]
+ self, payload: WildValue, branches: str | None, include_title: str | None
) -> list[dict[str, str]]: ...
@@ -428,10 +428,10 @@ def api_bitbucket3_webhook(
user_profile: UserProfile,
*,
payload: JsonBodyPayload[WildValue],
- branches: Optional[str] = None,
+ branches: str | None = None,
user_specified_topic: OptionalUserSpecifiedTopicStr = None,
) -> HttpResponse:
- eventkey: Optional[str]
+ eventkey: str | None
if "eventKey" in payload:
eventkey = payload["eventKey"].tame(check_string)
else:
diff --git a/zerver/webhooks/clubhouse/view.py b/zerver/webhooks/clubhouse/view.py
index 25f99e99bed..f1c4dfd463f 100644
--- a/zerver/webhooks/clubhouse/view.py
+++ b/zerver/webhooks/clubhouse/view.py
@@ -1,4 +1,4 @@
-from typing import Callable, Iterable, Iterator, Optional
+from typing import Callable, Iterable, Iterator
from django.http import HttpRequest, HttpResponse
@@ -83,7 +83,7 @@ def get_action_with_primary_id(payload: WildValue) -> WildValue:
return action_with_primary_id
-def get_event(payload: WildValue, action: WildValue) -> Optional[str]:
+def get_event(payload: WildValue, action: WildValue) -> str | None:
event = "{}_{}".format(
action["entity_type"].tame(check_string), action["action"].tame(check_string)
)
@@ -129,7 +129,7 @@ def get_event(payload: WildValue, action: WildValue) -> Optional[str]:
def get_topic_function_based_on_type(
payload: WildValue, action: WildValue
-) -> Optional[Callable[[WildValue, WildValue], Optional[str]]]:
+) -> Callable[[WildValue, WildValue], str | None] | None:
entity_type = action["entity_type"].tame(check_string)
return EVENT_TOPIC_FUNCTION_MAPPER.get(entity_type)
@@ -299,7 +299,7 @@ def get_story_task_body(operation: str, payload: WildValue, action: WildValue) -
return STORY_TASK_TEMPLATE.format(**kwargs)
-def get_story_task_completed_body(payload: WildValue, action: WildValue) -> Optional[str]:
+def get_story_task_completed_body(payload: WildValue, action: WildValue) -> str | None:
kwargs = {
"task_description": action["description"].tame(check_string),
}
@@ -371,7 +371,7 @@ def get_story_update_estimate_body(payload: WildValue, action: WildValue) -> str
return STORY_ESTIMATE_TEMPLATE.format(**kwargs)
-def get_reference_by_id(payload: WildValue, ref_id: Optional[int]) -> Optional[WildValue]:
+def get_reference_by_id(payload: WildValue, ref_id: int | None) -> WildValue | None:
ref = None
for reference in payload["references"]:
if reference["id"].tame(check_string_or_int) == ref_id:
@@ -431,7 +431,7 @@ def get_story_create_github_entity_body(entity: str, payload: WildValue, action:
return template.format(**kwargs)
-def get_story_update_attachment_body(payload: WildValue, action: WildValue) -> Optional[str]:
+def get_story_update_attachment_body(payload: WildValue, action: WildValue) -> str | None:
kwargs = {
"name_template": STORY_NAME_TEMPLATE.format(
name=action["name"].tame(check_string),
@@ -475,7 +475,7 @@ def get_story_joined_label_list(payload: WildValue, label_ids_added: list[int])
return ", ".join(labels)
-def get_story_label_body(payload: WildValue, action: WildValue) -> Optional[str]:
+def get_story_label_body(payload: WildValue, action: WildValue) -> str | None:
kwargs = {
"name_template": STORY_NAME_TEMPLATE.format(
name=action["name"].tame(check_string),
@@ -543,7 +543,7 @@ def get_story_update_owner_body(payload: WildValue, action: WildValue) -> str:
return STORY_UPDATE_OWNER_TEMPLATE.format(**kwargs)
-def get_story_update_batch_body(payload: WildValue, action: WildValue) -> Optional[str]:
+def get_story_update_batch_body(payload: WildValue, action: WildValue) -> str | None:
# When the user selects one or more stories with the checkbox, they can perform
# a batch update on multiple stories while changing multiple attributes at the
# same time.
@@ -660,7 +660,7 @@ def get_story_update_batch_body(payload: WildValue, action: WildValue) -> Option
return STORY_UPDATE_BATCH_TEMPLATE.format(**kwargs)
-def get_entity_name(entity: str, payload: WildValue, action: WildValue) -> Optional[str]:
+def get_entity_name(entity: str, payload: WildValue, action: WildValue) -> str | None:
name = action["name"].tame(check_string) if "name" in action else None
if name is None or action["entity_type"] == "branch":
@@ -701,7 +701,7 @@ def send_channel_messages_for_actions(
check_send_webhook_message(request, user_profile, topic_name, body, event)
-EVENT_BODY_FUNCTION_MAPPER: dict[str, Callable[[WildValue, WildValue], Optional[str]]] = {
+EVENT_BODY_FUNCTION_MAPPER: dict[str, Callable[[WildValue, WildValue], str | None]] = {
"story_update_archived": partial(get_update_archived_body, "story"),
"epic_update_archived": partial(get_update_archived_body, "epic"),
"story_create": get_story_create_body,
@@ -734,7 +734,7 @@ EVENT_BODY_FUNCTION_MAPPER: dict[str, Callable[[WildValue, WildValue], Optional[
ALL_EVENT_TYPES = list(EVENT_BODY_FUNCTION_MAPPER.keys())
-EVENT_TOPIC_FUNCTION_MAPPER: dict[str, Callable[[WildValue, WildValue], Optional[str]]] = {
+EVENT_TOPIC_FUNCTION_MAPPER: dict[str, Callable[[WildValue, WildValue], str | None]] = {
"story": partial(get_entity_name, "story"),
"pull-request": partial(get_entity_name, "story"),
"branch": partial(get_entity_name, "story"),
diff --git a/zerver/webhooks/dropbox/view.py b/zerver/webhooks/dropbox/view.py
index 9658fca7154..13ca5102286 100644
--- a/zerver/webhooks/dropbox/view.py
+++ b/zerver/webhooks/dropbox/view.py
@@ -1,5 +1,3 @@
-from typing import Optional
-
from django.http import HttpRequest, HttpResponse
from zerver.decorator import webhook_view
@@ -16,7 +14,7 @@ def api_dropbox_webhook(
request: HttpRequest,
user_profile: UserProfile,
*,
- challenge: Optional[str] = None,
+ challenge: str | None = None,
) -> HttpResponse:
if request.method == "POST":
topic_name = "Dropbox"
diff --git a/zerver/webhooks/gitea/view.py b/zerver/webhooks/gitea/view.py
index 55e5f9c1ba0..43c0b775b3f 100644
--- a/zerver/webhooks/gitea/view.py
+++ b/zerver/webhooks/gitea/view.py
@@ -1,5 +1,4 @@
# vim:fenc=utf-8
-from typing import Optional
from django.http import HttpRequest, HttpResponse
@@ -57,7 +56,7 @@ def api_gitea_webhook(
user_profile: UserProfile,
*,
payload: JsonBodyPayload[WildValue],
- branches: Optional[str] = None,
+ branches: str | None = None,
user_specified_topic: OptionalUserSpecifiedTopicStr = None,
) -> HttpResponse:
return gogs_webhook_main(
diff --git a/zerver/webhooks/github/view.py b/zerver/webhooks/github/view.py
index 680a89a91db..3112cc24942 100644
--- a/zerver/webhooks/github/view.py
+++ b/zerver/webhooks/github/view.py
@@ -1,6 +1,6 @@
import re
from datetime import datetime, timezone
-from typing import Callable, Optional
+from typing import Callable
from django.http import HttpRequest, HttpResponse
@@ -908,7 +908,7 @@ def api_github_webhook(
user_profile: UserProfile,
*,
payload: JsonBodyPayload[WildValue],
- branches: Optional[str] = None,
+ branches: str | None = None,
user_specified_topic: OptionalUserSpecifiedTopicStr = None,
) -> HttpResponse:
"""
@@ -943,8 +943,8 @@ def api_github_webhook(
def get_zulip_event_name(
header_event: str,
payload: WildValue,
- branches: Optional[str],
-) -> Optional[str]:
+ branches: str | None,
+) -> str | None:
"""
Usually, we return an event name that is a key in EVENT_FUNCTION_MAPPER.
diff --git a/zerver/webhooks/gitlab/view.py b/zerver/webhooks/gitlab/view.py
index 1bc9ac47dcb..45123030b68 100644
--- a/zerver/webhooks/gitlab/view.py
+++ b/zerver/webhooks/gitlab/view.py
@@ -1,5 +1,5 @@
import re
-from typing import Optional, Protocol, Union
+from typing import Protocol
from django.http import HttpRequest, HttpResponse
from pydantic import Json
@@ -176,7 +176,7 @@ def get_merge_request_open_or_updated_body(
)
-def get_assignees(payload: WildValue) -> Union[list[WildValue], WildValue]:
+def get_assignees(payload: WildValue) -> list[WildValue] | WildValue:
assignee_details = payload.get("assignees")
if not assignee_details:
single_assignee_details = payload.get("assignee")
@@ -189,7 +189,7 @@ def get_assignees(payload: WildValue) -> Union[list[WildValue], WildValue]:
def replace_assignees_username_with_name(
- assignees: Union[list[WildValue], WildValue],
+ assignees: list[WildValue] | WildValue,
) -> list[dict[str, str]]:
"""Replace the username of each assignee with their (full) name.
@@ -423,7 +423,7 @@ def api_gitlab_webhook(
user_profile: UserProfile,
*,
payload: JsonBodyPayload[WildValue],
- branches: Optional[str] = None,
+ branches: str | None = None,
use_merge_request_title: Json[bool] = True,
user_specified_topic: OptionalUserSpecifiedTopicStr = None,
) -> HttpResponse:
@@ -508,7 +508,7 @@ def get_topic_based_on_event(event: str, payload: WildValue, use_merge_request_t
return get_repo_name(payload)
-def get_event(request: HttpRequest, payload: WildValue, branches: Optional[str]) -> Optional[str]:
+def get_event(request: HttpRequest, payload: WildValue, branches: str | None) -> str | None:
event = validate_extract_webhook_http_header(request, "X-GitLab-Event", "GitLab")
if event == "System Hook":
# Convert the event name to a GitLab event title
diff --git a/zerver/webhooks/gogs/view.py b/zerver/webhooks/gogs/view.py
index 2e074059b8d..eecfcd3e2ed 100644
--- a/zerver/webhooks/gogs/view.py
+++ b/zerver/webhooks/gogs/view.py
@@ -1,5 +1,5 @@
# vim:fenc=utf-8
-from typing import Optional, Protocol
+from typing import Protocol
from django.http import HttpRequest, HttpResponse
@@ -157,7 +157,7 @@ def api_gogs_webhook(
user_profile: UserProfile,
*,
payload: JsonBodyPayload[WildValue],
- branches: Optional[str] = None,
+ branches: str | None = None,
user_specified_topic: OptionalUserSpecifiedTopicStr = None,
) -> HttpResponse:
return gogs_webhook_main(
@@ -183,8 +183,8 @@ def gogs_webhook_main(
request: HttpRequest,
user_profile: UserProfile,
payload: WildValue,
- branches: Optional[str],
- user_specified_topic: Optional[str],
+ branches: str | None,
+ user_specified_topic: str | None,
) -> HttpResponse:
repo = payload["repository"]["name"].tame(check_string)
event = validate_extract_webhook_http_header(request, http_header_name, integration_name)
diff --git a/zerver/webhooks/groove/view.py b/zerver/webhooks/groove/view.py
index 62e1323d3c8..2b9dd7d768f 100644
--- a/zerver/webhooks/groove/view.py
+++ b/zerver/webhooks/groove/view.py
@@ -1,5 +1,5 @@
# Webhooks for external integrations.
-from typing import Callable, Optional
+from typing import Callable
from django.http import HttpRequest, HttpResponse
@@ -45,7 +45,7 @@ def ticket_started_body(payload: WildValue) -> str:
)
-def ticket_assigned_body(payload: WildValue) -> Optional[str]:
+def ticket_assigned_body(payload: WildValue) -> str | None:
state = payload["state"].tame(check_string)
kwargs = {
"state": "open" if state == "opened" else state,
@@ -90,7 +90,7 @@ def replied_body(actor: str, action: str, payload: WildValue) -> str:
return body
-EVENTS_FUNCTION_MAPPER: dict[str, Callable[[WildValue], Optional[str]]] = {
+EVENTS_FUNCTION_MAPPER: dict[str, Callable[[WildValue], str | None]] = {
"ticket_started": ticket_started_body,
"ticket_assigned": ticket_assigned_body,
"agent_replied": partial(replied_body, "agent", "replied to"),
diff --git a/zerver/webhooks/harbor/view.py b/zerver/webhooks/harbor/view.py
index 1817d21f29f..9095d6a019a 100644
--- a/zerver/webhooks/harbor/view.py
+++ b/zerver/webhooks/harbor/view.py
@@ -1,5 +1,4 @@
# Webhooks for external integrations.
-from typing import Optional
from django.db.models import Q
from django.http import HttpRequest, HttpResponse
@@ -22,7 +21,7 @@ IGNORED_EVENTS = [
]
-def guess_zulip_user_from_harbor(harbor_username: str, realm: Realm) -> Optional[UserProfile]:
+def guess_zulip_user_from_harbor(harbor_username: str, realm: Realm) -> UserProfile | None:
try:
# Try to find a matching user in Zulip
# We search a user's full name, short name,
diff --git a/zerver/webhooks/jira/view.py b/zerver/webhooks/jira/view.py
index 28d5feee50e..d37dd3f5dfc 100644
--- a/zerver/webhooks/jira/view.py
+++ b/zerver/webhooks/jira/view.py
@@ -1,7 +1,7 @@
# Webhooks for external integrations.
import re
import string
-from typing import Callable, Optional
+from typing import Callable
from django.core.exceptions import ValidationError
from django.db.models import Q
@@ -29,7 +29,7 @@ IGNORED_EVENTS = [
]
-def guess_zulip_user_from_jira(jira_username: str, realm: Realm) -> Optional[UserProfile]:
+def guess_zulip_user_from_jira(jira_username: str, realm: Realm) -> UserProfile | None:
try:
# Try to find a matching user in Zulip
# We search a user's full name, short name,
@@ -105,7 +105,7 @@ def get_in(payload: WildValue, keys: list[str], default: str = "") -> WildValue:
def get_issue_string(
- payload: WildValue, issue_id: Optional[str] = None, with_title: bool = False
+ payload: WildValue, issue_id: str | None = None, with_title: bool = False
) -> str:
# Guess the URL as it is not specified in the payload
# We assume that there is a /browse/BUG-### page
@@ -181,7 +181,7 @@ def get_sub_event_for_update_issue(payload: WildValue) -> str:
return sub_event
-def get_event_type(payload: WildValue) -> Optional[str]:
+def get_event_type(payload: WildValue) -> str | None:
event = payload.get("webhookEvent").tame(check_none_or(check_string))
if event is None and payload.get("transition"):
event = "jira:issue_updated"
@@ -189,7 +189,7 @@ def get_event_type(payload: WildValue) -> Optional[str]:
def add_change_info(
- content: str, field: Optional[str], from_field: Optional[str], to_field: Optional[str]
+ content: str, field: str | None, from_field: str | None, to_field: str | None
) -> str:
content += f"* Changed {field}"
if from_field:
@@ -339,7 +339,7 @@ def handle_comment_deleted_event(payload: WildValue, user_profile: UserProfile)
)
-JIRA_CONTENT_FUNCTION_MAPPER: dict[str, Optional[Callable[[WildValue, UserProfile], str]]] = {
+JIRA_CONTENT_FUNCTION_MAPPER: dict[str, Callable[[WildValue, UserProfile], str] | None] = {
"jira:issue_created": handle_created_issue_event,
"jira:issue_deleted": handle_deleted_issue_event,
"jira:issue_updated": handle_updated_issue_event,
diff --git a/zerver/webhooks/linear/view.py b/zerver/webhooks/linear/view.py
index c578e9bee40..e3b82b5b976 100644
--- a/zerver/webhooks/linear/view.py
+++ b/zerver/webhooks/linear/view.py
@@ -1,4 +1,4 @@
-from typing import Callable, Optional
+from typing import Callable
from django.http import HttpRequest, HttpResponse
@@ -133,7 +133,7 @@ def api_linear_webhook(
return json_success(request)
-def get_topic(user_specified_topic: Optional[str], event: str, payload: WildValue) -> str:
+def get_topic(user_specified_topic: str | None, event: str, payload: WildValue) -> str:
if user_specified_topic is not None:
return user_specified_topic
elif event == "comment":
@@ -149,7 +149,7 @@ def get_topic(user_specified_topic: Optional[str], event: str, payload: WildValu
raise UnsupportedWebhookEventTypeError(event)
-def get_event_type(payload: WildValue) -> Optional[str]:
+def get_event_type(payload: WildValue) -> str | None:
event_type = payload["type"].tame(check_string)
if event_type == "Issue":
diff --git a/zerver/webhooks/pagerduty/view.py b/zerver/webhooks/pagerduty/view.py
index 9f8f95f7f0d..8fd131ee9d8 100644
--- a/zerver/webhooks/pagerduty/view.py
+++ b/zerver/webhooks/pagerduty/view.py
@@ -1,5 +1,4 @@
from email.headerregistry import Address
-from typing import Union
from django.http import HttpRequest, HttpResponse
from typing_extensions import TypeAlias
@@ -12,7 +11,7 @@ from zerver.lib.validator import WildValue, check_int, check_none_or, check_stri
from zerver.lib.webhooks.common import check_send_webhook_message
from zerver.models import UserProfile
-FormatDictType: TypeAlias = dict[str, Union[str, int]]
+FormatDictType: TypeAlias = dict[str, str | int]
PAGER_DUTY_EVENT_NAMES = {
"incident.trigger": "triggered",
diff --git a/zerver/webhooks/patreon/view.py b/zerver/webhooks/patreon/view.py
index d61caffffa9..b433268c5a0 100644
--- a/zerver/webhooks/patreon/view.py
+++ b/zerver/webhooks/patreon/view.py
@@ -1,4 +1,4 @@
-from typing import Callable, Optional
+from typing import Callable
from django.http import HttpRequest, HttpResponse
@@ -28,7 +28,7 @@ def get_custom_http_headers_from_filename(http_header_key: str) -> Callable[[str
fixture_to_headers = get_custom_http_headers_from_filename("HTTP_X_PATREON_EVENT")
-def get_members_create_body(payload: WildValue) -> Optional[str]:
+def get_members_create_body(payload: WildValue) -> str | None:
last_charge_status = get_last_charge_status(payload)
patron_status = get_patron_status(payload)
# null values indicate the member has never pledged
@@ -40,7 +40,7 @@ def get_members_create_body(payload: WildValue) -> Optional[str]:
return None
-def get_members_update_body(payload: WildValue) -> Optional[str]:
+def get_members_update_body(payload: WildValue) -> str | None:
last_charge_status = get_last_charge_status(payload)
patron_status = get_patron_status(payload)
if last_charge_status in ("Paid", None) and patron_status in ("active_patron", "former_patron"):
@@ -52,7 +52,7 @@ def get_members_update_body(payload: WildValue) -> Optional[str]:
return None
-def get_members_delete_body(payload: WildValue) -> Optional[str]:
+def get_members_delete_body(payload: WildValue) -> str | None:
last_charge_status = get_last_charge_status(payload)
patron_status = get_patron_status(payload)
# null value indicates the member has never pledged
@@ -64,7 +64,7 @@ def get_members_delete_body(payload: WildValue) -> Optional[str]:
return None
-def get_members_pledge_create_body(payload: WildValue) -> Optional[str]:
+def get_members_pledge_create_body(payload: WildValue) -> str | None:
last_charge_status = get_last_charge_status(payload)
pledge_amount = get_pledge_amount(payload)
# The only successful charge status is "Paid". null if not yet charged.
@@ -79,7 +79,7 @@ def get_members_pledge_create_body(payload: WildValue) -> Optional[str]:
return None
-def get_members_pledge_update_body(payload: WildValue) -> Optional[str]:
+def get_members_pledge_update_body(payload: WildValue) -> str | None:
last_charge_status = get_last_charge_status(payload)
pledge_amount = get_pledge_amount(payload)
# The only successful charge status is "Paid". null if not yet charged.
@@ -93,7 +93,7 @@ def get_members_pledge_update_body(payload: WildValue) -> Optional[str]:
return None
-def get_members_pledge_delete_body(payload: WildValue) -> Optional[str]:
+def get_members_pledge_delete_body(payload: WildValue) -> str | None:
last_charge_status = get_last_charge_status(payload)
if last_charge_status in ("Paid", "Deleted", None):
template = "{user_name}'s pledge has been cancelled. :cross_mark:\nTotal number of patrons: {patron_count}"
@@ -104,11 +104,11 @@ def get_members_pledge_delete_body(payload: WildValue) -> Optional[str]:
return None
-def get_last_charge_status(payload: WildValue) -> Optional[str]:
+def get_last_charge_status(payload: WildValue) -> str | None:
return payload["data"]["attributes"]["last_charge_status"].tame(check_none_or(check_string))
-def get_patron_status(payload: WildValue) -> Optional[str]:
+def get_patron_status(payload: WildValue) -> str | None:
return payload["data"]["attributes"]["patron_status"].tame(check_none_or(check_string))
@@ -128,7 +128,7 @@ def get_pay_per_name(payload: WildValue) -> str:
return payload["included"][0]["attributes"]["pay_per_name"].tame(check_string)
-EVENT_FUNCTION_MAPPER: dict[str, Callable[[WildValue], Optional[str]]] = {
+EVENT_FUNCTION_MAPPER: dict[str, Callable[[WildValue], str | None]] = {
"members:create": get_members_create_body,
"members:update": get_members_update_body,
"members:delete": get_members_delete_body,
@@ -178,7 +178,7 @@ def api_patreon_webhook(
def get_zulip_event_name(
header_event: str,
payload: WildValue,
-) -> Optional[str]:
+) -> str | None:
"""
Usually, we return an event name that is a key in EVENT_FUNCTION_MAPPER.
We return None for an event that we know we don't want to handle.
diff --git a/zerver/webhooks/pivotal/view.py b/zerver/webhooks/pivotal/view.py
index e5fc94c74a0..8af5edcc2b9 100644
--- a/zerver/webhooks/pivotal/view.py
+++ b/zerver/webhooks/pivotal/view.py
@@ -1,7 +1,7 @@
"""Webhooks for external integrations."""
import re
-from typing import Any, Optional
+from typing import Any
import orjson
from defusedxml.ElementTree import fromstring as xml_fromstring
@@ -110,7 +110,7 @@ def api_pivotal_webhook_v5(request: HttpRequest, user_profile: UserProfile) -> t
content = ""
topic_name = f"#{story_id}: {story_name}"
- def extract_comment(change: dict[str, Any]) -> Optional[str]:
+ def extract_comment(change: dict[str, Any]) -> str | None:
if change.get("kind") == "comment":
return change.get("new_values", {}).get("text", None)
return None
diff --git a/zerver/webhooks/rhodecode/view.py b/zerver/webhooks/rhodecode/view.py
index 0cea8921b02..77e693bd41a 100644
--- a/zerver/webhooks/rhodecode/view.py
+++ b/zerver/webhooks/rhodecode/view.py
@@ -1,4 +1,4 @@
-from typing import Callable, Optional
+from typing import Callable
from django.core.exceptions import ValidationError
from django.http import HttpRequest, HttpResponse
@@ -45,7 +45,7 @@ def get_push_branch_name(payload: WildValue) -> str:
return payload["event"]["push"]["commits"][0]["raw_id"].tame(check_string).split("=>")[1]
-def get_event_name(payload: WildValue, branches: Optional[str]) -> Optional[str]:
+def get_event_name(payload: WildValue, branches: str | None) -> str | None:
event_name = payload["event"]["name"].tame(check_string)
if event_name == "repo-push" and branches is not None:
branch = get_push_branch_name(payload)
@@ -82,7 +82,7 @@ def api_rhodecode_webhook(
user_profile: UserProfile,
*,
payload: JsonBodyPayload[WildValue],
- branches: Optional[str] = None,
+ branches: str | None = None,
) -> HttpResponse:
event = get_event_name(payload, branches)
if event is None:
diff --git a/zerver/webhooks/semaphore/view.py b/zerver/webhooks/semaphore/view.py
index a0a5eeb6984..f221366f395 100644
--- a/zerver/webhooks/semaphore/view.py
+++ b/zerver/webhooks/semaphore/view.py
@@ -1,5 +1,4 @@
# Webhooks for external integrations.
-from typing import Optional
from urllib.parse import urlsplit
from django.http import HttpRequest, HttpResponse
@@ -161,7 +160,7 @@ def semaphore_classic(payload: WildValue) -> tuple[str, str, str, str]:
return content, project_name, branch_name, event
-def semaphore_2(payload: WildValue) -> tuple[str, str, Optional[str], str]:
+def semaphore_2(payload: WildValue) -> tuple[str, str, str | None, str]:
repo_url = payload["repository"]["url"].tame(check_string)
project_name = payload["project"]["name"].tame(check_string)
organization_name = payload["organization"]["name"].tame(check_string)
diff --git a/zerver/webhooks/sentry/view.py b/zerver/webhooks/sentry/view.py
index 10cd20887fa..c292f4d9e1c 100644
--- a/zerver/webhooks/sentry/view.py
+++ b/zerver/webhooks/sentry/view.py
@@ -1,6 +1,6 @@
import logging
from datetime import datetime, timezone
-from typing import Any, Optional
+from typing import Any
from urllib.parse import urljoin
from django.http import HttpRequest, HttpResponse
@@ -90,7 +90,7 @@ def is_sample_event(event: dict[str, Any]) -> bool:
return False
-def convert_lines_to_traceback_string(lines: Optional[list[str]]) -> str:
+def convert_lines_to_traceback_string(lines: list[str] | None) -> str:
traceback = ""
if lines is not None:
for line in lines:
@@ -243,7 +243,7 @@ def handle_deprecated_payload(payload: dict[str, Any]) -> tuple[str, str]:
return (topic_name, body)
-def transform_webhook_payload(payload: dict[str, Any]) -> Optional[dict[str, Any]]:
+def transform_webhook_payload(payload: dict[str, Any]) -> dict[str, Any] | None:
"""Attempt to use webhook payload for the notification.
When the integration is configured as a webhook, instead of being added as
diff --git a/zerver/webhooks/slack/view.py b/zerver/webhooks/slack/view.py
index 8d0c3a42b98..112b2fc1599 100644
--- a/zerver/webhooks/slack/view.py
+++ b/zerver/webhooks/slack/view.py
@@ -1,5 +1,3 @@
-from typing import Optional
-
from django.http import HttpRequest
from django.http.response import HttpResponse
from django.utils.translation import gettext as _
@@ -24,7 +22,7 @@ def api_slack_webhook(
user_name: str,
text: str,
channel_name: str,
- channels_map_to_topics: Optional[str] = None,
+ channels_map_to_topics: str | None = None,
) -> HttpResponse:
content = ZULIP_MESSAGE_TEMPLATE.format(message_sender=user_name, text=text)
topic_name = "Message from Slack"
diff --git a/zerver/webhooks/stripe/view.py b/zerver/webhooks/stripe/view.py
index cb086010eb3..0e809388575 100644
--- a/zerver/webhooks/stripe/view.py
+++ b/zerver/webhooks/stripe/view.py
@@ -1,6 +1,6 @@
# Webhooks for external integrations.
import time
-from typing import Optional, Sequence
+from typing import Sequence
from django.http import HttpRequest, HttpResponse
@@ -318,7 +318,7 @@ def amount_string(amount: int, currency: str) -> str:
def linkified_id(object_id: str, lower: bool = False) -> str:
- names_and_urls: dict[str, tuple[str, Optional[str]]] = {
+ names_and_urls: dict[str, tuple[str, str | None]] = {
# Core resources
"ch": ("Charge", "charges"),
"cus": ("Customer", "customers"),
diff --git a/zerver/webhooks/taiga/view.py b/zerver/webhooks/taiga/view.py
index 306bf7b6cae..ba8f2231ffa 100644
--- a/zerver/webhooks/taiga/view.py
+++ b/zerver/webhooks/taiga/view.py
@@ -7,8 +7,6 @@ value should always be in bold; otherwise the subject of US/task
should be in bold.
"""
-from typing import Optional, Union
-
from django.http import HttpRequest, HttpResponse
from typing_extensions import TypeAlias
@@ -19,7 +17,7 @@ from zerver.lib.validator import WildValue, check_bool, check_none_or, check_str
from zerver.lib.webhooks.common import check_send_webhook_message
from zerver.models import UserProfile
-EventType: TypeAlias = dict[str, Union[str, dict[str, Optional[Union[str, bool]]]]]
+EventType: TypeAlias = dict[str, str | dict[str, str | bool | None]]
ReturnType: TypeAlias = tuple[WildValue, WildValue]
@@ -204,10 +202,10 @@ def parse_create_or_delete(
}
-def parse_change_event(change_type: str, message: WildValue) -> Optional[EventType]:
+def parse_change_event(change_type: str, message: WildValue) -> EventType | None:
"""Parses change event."""
evt: EventType = {}
- values: dict[str, Optional[Union[str, bool]]] = {
+ values: dict[str, str | bool | None] = {
"user": get_owner_name(message),
"user_link": get_owner_link(message),
"subject": get_subject(message),
diff --git a/zerver/webhooks/teamcity/view.py b/zerver/webhooks/teamcity/view.py
index aea56f2fc05..6cdb2dd1950 100644
--- a/zerver/webhooks/teamcity/view.py
+++ b/zerver/webhooks/teamcity/view.py
@@ -1,6 +1,5 @@
# Webhooks for teamcity integration
import logging
-from typing import Optional
from django.db.models import Q
from django.http import HttpRequest, HttpResponse
@@ -28,7 +27,7 @@ need further help!
"""
-def guess_zulip_user_from_teamcity(teamcity_username: str, realm: Realm) -> Optional[UserProfile]:
+def guess_zulip_user_from_teamcity(teamcity_username: str, realm: Realm) -> UserProfile | None:
try:
# Try to find a matching user in Zulip
# We search a user's full name, short name,
@@ -43,7 +42,7 @@ def guess_zulip_user_from_teamcity(teamcity_username: str, realm: Realm) -> Opti
return None
-def get_teamcity_property_value(property_list: WildValue, name: str) -> Optional[str]:
+def get_teamcity_property_value(property_list: WildValue, name: str) -> str | None:
for property in property_list:
if property["name"].tame(check_string) == name:
return property["value"].tame(check_string)
diff --git a/zerver/webhooks/thinkst/view.py b/zerver/webhooks/thinkst/view.py
index 2518b9a0822..7cc81eb988f 100644
--- a/zerver/webhooks/thinkst/view.py
+++ b/zerver/webhooks/thinkst/view.py
@@ -1,5 +1,4 @@
# Webhooks for external integrations.
-from typing import Optional
from django.http import HttpRequest, HttpResponse
@@ -40,7 +39,7 @@ def canary_kind(message: WildValue) -> str:
return "canary"
-def source_ip_and_reverse_dns(message: WildValue) -> tuple[Optional[str], Optional[str]]:
+def source_ip_and_reverse_dns(message: WildValue) -> tuple[str | None, str | None]:
"""
Extract the source IP and reverse DNS information from a canary request.
"""
diff --git a/zerver/webhooks/transifex/view.py b/zerver/webhooks/transifex/view.py
index 7f1aaae497d..d0861e685a7 100644
--- a/zerver/webhooks/transifex/view.py
+++ b/zerver/webhooks/transifex/view.py
@@ -1,5 +1,4 @@
# Webhooks for external integrations.
-from typing import Optional
from django.http import HttpRequest, HttpResponse
from pydantic import Json
@@ -24,8 +23,8 @@ def api_transifex_webhook(
resource: str,
language: str,
event: str,
- translated: Optional[Json[int]] = None,
- reviewed: Optional[Json[int]] = None,
+ translated: Json[int] | None = None,
+ reviewed: Json[int] | None = None,
) -> HttpResponse:
topic_name = f"{project} in {language}"
if event == "translation_completed":
diff --git a/zerver/webhooks/trello/view/__init__.py b/zerver/webhooks/trello/view/__init__.py
index c80385a08c9..0df29e7b056 100644
--- a/zerver/webhooks/trello/view/__init__.py
+++ b/zerver/webhooks/trello/view/__init__.py
@@ -1,6 +1,4 @@
# Webhooks for external integrations.
-from typing import Optional
-
from django.http import HttpRequest, HttpResponse
from zerver.decorator import return_success_on_head_request, webhook_view
@@ -35,7 +33,7 @@ def api_trello_webhook(
return json_success(request)
-def get_topic_and_body(payload: WildValue, action_type: str) -> Optional[tuple[str, str]]:
+def get_topic_and_body(payload: WildValue, action_type: str) -> tuple[str, str] | None:
if action_type in SUPPORTED_CARD_ACTIONS:
return process_card_action(payload, action_type)
if action_type in IGNORED_CARD_ACTIONS:
diff --git a/zerver/webhooks/trello/view/board_actions.py b/zerver/webhooks/trello/view/board_actions.py
index f03115dd886..d69e70c1fe8 100644
--- a/zerver/webhooks/trello/view/board_actions.py
+++ b/zerver/webhooks/trello/view/board_actions.py
@@ -1,4 +1,4 @@
-from typing import Mapping, Optional
+from typing import Mapping
from zerver.lib.exceptions import UnsupportedWebhookEventTypeError
from zerver.lib.validator import WildValue, check_string
@@ -25,16 +25,14 @@ ACTIONS_TO_MESSAGE_MAPPER = {
}
-def process_board_action(
- payload: WildValue, action_type: Optional[str]
-) -> Optional[tuple[str, str]]:
+def process_board_action(payload: WildValue, action_type: str | None) -> tuple[str, str] | None:
action_type = get_proper_action(payload, action_type)
if action_type is not None:
return get_topic(payload), get_body(payload, action_type)
return None
-def get_proper_action(payload: WildValue, action_type: Optional[str]) -> Optional[str]:
+def get_proper_action(payload: WildValue, action_type: str | None) -> str | None:
if action_type == "updateBoard":
data = get_action_data(payload)
# we don't support events for when a board's background
diff --git a/zerver/webhooks/trello/view/card_actions.py b/zerver/webhooks/trello/view/card_actions.py
index 4fb950582e2..da0fcd3be7c 100644
--- a/zerver/webhooks/trello/view/card_actions.py
+++ b/zerver/webhooks/trello/view/card_actions.py
@@ -1,4 +1,4 @@
-from typing import Mapping, Optional
+from typing import Mapping
from zerver.lib.exceptions import UnsupportedWebhookEventTypeError
from zerver.lib.validator import WildValue, check_bool, check_none_or, check_string
@@ -75,14 +75,14 @@ def prettify_date(date_string: str) -> str:
return date_string.replace("T", " ").replace(".000", "").replace("Z", " UTC")
-def process_card_action(payload: WildValue, action_type: str) -> Optional[tuple[str, str]]:
+def process_card_action(payload: WildValue, action_type: str) -> tuple[str, str] | None:
proper_action = get_proper_action(payload, action_type)
if proper_action is not None:
return get_topic(payload), get_body(payload, proper_action)
return None
-def get_proper_action(payload: WildValue, action_type: str) -> Optional[str]:
+def get_proper_action(payload: WildValue, action_type: str) -> str | None:
if action_type == "updateCard":
data = get_action_data(payload)
old_data = data["old"]
diff --git a/zerver/worker/base.py b/zerver/worker/base.py
index da3ac9d5530..a6e1d009ccb 100644
--- a/zerver/worker/base.py
+++ b/zerver/worker/base.py
@@ -6,7 +6,7 @@ import time
from abc import ABC, abstractmethod
from collections import deque
from types import FrameType
-from typing import Any, Callable, MutableSequence, Optional, TypeVar
+from typing import Any, Callable, MutableSequence, TypeVar
import orjson
import sentry_sdk
@@ -87,7 +87,7 @@ def check_and_send_restart_signal() -> None:
class QueueProcessingWorker(ABC):
queue_name: str
- MAX_CONSUME_SECONDS: Optional[int] = 30
+ MAX_CONSUME_SECONDS: int | None = 30
CONSUME_ITERATIONS_BEFORE_UPDATE_STATS_NUM = 50
MAX_SECONDS_BEFORE_UPDATE_STATS = 30
@@ -101,9 +101,9 @@ class QueueProcessingWorker(ABC):
self,
threaded: bool = False,
disable_timeout: bool = False,
- worker_num: Optional[int] = None,
+ worker_num: int | None = None,
) -> None:
- self.q: Optional[SimpleQueueClient] = None
+ self.q: SimpleQueueClient | None = None
self.threaded = threaded
self.disable_timeout = disable_timeout
self.worker_num = worker_num
@@ -166,7 +166,7 @@ class QueueProcessingWorker(ABC):
def do_consume(
self, consume_func: Callable[[list[dict[str, Any]]], None], events: list[dict[str, Any]]
) -> None:
- consume_time_seconds: Optional[float] = None
+ consume_time_seconds: float | None = None
with sentry_sdk.start_transaction(
op="task",
name=f"consume {self.queue_name}",
@@ -241,7 +241,7 @@ class QueueProcessingWorker(ABC):
self.do_consume(consume_func, [event])
def timer_expired(
- self, limit: int, events: list[dict[str, Any]], signal: int, frame: Optional[FrameType]
+ self, limit: int, events: list[dict[str, Any]], signal: int, frame: FrameType | None
) -> None:
raise WorkerTimeoutError(self.queue_name, limit, len(events))
diff --git a/zerver/worker/email_senders.py b/zerver/worker/email_senders.py
index 59b553b1d65..5689d6ee155 100644
--- a/zerver/worker/email_senders.py
+++ b/zerver/worker/email_senders.py
@@ -3,7 +3,7 @@ import copy
import logging
import socket
from functools import wraps
-from typing import Any, Callable, Optional
+from typing import Any, Callable
from django.core.mail.backends.base import BaseEmailBackend
from typing_extensions import override
@@ -50,10 +50,10 @@ class EmailSendingWorker(LoopQueueProcessingWorker):
self,
threaded: bool = False,
disable_timeout: bool = False,
- worker_num: Optional[int] = None,
+ worker_num: int | None = None,
) -> None:
super().__init__(threaded, disable_timeout, worker_num)
- self.connection: Optional[BaseEmailBackend] = None
+ self.connection: BaseEmailBackend | None = None
@retry_send_email_failures
def send_email(self, event: dict[str, Any]) -> None:
diff --git a/zerver/worker/embed_links.py b/zerver/worker/embed_links.py
index c4a03a2ab5d..86b001eff54 100644
--- a/zerver/worker/embed_links.py
+++ b/zerver/worker/embed_links.py
@@ -2,7 +2,7 @@
import logging
import time
from types import FrameType
-from typing import Any, Mapping, Optional
+from typing import Any, Mapping
from django.db import transaction
from typing_extensions import override
@@ -25,7 +25,7 @@ class FetchLinksEmbedData(QueueProcessingWorker):
@override
def consume(self, event: Mapping[str, Any]) -> None:
- url_embed_data: dict[str, Optional[UrlEmbedData]] = {}
+ url_embed_data: dict[str, UrlEmbedData | None] = {}
for url in event["urls"]:
start_time = time.time()
url_embed_data[url] = url_preview.get_link_embed_data(url)
@@ -59,7 +59,7 @@ class FetchLinksEmbedData(QueueProcessingWorker):
@override
def timer_expired(
- self, limit: int, events: list[dict[str, Any]], signal: int, frame: Optional[FrameType]
+ self, limit: int, events: list[dict[str, Any]], signal: int, frame: FrameType | None
) -> None:
assert len(events) == 1
event = events[0]
diff --git a/zerver/worker/missedmessage_emails.py b/zerver/worker/missedmessage_emails.py
index ecf404f959b..079db3923bd 100644
--- a/zerver/worker/missedmessage_emails.py
+++ b/zerver/worker/missedmessage_emails.py
@@ -3,7 +3,7 @@ import logging
import threading
from collections import defaultdict
from datetime import timedelta
-from typing import Any, Optional
+from typing import Any
import sentry_sdk
from django.db import transaction
@@ -32,7 +32,7 @@ class MissedMessageWorker(QueueProcessingWorker):
# CHECK_FREQUENCY_SECONDS, to avoid excessive activity.
CHECK_FREQUENCY_SECONDS = 5
- worker_thread: Optional[threading.Thread] = None
+ worker_thread: threading.Thread | None = None
# This condition variable mediates the stopping and has_timeout
# pieces of state, below it.
@@ -176,7 +176,7 @@ class MissedMessageWorker(QueueProcessingWorker):
# them regularly; this happens by hitting the
# timeout and calling maybe_send_batched_emails().
# There is no explicit notify() for this.
- timeout: Optional[int] = None
+ timeout: int | None = None
if ScheduledMessageNotificationEmail.objects.exists():
timeout = self.CHECK_FREQUENCY_SECONDS
self.has_timeout = timeout is not None
diff --git a/zerver/worker/missedmessage_mobile_notifications.py b/zerver/worker/missedmessage_mobile_notifications.py
index a776ebc2903..f63e57e3c5a 100644
--- a/zerver/worker/missedmessage_mobile_notifications.py
+++ b/zerver/worker/missedmessage_mobile_notifications.py
@@ -1,6 +1,6 @@
# Documented in https://zulip.readthedocs.io/en/latest/subsystems/queuing.html
import logging
-from typing import Any, Optional
+from typing import Any
from django.conf import settings
from typing_extensions import override
@@ -29,7 +29,7 @@ class PushNotificationsWorker(QueueProcessingWorker):
self,
threaded: bool = False,
disable_timeout: bool = False,
- worker_num: Optional[int] = None,
+ worker_num: int | None = None,
) -> None:
if settings.MOBILE_NOTIFICATIONS_SHARDS > 1 and worker_num is not None: # nocoverage
self.queue_name = self.queue_name + f"_shard{worker_num}"
diff --git a/zerver/worker/queue_processors.py b/zerver/worker/queue_processors.py
index 72427e0ca62..f85836a42fb 100644
--- a/zerver/worker/queue_processors.py
+++ b/zerver/worker/queue_processors.py
@@ -1,7 +1,6 @@
# Documented in https://zulip.readthedocs.io/en/latest/subsystems/queuing.html
import importlib
import pkgutil
-from typing import Optional
import zerver.worker
from zerver.worker.base import QueueProcessingWorker, test_queues, worker_classes
@@ -12,7 +11,7 @@ def get_worker(
*,
threaded: bool = False,
disable_timeout: bool = False,
- worker_num: Optional[int] = None,
+ worker_num: int | None = None,
) -> QueueProcessingWorker:
if queue_name in {"test", "noop", "noop_batch"}:
import_module = "zerver.worker.test"
diff --git a/zerver/worker/test.py b/zerver/worker/test.py
index 7cd701bfca8..2faf04b6e60 100644
--- a/zerver/worker/test.py
+++ b/zerver/worker/test.py
@@ -1,7 +1,7 @@
# Documented in https://zulip.readthedocs.io/en/latest/subsystems/queuing.html
import logging
import time
-from typing import Any, Mapping, Optional, Sequence
+from typing import Any, Mapping, Sequence
import orjson
from django.conf import settings
@@ -35,7 +35,7 @@ class NoopWorker(QueueProcessingWorker):
self,
threaded: bool = False,
disable_timeout: bool = False,
- worker_num: Optional[int] = None,
+ worker_num: int | None = None,
max_consume: int = 1000,
slow_queries: Sequence[int] = [],
) -> None:
diff --git a/zilencer/management/commands/populate_billing_realms.py b/zilencer/management/commands/populate_billing_realms.py
index b0651917c6d..8c66f558fa3 100644
--- a/zilencer/management/commands/populate_billing_realms.py
+++ b/zilencer/management/commands/populate_billing_realms.py
@@ -2,7 +2,7 @@ import contextlib
import uuid
from dataclasses import dataclass
from datetime import datetime, timezone
-from typing import Any, Optional
+from typing import Any
import stripe
from django.conf import settings
@@ -47,8 +47,8 @@ communicate_with_stripe = get_secret("stripe_secret_key") is not None
class CustomerProfile:
unique_id: str
billing_schedule: int = CustomerPlan.BILLING_SCHEDULE_ANNUAL
- tier: Optional[int] = None
- new_plan_tier: Optional[int] = None
+ tier: int | None = None
+ new_plan_tier: int | None = None
automanage_licenses: bool = False
status: int = CustomerPlan.ACTIVE
sponsorship_pending: bool = False
@@ -329,7 +329,7 @@ def create_plan_for_customer(customer: Customer, customer_profile: CustomerProfi
)
-def populate_realm(customer_profile: CustomerProfile) -> Optional[Realm]:
+def populate_realm(customer_profile: CustomerProfile) -> Realm | None:
unique_id = customer_profile.unique_id
if customer_profile.is_remote_realm:
plan_type = Realm.PLAN_TYPE_SELF_HOSTED
diff --git a/zilencer/management/commands/queue_rate.py b/zilencer/management/commands/queue_rate.py
index 788a947070a..db47e6a7988 100644
--- a/zilencer/management/commands/queue_rate.py
+++ b/zilencer/management/commands/queue_rate.py
@@ -1,6 +1,6 @@
import csv
from timeit import timeit
-from typing import Any, Union
+from typing import Any
from django.core.management.base import CommandParser
from typing_extensions import override
@@ -53,7 +53,7 @@ class Command(ZulipBaseCommand):
for prefetch in options["prefetches"]:
print(f"Queue size {count}, prefetch {prefetch}...")
- worker: Union[NoopWorker, BatchNoopWorker] = NoopWorker(count, options["slow"])
+ worker: NoopWorker | BatchNoopWorker = NoopWorker(count, options["slow"])
if options["batch"]:
worker = BatchNoopWorker(count, options["slow"])
if prefetch > 0 and prefetch < worker.batch_size:
diff --git a/zilencer/views.py b/zilencer/views.py
index 302dd87820c..cbdb6abe4f2 100644
--- a/zilencer/views.py
+++ b/zilencer/views.py
@@ -2,7 +2,7 @@ import logging
from collections import Counter
from datetime import datetime, timezone
from email.headerregistry import Address
-from typing import Any, Optional, TypedDict, TypeVar, Union
+from typing import Any, TypedDict, TypeVar
from uuid import UUID
import orjson
@@ -142,7 +142,7 @@ def register_remote_server(
hostname: Annotated[str, StringConstraints(max_length=RemoteZulipServer.HOSTNAME_MAX_LENGTH)],
contact_email: str,
new_org_key: Annotated[
- Optional[str],
+ str | None,
RequiredStringConstraint,
AfterValidator(lambda s: check_string_fixed_length(s, RemoteZulipServer.API_KEY_LENGTH)),
] = None,
@@ -247,12 +247,12 @@ def register_remote_push_device(
request: HttpRequest,
server: RemoteZulipServer,
*,
- user_id: Optional[Json[int]] = None,
- user_uuid: Optional[str] = None,
- realm_uuid: Optional[str] = None,
+ user_id: Json[int] | None = None,
+ user_uuid: str | None = None,
+ realm_uuid: str | None = None,
token: Annotated[str, RequiredStringConstraint],
token_kind: Json[int],
- ios_app_id: Optional[ApnsAppId] = None,
+ ios_app_id: ApnsAppId | None = None,
) -> HttpResponse:
validate_bouncer_token_request(token, token_kind)
if token_kind == RemotePushDeviceToken.APNS and ios_app_id is None:
@@ -310,9 +310,9 @@ def unregister_remote_push_device(
*,
token: Annotated[str, RequiredStringConstraint],
token_kind: Json[int],
- user_id: Optional[Json[int]] = None,
- user_uuid: Optional[str] = None,
- realm_uuid: Optional[str] = None,
+ user_id: Json[int] | None = None,
+ user_uuid: str | None = None,
+ realm_uuid: str | None = None,
) -> HttpResponse:
validate_bouncer_token_request(token, token_kind)
user_identity = UserPushIdentityCompat(user_id=user_id, user_uuid=user_uuid)
@@ -333,9 +333,9 @@ def unregister_all_remote_push_devices(
request: HttpRequest,
server: RemoteZulipServer,
*,
- user_id: Optional[Json[int]] = None,
- user_uuid: Optional[str] = None,
- realm_uuid: Optional[str] = None,
+ user_id: Json[int] | None = None,
+ user_uuid: str | None = None,
+ realm_uuid: str | None = None,
) -> HttpResponse:
user_identity = UserPushIdentityCompat(user_id=user_id, user_uuid=user_uuid)
@@ -348,8 +348,8 @@ def unregister_all_remote_push_devices(
def update_remote_realm_last_request_datetime_helper(
request: HttpRequest,
server: RemoteZulipServer,
- realm_uuid: Optional[str],
- user_uuid: Optional[str],
+ realm_uuid: str | None,
+ user_uuid: str | None,
) -> None:
if realm_uuid is not None:
assert user_uuid is not None
@@ -422,7 +422,7 @@ class TestNotificationPayload(BaseModel):
token_kind: int
user_id: int
user_uuid: str
- realm_uuid: Optional[str] = None
+ realm_uuid: str | None = None
base_payload: dict[str, Any]
model_config = ConfigDict(extra="forbid")
@@ -469,7 +469,7 @@ def remote_server_send_test_notification(
def get_remote_realm_helper(
request: HttpRequest, server: RemoteZulipServer, realm_uuid: str, user_uuid: str
-) -> Optional[RemoteRealm]:
+) -> RemoteRealm | None:
"""
Tries to fetch RemoteRealm for the given realm_uuid and server. Otherwise,
returns None and logs what happened using request and user_uuid args to make
@@ -518,9 +518,9 @@ class PushNotificationsDisallowedError(JsonableError):
class RemoteServerNotificationPayload(BaseModel):
- user_id: Optional[int] = None
- user_uuid: Optional[str] = None
- realm_uuid: Optional[str] = None
+ user_id: int | None = None
+ user_uuid: str | None = None
+ realm_uuid: str | None = None
gcm_payload: dict[str, Any] = {}
apns_payload: dict[str, Any] = {}
gcm_options: dict[str, Any] = {}
@@ -585,8 +585,8 @@ def remote_server_notify_push(
if apple_devices and user_id is not None and user_uuid is not None:
apple_devices = delete_duplicate_registrations(apple_devices, server.id, user_id, user_uuid)
- remote_queue_latency: Optional[str] = None
- sent_time: Optional[Union[float, int]] = gcm_payload.get(
+ remote_queue_latency: str | None = None
+ sent_time: float | int | None = gcm_payload.get(
# TODO/compatibility: This could be a lot simpler if not for pre-5.0 Zulip servers
# that had an older format. Future implementation:
# "time", apns_payload["custom"]["zulip"].get("time")
@@ -680,7 +680,7 @@ def remote_server_notify_push(
increment=android_successfully_delivered + apple_successfully_delivered,
)
- remote_realm_dict: Optional[RemoteRealmDictValue] = None
+ remote_realm_dict: RemoteRealmDictValue | None = None
if remote_realm is not None:
do_increment_logging_stat(
remote_realm,
@@ -1144,11 +1144,11 @@ def remote_server_post_analytics(
*,
realm_counts: Json[list[RealmCountDataForAnalytics]],
installation_counts: Json[list[InstallationCountDataForAnalytics]],
- realmauditlog_rows: Optional[Json[list[RealmAuditLogDataForAnalytics]]] = None,
- realms: Optional[Json[list[RealmDataForAnalytics]]] = None,
- version: Optional[Json[str]] = None,
- merge_base: Optional[Json[str]] = None,
- api_feature_level: Optional[Json[int]] = None,
+ realmauditlog_rows: Json[list[RealmAuditLogDataForAnalytics]] | None = None,
+ realms: Json[list[RealmDataForAnalytics]] | None = None,
+ version: Json[str] | None = None,
+ merge_base: Json[str] | None = None,
+ api_feature_level: Json[int] | None = None,
) -> HttpResponse:
# Lock the server, preventing this from racing with other
# duplicate submissions of the data
@@ -1329,7 +1329,7 @@ def remote_server_post_analytics(
def build_realm_id_to_remote_realm_dict(
- server: RemoteZulipServer, realms: Optional[list[RealmDataForAnalytics]]
+ server: RemoteZulipServer, realms: list[RealmDataForAnalytics] | None
) -> dict[int, RemoteRealm]:
if realms is None:
return {}
diff --git a/zproject/backends.py b/zproject/backends.py
index 4d9550fec95..8a910f40562 100644
--- a/zproject/backends.py
+++ b/zproject/backends.py
@@ -17,7 +17,7 @@ import json
import logging
from abc import ABC, abstractmethod
from email.headerregistry import Address
-from typing import Any, Callable, Optional, TypedDict, TypeVar, Union, cast
+from typing import Any, Callable, TypedDict, TypeVar, cast
from urllib.parse import urlencode
import magic
@@ -153,8 +153,8 @@ def pad_method_dict(method_dict: dict[str, bool]) -> dict[str, bool]:
def auth_enabled_helper(
backends_to_check: list[str],
- realm: Optional[Realm],
- realm_authentication_methods: Optional[dict[str, bool]] = None,
+ realm: Realm | None,
+ realm_authentication_methods: dict[str, bool] | None = None,
) -> bool:
"""
realm_authentication_methods can be passed if already fetched to avoid
@@ -179,19 +179,19 @@ def auth_enabled_helper(
def ldap_auth_enabled(
- realm: Optional[Realm] = None, realm_authentication_methods: Optional[dict[str, bool]] = None
+ realm: Realm | None = None, realm_authentication_methods: dict[str, bool] | None = None
) -> bool:
return auth_enabled_helper(["LDAP"], realm, realm_authentication_methods)
def email_auth_enabled(
- realm: Optional[Realm] = None, realm_authentication_methods: Optional[dict[str, bool]] = None
+ realm: Realm | None = None, realm_authentication_methods: dict[str, bool] | None = None
) -> bool:
return auth_enabled_helper(["Email"], realm, realm_authentication_methods)
def password_auth_enabled(
- realm: Optional[Realm] = None, realm_authentication_methods: Optional[dict[str, bool]] = None
+ realm: Realm | None = None, realm_authentication_methods: dict[str, bool] | None = None
) -> bool:
return ldap_auth_enabled(realm, realm_authentication_methods) or email_auth_enabled(
realm, realm_authentication_methods
@@ -199,48 +199,48 @@ def password_auth_enabled(
def dev_auth_enabled(
- realm: Optional[Realm] = None, realm_authentication_methods: Optional[dict[str, bool]] = None
+ realm: Realm | None = None, realm_authentication_methods: dict[str, bool] | None = None
) -> bool:
return auth_enabled_helper(["Dev"], realm, realm_authentication_methods)
def google_auth_enabled(
- realm: Optional[Realm] = None, realm_authentication_methods: Optional[dict[str, bool]] = None
+ realm: Realm | None = None, realm_authentication_methods: dict[str, bool] | None = None
) -> bool:
return auth_enabled_helper(["Google"], realm, realm_authentication_methods)
def github_auth_enabled(
- realm: Optional[Realm] = None, realm_authentication_methods: Optional[dict[str, bool]] = None
+ realm: Realm | None = None, realm_authentication_methods: dict[str, bool] | None = None
) -> bool:
return auth_enabled_helper(["GitHub"], realm, realm_authentication_methods)
def gitlab_auth_enabled(
- realm: Optional[Realm] = None, realm_authentication_methods: Optional[dict[str, bool]] = None
+ realm: Realm | None = None, realm_authentication_methods: dict[str, bool] | None = None
) -> bool:
return auth_enabled_helper(["GitLab"], realm, realm_authentication_methods)
def apple_auth_enabled(
- realm: Optional[Realm] = None, realm_authentication_methods: Optional[dict[str, bool]] = None
+ realm: Realm | None = None, realm_authentication_methods: dict[str, bool] | None = None
) -> bool:
return auth_enabled_helper(["Apple"], realm, realm_authentication_methods)
def saml_auth_enabled(
- realm: Optional[Realm] = None, realm_authentication_methods: Optional[dict[str, bool]] = None
+ realm: Realm | None = None, realm_authentication_methods: dict[str, bool] | None = None
) -> bool:
return auth_enabled_helper(["SAML"], realm, realm_authentication_methods)
-def require_email_format_usernames(realm: Optional[Realm] = None) -> bool:
+def require_email_format_usernames(realm: Realm | None = None) -> bool:
if ldap_auth_enabled(realm) and (settings.LDAP_EMAIL_ATTR or settings.LDAP_APPEND_DOMAIN):
return False
return True
-def is_user_active(user_profile: UserProfile, return_data: Optional[dict[str, Any]] = None) -> bool:
+def is_user_active(user_profile: UserProfile, return_data: dict[str, Any] | None = None) -> bool:
if user_profile.realm.deactivated:
if return_data is not None:
return_data["inactive_realm"] = True
@@ -258,8 +258,8 @@ def is_user_active(user_profile: UserProfile, return_data: Optional[dict[str, An
def common_get_active_user(
- email: str, realm: Realm, return_data: Optional[dict[str, Any]] = None
-) -> Optional[UserProfile]:
+ email: str, realm: Realm, return_data: dict[str, Any] | None = None
+) -> UserProfile | None:
"""This is the core common function used by essentially all
authentication backends to check if there's an active user account
with a given email address in the organization, handling both
@@ -305,7 +305,7 @@ def is_subdomain_in_allowed_subdomains_list(subdomain: str, allowed_subdomains:
return False
-AuthFuncT = TypeVar("AuthFuncT", bound=Callable[..., Optional[UserProfile]])
+AuthFuncT = TypeVar("AuthFuncT", bound=Callable[..., UserProfile | None])
class RateLimitedAuthenticationByUsername(RateLimitedObject):
@@ -340,7 +340,7 @@ def auth_rate_limiting_already_applied(request: HttpRequest) -> bool:
# @decorator does this for us.
# The usual @wraps from functools breaks signatures, so it can't be used here.
@decorator
-def custom_auth_decorator(auth_func: AuthFuncT, *args: Any, **kwargs: Any) -> Optional[UserProfile]:
+def custom_auth_decorator(auth_func: AuthFuncT, *args: Any, **kwargs: Any) -> UserProfile | None:
custom_auth_wrapper_func = settings.CUSTOM_AUTHENTICATION_WRAPPER_FUNCTION
if custom_auth_wrapper_func is None:
return auth_func(*args, **kwargs)
@@ -349,7 +349,7 @@ def custom_auth_decorator(auth_func: AuthFuncT, *args: Any, **kwargs: Any) -> Op
@decorator
-def rate_limit_auth(auth_func: AuthFuncT, *args: Any, **kwargs: Any) -> Optional[UserProfile]:
+def rate_limit_auth(auth_func: AuthFuncT, *args: Any, **kwargs: Any) -> UserProfile | None:
if not settings.RATE_LIMITING_AUTHENTICATE:
return auth_func(*args, **kwargs)
@@ -379,7 +379,7 @@ def rate_limit_auth(auth_func: AuthFuncT, *args: Any, **kwargs: Any) -> Optional
@decorator
-def log_auth_attempts(auth_func: AuthFuncT, *args: Any, **kwargs: Any) -> Optional[UserProfile]:
+def log_auth_attempts(auth_func: AuthFuncT, *args: Any, **kwargs: Any) -> UserProfile | None:
result = auth_func(*args, **kwargs)
backend_instance = args[0]
@@ -428,12 +428,12 @@ class ZulipAuthMixin:
"""
name = "undefined"
- _logger: Optional[logging.Logger] = None
+ _logger: logging.Logger | None = None
# Describes which plans gives access to this authentication method on zulipchat.com.
# None means the backend is available regardless of the plan.
# Otherwise, it should be a list of Realm.plan_type values that give access to the backend.
- available_for_cloud_plans: Optional[list[int]] = None
+ available_for_cloud_plans: list[int] | None = None
@property
def logger(self) -> logging.Logger:
@@ -441,7 +441,7 @@ class ZulipAuthMixin:
self._logger = logging.getLogger(f"zulip.auth.{self.name}")
return self._logger
- def get_user(self, user_profile_id: int) -> Optional[UserProfile]:
+ def get_user(self, user_profile_id: int) -> UserProfile | None:
"""Override the Django method for getting a UserProfile object from
the user_profile_id,."""
try:
@@ -464,13 +464,13 @@ class ZulipDummyBackend(ZulipAuthMixin):
@custom_auth_decorator
def authenticate(
self,
- request: Optional[HttpRequest] = None,
+ request: HttpRequest | None = None,
*,
username: str,
realm: Realm,
use_dummy_backend: bool = False,
- return_data: Optional[dict[str, Any]] = None,
- ) -> Optional[UserProfile]:
+ return_data: dict[str, Any] | None = None,
+ ) -> UserProfile | None:
if use_dummy_backend:
return common_get_active_user(username, realm, return_data)
return None
@@ -514,8 +514,8 @@ class EmailAuthBackend(ZulipAuthMixin):
username: str,
password: str,
realm: Realm,
- return_data: Optional[dict[str, Any]] = None,
- ) -> Optional[UserProfile]:
+ return_data: dict[str, Any] | None = None,
+ ) -> UserProfile | None:
"""Authenticate a user based on email address as the user name."""
if not password_auth_enabled(realm):
if return_data is not None:
@@ -706,16 +706,16 @@ class ZulipLDAPAuthBackendBase(ZulipAuthMixin, LDAPBackend):
# Disable django-auth-ldap's permissions functions -- we don't use
# the standard Django user/group permissions system because they
# are prone to performance issues.
- def has_perm(self, user: Optional[UserProfile], perm: Any, obj: Any = None) -> bool:
+ def has_perm(self, user: UserProfile | None, perm: Any, obj: Any = None) -> bool:
return False
- def has_module_perms(self, user: Optional[UserProfile], app_label: Optional[str]) -> bool:
+ def has_module_perms(self, user: UserProfile | None, app_label: str | None) -> bool:
return False
- def get_all_permissions(self, user: Optional[UserProfile], obj: Any = None) -> set[Any]:
+ def get_all_permissions(self, user: UserProfile | None, obj: Any = None) -> set[Any]:
return set()
- def get_group_permissions(self, user: Optional[UserProfile], obj: Any = None) -> set[Any]:
+ def get_group_permissions(self, user: UserProfile | None, obj: Any = None) -> set[Any]:
return set()
def django_to_ldap_username(self, username: str) -> str:
@@ -929,7 +929,7 @@ class ZulipLDAPAuthBackendBase(ZulipAuthMixin, LDAPBackend):
def sync_custom_profile_fields_from_ldap(
self, user_profile: UserProfile, ldap_user: _LDAPUser
) -> None:
- values_by_var_name: dict[str, Union[int, str, list[int]]] = {}
+ values_by_var_name: dict[str, int | str | list[int]] = {}
for attr, ldap_attr in settings.AUTH_LDAP_USER_ATTR_MAP.items():
if not attr.startswith("custom_profile_field__"):
continue
@@ -1029,15 +1029,15 @@ class ZulipLDAPAuthBackend(ZulipLDAPAuthBackendBase):
@custom_auth_decorator
def authenticate(
self,
- request: Optional[HttpRequest] = None,
+ request: HttpRequest | None = None,
*,
username: str,
password: str,
realm: Realm,
- prereg_realm: Optional[PreregistrationRealm] = None,
- prereg_user: Optional[PreregistrationUser] = None,
- return_data: Optional[dict[str, Any]] = None,
- ) -> Optional[UserProfile]:
+ prereg_realm: PreregistrationRealm | None = None,
+ prereg_user: PreregistrationUser | None = None,
+ return_data: dict[str, Any] | None = None,
+ ) -> UserProfile | None:
self._realm = realm
self._prereg_user = prereg_user
self._prereg_realm = prereg_realm
@@ -1204,13 +1204,13 @@ class ZulipLDAPUserPopulator(ZulipLDAPAuthBackendBase):
def authenticate(
self,
- request: Optional[HttpRequest] = None,
+ request: HttpRequest | None = None,
*,
username: str,
password: str,
realm: Realm,
- return_data: Optional[dict[str, Any]] = None,
- ) -> Optional[UserProfile]:
+ return_data: dict[str, Any] | None = None,
+ ) -> UserProfile | None:
return None
def get_or_build_user(
@@ -1348,12 +1348,12 @@ class DevAuthBackend(ZulipAuthMixin):
def authenticate(
self,
- request: Optional[HttpRequest] = None,
+ request: HttpRequest | None = None,
*,
dev_auth_username: str,
realm: Realm,
- return_data: Optional[dict[str, Any]] = None,
- ) -> Optional[UserProfile]:
+ return_data: dict[str, Any] | None = None,
+ ) -> UserProfile | None:
if not dev_auth_enabled(realm):
return None
return common_get_active_user(dev_auth_username, realm, return_data=return_data)
@@ -1362,7 +1362,7 @@ class DevAuthBackend(ZulipAuthMixin):
class ExternalAuthMethodDictT(TypedDict):
name: str
display_name: str
- display_icon: Optional[str]
+ display_icon: str | None
login_url: str
signup_url: str
@@ -1377,7 +1377,7 @@ class ExternalAuthMethod(ABC):
auth_backend_name = "undeclared"
name = "undeclared"
- display_icon: Optional[str] = None
+ display_icon: str | None = None
# Used to determine how to order buttons on login form, backend with
# higher sort order are displayed first.
@@ -1385,7 +1385,7 @@ class ExternalAuthMethod(ABC):
@classmethod
@abstractmethod
- def dict_representation(cls, realm: Optional[Realm] = None) -> list[ExternalAuthMethodDictT]:
+ def dict_representation(cls, realm: Realm | None = None) -> list[ExternalAuthMethodDictT]:
"""
Method returning dictionaries representing the authentication methods
corresponding to the backend that subclasses this. The documentation
@@ -1415,8 +1415,8 @@ class ExternalAuthDataDict(TypedDict, total=False):
is_signup: bool
is_realm_creation: bool
redirect_to: str
- mobile_flow_otp: Optional[str]
- desktop_flow_otp: Optional[str]
+ mobile_flow_otp: str | None
+ desktop_flow_otp: str | None
multiuse_object_key: str
full_name_validated: bool
# The mobile app doesn't actually use a session, so this
@@ -1433,10 +1433,10 @@ class ExternalAuthResult:
def __init__(
self,
*,
- user_profile: Optional[UserProfile] = None,
- data_dict: Optional[ExternalAuthDataDict] = None,
- request: Optional[HttpRequest] = None,
- login_token: Optional[str] = None,
+ user_profile: UserProfile | None = None,
+ data_dict: ExternalAuthDataDict | None = None,
+ request: HttpRequest | None = None,
+ login_token: str | None = None,
delete_stored_data: bool = True,
) -> None:
if data_dict is None:
@@ -1580,12 +1580,12 @@ class ZulipRemoteUserBackend(ZulipAuthMixin, RemoteUserBackend, ExternalAuthMeth
@override
def authenticate( # type: ignore[override] # authenticate has an incompatible signature with ModelBackend and BaseBackend
self,
- request: Optional[HttpRequest] = None,
+ request: HttpRequest | None = None,
*,
remote_user: str,
realm: Realm,
- return_data: Optional[dict[str, Any]] = None,
- ) -> Optional[UserProfile]:
+ return_data: dict[str, Any] | None = None,
+ ) -> UserProfile | None:
if not auth_enabled_helper(["RemoteUser"], realm):
return None
@@ -1594,7 +1594,7 @@ class ZulipRemoteUserBackend(ZulipAuthMixin, RemoteUserBackend, ExternalAuthMeth
@classmethod
@override
- def dict_representation(cls, realm: Optional[Realm] = None) -> list[ExternalAuthMethodDictT]:
+ def dict_representation(cls, realm: Realm | None = None) -> list[ExternalAuthMethodDictT]:
return [
dict(
name=cls.name,
@@ -1631,7 +1631,7 @@ def redirect_deactivated_user_to_login(realm: Realm, email: str) -> HttpResponse
def social_associate_user_helper(
backend: BaseAuth, return_data: dict[str, Any], *args: Any, **kwargs: Any
-) -> Union[HttpResponse, Optional[UserProfile]]:
+) -> HttpResponse | UserProfile | None:
"""Responsible for doing the Zulip account lookup and validation parts
of the Zulip social auth pipeline (similar to the authenticate()
methods in most other auth backends in this file).
@@ -1783,7 +1783,7 @@ def social_associate_user_helper(
@partial
def social_auth_associate_user(
backend: BaseAuth, *args: Any, **kwargs: Any
-) -> Union[HttpResponse, dict[str, Any]]:
+) -> HttpResponse | dict[str, Any]:
"""A simple wrapper function to reformat the return data from
social_associate_user_helper as a dictionary. The
python-social-auth infrastructure will then pass those values into
@@ -1807,7 +1807,7 @@ def social_auth_associate_user(
def social_auth_finish(
backend: Any, details: dict[str, Any], response: HttpResponse, *args: Any, **kwargs: Any
-) -> Optional[HttpResponse]:
+) -> HttpResponse | None:
"""Given the determination in social_auth_associate_user for whether
the user should be authenticated, this takes care of actually
logging in the user (if appropriate) and redirecting the browser
@@ -2013,7 +2013,7 @@ class SocialAuthMixin(ZulipAuthMixin, ExternalAuthMethod, BaseAuth):
standard_relay_params = [*settings.SOCIAL_AUTH_FIELDS_STORED_IN_SESSION, "next"]
- def auth_complete(self, *args: Any, **kwargs: Any) -> Optional[HttpResponse]:
+ def auth_complete(self, *args: Any, **kwargs: Any) -> HttpResponse | None:
"""This is a small wrapper around the core `auth_complete` method of
python-social-auth, designed primarily to prevent 500s for
exceptions in the social auth code from situations that are
@@ -2049,7 +2049,7 @@ class SocialAuthMixin(ZulipAuthMixin, ExternalAuthMethod, BaseAuth):
@classmethod
@override
- def dict_representation(cls, realm: Optional[Realm] = None) -> list[ExternalAuthMethodDictT]:
+ def dict_representation(cls, realm: Realm | None = None) -> list[ExternalAuthMethodDictT]:
return [
dict(
name=cls.name,
@@ -2286,7 +2286,7 @@ class AppleAuthBackend(SocialAuthMixin, AppleIdAuth):
)
return state
- def validate_state(self) -> Optional[str]:
+ def validate_state(self) -> str | None:
"""
This method replaces a method from python-social-auth; it is
adapted to retrieve the data stored in Redis, save it in
@@ -2337,7 +2337,7 @@ class AppleAuthBackend(SocialAuthMixin, AppleIdAuth):
return user_details
@override
- def auth_complete(self, *args: Any, **kwargs: Any) -> Optional[HttpResponse]:
+ def auth_complete(self, *args: Any, **kwargs: Any) -> HttpResponse | None:
if not self.is_native_flow():
# The default implementation in python-social-auth is the browser flow.
return super().auth_complete(*args, **kwargs)
@@ -2428,7 +2428,7 @@ class SAMLDocument:
self.encoded_saml_message = encoded_saml_message
self.backend = backend
- self._decoded_saml_message: Optional[str] = None
+ self._decoded_saml_message: str | None = None
@property
def logger(self) -> logging.Logger:
@@ -2457,7 +2457,7 @@ class SAMLDocument:
"""
return type(self).__name__
- def get_issuing_idp(self) -> Optional[str]:
+ def get_issuing_idp(self) -> str | None:
"""
Given a SAMLResponse or SAMLRequest, returns which of the configured IdPs
is declared as the issuer.
@@ -2523,7 +2523,7 @@ class SAMLResponse(SAMLDocument):
self.logger.error("Error parsing SAMLResponse: %s", str(e))
return []
- def get_session_index(self) -> Optional[str]:
+ def get_session_index(self) -> str | None:
"""
Returns the SessionIndex from the SAMLResponse.
"""
@@ -2637,7 +2637,7 @@ class SAMLAuthBackend(SocialAuthMixin, SAMLAuth):
)
@classmethod
- def get_data_from_redis(cls, key: str) -> Optional[dict[str, Any]]:
+ def get_data_from_redis(cls, key: str) -> dict[str, Any] | None:
data = None
if key.startswith("saml_token_"):
# Safety if statement, to not allow someone to poke around arbitrary Redis keys here.
@@ -2664,7 +2664,7 @@ class SAMLAuthBackend(SocialAuthMixin, SAMLAuth):
except orjson.JSONDecodeError:
return {}
- def choose_subdomain(self, relayed_params: dict[str, Any]) -> Optional[str]:
+ def choose_subdomain(self, relayed_params: dict[str, Any]) -> str | None:
subdomain = relayed_params.get("subdomain")
if subdomain is not None:
return subdomain
@@ -2707,7 +2707,7 @@ class SAMLAuthBackend(SocialAuthMixin, SAMLAuth):
return
subdomain = self.strategy.session_get("subdomain")
- entitlements: Union[str, list[str]] = attributes.get(org_membership_attribute, [])
+ entitlements: str | list[str] = attributes.get(org_membership_attribute, [])
if isinstance(entitlements, str): # nocoverage
# This shouldn't happen as we'd always expect a list from this attribute even
# if it only has one element, but it's safer to have this defensive code.
@@ -2725,7 +2725,7 @@ class SAMLAuthBackend(SocialAuthMixin, SAMLAuth):
)
raise AuthFailed(self, error_msg)
- def process_logout(self, subdomain: str, idp_name: str) -> Optional[HttpResponse]:
+ def process_logout(self, subdomain: str, idp_name: str) -> HttpResponse | None:
"""
We override process_logout, because we need to customize
the way of revoking sessions and introduce NameID validation.
@@ -2797,7 +2797,7 @@ class SAMLAuthBackend(SocialAuthMixin, SAMLAuth):
return HttpResponseRedirect(url)
@override
- def auth_complete(self, *args: Any, **kwargs: Any) -> Optional[HttpResponse]:
+ def auth_complete(self, *args: Any, **kwargs: Any) -> HttpResponse | None:
"""
Additional ugly wrapping on top of auth_complete in SocialAuthMixin.
We handle two things for processing SAMLResponses here:
@@ -2948,7 +2948,7 @@ class SAMLAuthBackend(SocialAuthMixin, SAMLAuth):
@classmethod
@override
- def dict_representation(cls, realm: Optional[Realm] = None) -> list[ExternalAuthMethodDictT]:
+ def dict_representation(cls, realm: Realm | None = None) -> list[ExternalAuthMethodDictT]:
result: list[ExternalAuthMethodDictT] = []
for idp_name, idp_dict in settings.SOCIAL_AUTH_SAML_ENABLED_IDPS.items():
if realm and not cls.validate_idp_for_subdomain(idp_name, realm.subdomain):
@@ -3019,7 +3019,7 @@ class GenericOpenIdConnectBackend(SocialAuthMixin, OpenIdConnectAuth):
settings_dict: OIDCIdPConfigDict
[settings_dict] = settings.SOCIAL_AUTH_OIDC_ENABLED_IDPS.values() or [OIDCIdPConfigDict()]
- display_icon: Optional[str] = settings_dict.get("display_icon", None)
+ display_icon: str | None = settings_dict.get("display_icon", None)
display_name: str = settings_dict.get("display_name", "OIDC")
full_name_validated = getattr(settings, "SOCIAL_AUTH_OIDC_FULL_NAME_VALIDATED", False)
@@ -3050,7 +3050,7 @@ class GenericOpenIdConnectBackend(SocialAuthMixin, OpenIdConnectAuth):
@classmethod
@override
- def dict_representation(cls, realm: Optional[Realm] = None) -> list[ExternalAuthMethodDictT]:
+ def dict_representation(cls, realm: Realm | None = None) -> list[ExternalAuthMethodDictT]:
return [
dict(
name=f"oidc:{cls.name}",
@@ -3069,7 +3069,7 @@ class GenericOpenIdConnectBackend(SocialAuthMixin, OpenIdConnectAuth):
def validate_otp_params(
- mobile_flow_otp: Optional[str] = None, desktop_flow_otp: Optional[str] = None
+ mobile_flow_otp: str | None = None, desktop_flow_otp: str | None = None
) -> None:
for otp in [mobile_flow_otp, desktop_flow_otp]:
if otp is not None and not is_valid_otp(otp):
@@ -3081,7 +3081,7 @@ def validate_otp_params(
class SAMLSPInitiatedLogout:
@classmethod
- def get_logged_in_user_idp(cls, request: HttpRequest) -> Optional[str]:
+ def get_logged_in_user_idp(cls, request: HttpRequest) -> str | None:
"""
Information about the authentication method which was used for
this session is stored in social_auth_backend session attribute.
@@ -3098,7 +3098,7 @@ class SAMLSPInitiatedLogout:
return authentication_method.split("saml:")[1]
@classmethod
- def get_logged_in_user_session_index(cls, request: HttpRequest) -> Optional[str]:
+ def get_logged_in_user_session_index(cls, request: HttpRequest) -> str | None:
"""
During SAML authentication, we obtain the SessionIndex value provided
by the IdP and save it in the session. This function can be used
@@ -3112,9 +3112,7 @@ class SAMLSPInitiatedLogout:
return session_index
@classmethod
- def slo_request_to_idp(
- cls, request: HttpRequest, return_to: Optional[str] = None
- ) -> HttpResponse:
+ def slo_request_to_idp(cls, request: HttpRequest, return_to: str | None = None) -> HttpResponse:
"""
Generates the redirect to the IdP's SLO endpoint with
the appropriately generated LogoutRequest. This should only be called
@@ -3163,7 +3161,7 @@ class SAMLSPInitiatedLogout:
return HttpResponseRedirect(settings.LOGIN_URL)
-def get_external_method_dicts(realm: Optional[Realm] = None) -> list[ExternalAuthMethodDictT]:
+def get_external_method_dicts(realm: Realm | None = None) -> list[ExternalAuthMethodDictT]:
"""
Returns a list of dictionaries that represent social backends, sorted
in the order in which they should be displayed.
diff --git a/zproject/computed_settings.py b/zproject/computed_settings.py
index 6c70b5a4962..17b198a42f3 100644
--- a/zproject/computed_settings.py
+++ b/zproject/computed_settings.py
@@ -3,7 +3,7 @@ import os
import sys
import time
from copy import deepcopy
-from typing import Any, Final, Literal, Union
+from typing import Any, Final, Literal
from urllib.parse import urljoin
from scripts.lib.zulip_tools import get_tornado_ports
@@ -576,7 +576,7 @@ else:
########################################################################
# List of callables that know how to import templates from various sources.
-LOADERS: list[Union[str, tuple[object, ...]]] = [
+LOADERS: list[str | tuple[object, ...]] = [
"django.template.loaders.filesystem.Loader",
"django.template.loaders.app_directories.Loader",
]
diff --git a/zproject/config.py b/zproject/config.py
index c4fdd35f8f4..1f44f8660fd 100644
--- a/zproject/config.py
+++ b/zproject/config.py
@@ -1,6 +1,6 @@
import configparser
import os
-from typing import Optional, Union, overload
+from typing import overload
from scripts.lib.zulip_tools import get_config as get_config_from_file
@@ -27,12 +27,12 @@ else:
@overload
def get_secret(
key: str, default_value: None = None, development_only: bool = False
-) -> Optional[str]: ...
+) -> str | None: ...
@overload
def get_secret(key: str, default_value: str, development_only: bool = False) -> str: ...
def get_secret(
- key: str, default_value: Optional[str] = None, development_only: bool = False
-) -> Optional[str]:
+ key: str, default_value: str | None = None, development_only: bool = False
+) -> str | None:
if development_only and PRODUCTION: # nocoverage
return default_value
return secrets_file.get("secrets", key, fallback=default_value)
@@ -48,14 +48,14 @@ def get_mandatory_secret(key: str) -> str:
@overload
-def get_config(section: str, key: str, default_value: None = None) -> Optional[str]: ...
+def get_config(section: str, key: str, default_value: None = None) -> str | None: ...
@overload
def get_config(section: str, key: str, default_value: str) -> str: ...
@overload
def get_config(section: str, key: str, default_value: bool) -> bool: ...
def get_config(
- section: str, key: str, default_value: Union[str, bool, None] = None
-) -> Union[str, bool, None]:
+ section: str, key: str, default_value: str | bool | None = None
+) -> str | bool | None:
return get_config_from_file(config_file, section, key, default_value)
diff --git a/zproject/default_settings.py b/zproject/default_settings.py
index e7b8bd83fd6..3f30738a20d 100644
--- a/zproject/default_settings.py
+++ b/zproject/default_settings.py
@@ -1,6 +1,6 @@
import os
from email.headerregistry import Address
-from typing import TYPE_CHECKING, Any, Callable, Literal, Optional, Union
+from typing import TYPE_CHECKING, Any, Callable, Literal, Optional
from django_auth_ldap.config import GroupOfUniqueNamesType, LDAPGroupType
@@ -21,7 +21,7 @@ DEBUG = DEVELOPMENT
EXTERNAL_HOST_WITHOUT_PORT = deport(EXTERNAL_HOST)
-STATIC_URL: Optional[str] = None
+STATIC_URL: str | None = None
# These settings are intended for the server admin to set. We document them in
# prod_settings_template.py, and in the initial /etc/zulip/settings.py on a new
@@ -40,7 +40,7 @@ PHYSICAL_ADDRESS = ""
FAKE_EMAIL_DOMAIN = EXTERNAL_HOST_WITHOUT_PORT
# SMTP settings
-EMAIL_HOST: Optional[str] = None
+EMAIL_HOST: str | None = None
# Other settings, like EMAIL_HOST_USER, EMAIL_PORT, and EMAIL_USE_TLS,
# we leave up to Django's defaults.
@@ -48,17 +48,17 @@ EMAIL_HOST: Optional[str] = None
AUTH_LDAP_SERVER_URI = ""
AUTH_LDAP_BIND_DN = ""
AUTH_LDAP_USER_SEARCH: Optional["LDAPSearch"] = None
-LDAP_APPEND_DOMAIN: Optional[str] = None
-LDAP_EMAIL_ATTR: Optional[str] = None
+LDAP_APPEND_DOMAIN: str | None = None
+LDAP_EMAIL_ATTR: str | None = None
AUTH_LDAP_REVERSE_EMAIL_SEARCH: Optional["LDAPSearch"] = None
-AUTH_LDAP_USERNAME_ATTR: Optional[str] = None
+AUTH_LDAP_USERNAME_ATTR: str | None = None
# AUTH_LDAP_USER_ATTR_MAP is uncommented in prod_settings_template.py,
# so the value here mainly serves to help document the default.
AUTH_LDAP_USER_ATTR_MAP: dict[str, str] = {
"full_name": "cn",
}
# Automatically deactivate users not found by the AUTH_LDAP_USER_SEARCH query.
-LDAP_DEACTIVATE_NON_MATCHING_USERS: Optional[bool] = None
+LDAP_DEACTIVATE_NON_MATCHING_USERS: bool | None = None
# AUTH_LDAP_CONNECTION_OPTIONS: we set ldap.OPT_REFERRALS in settings.py if unset.
AUTH_LDAP_CONNECTION_OPTIONS: dict[int, object] = {}
# Disable django-auth-ldap caching, to prevent problems with OU changes.
@@ -68,28 +68,28 @@ AUTH_LDAP_ALWAYS_UPDATE_USER = False
# Development-only settings for fake LDAP authentication; used to
# support local development of LDAP auth without an LDAP server.
# Detailed docs in zproject/dev_settings.py.
-FAKE_LDAP_MODE: Optional[str] = None
+FAKE_LDAP_MODE: str | None = None
FAKE_LDAP_NUM_USERS = 8
-AUTH_LDAP_ADVANCED_REALM_ACCESS_CONTROL: Optional[dict[str, Any]] = None
+AUTH_LDAP_ADVANCED_REALM_ACCESS_CONTROL: dict[str, Any] | None = None
LDAP_SYNCHRONIZED_GROUPS_BY_REALM: dict[str, list[str]] = {}
AUTH_LDAP_GROUP_TYPE: LDAPGroupType = GroupOfUniqueNamesType()
# Social auth; we support providing values for some of these
# settings in zulip-secrets.conf instead of settings.py in development.
SOCIAL_AUTH_GITHUB_KEY = get_secret("social_auth_github_key", development_only=True)
-SOCIAL_AUTH_GITHUB_ORG_NAME: Optional[str] = None
-SOCIAL_AUTH_GITHUB_TEAM_ID: Optional[str] = None
+SOCIAL_AUTH_GITHUB_ORG_NAME: str | None = None
+SOCIAL_AUTH_GITHUB_TEAM_ID: str | None = None
SOCIAL_AUTH_GITLAB_KEY = get_secret("social_auth_gitlab_key", development_only=True)
-SOCIAL_AUTH_SUBDOMAIN: Optional[str] = None
+SOCIAL_AUTH_SUBDOMAIN: str | None = None
SOCIAL_AUTH_AZUREAD_OAUTH2_KEY = get_secret("social_auth_azuread_oauth2_key", development_only=True)
SOCIAL_AUTH_GOOGLE_KEY = get_secret("social_auth_google_key", development_only=True)
# SAML:
-SOCIAL_AUTH_SAML_SP_ENTITY_ID: Optional[str] = None
+SOCIAL_AUTH_SAML_SP_ENTITY_ID: str | None = None
SOCIAL_AUTH_SAML_SP_PUBLIC_CERT = ""
SOCIAL_AUTH_SAML_SP_PRIVATE_KEY = ""
-SOCIAL_AUTH_SAML_ORG_INFO: Optional[dict[str, dict[str, str]]] = None
-SOCIAL_AUTH_SAML_TECHNICAL_CONTACT: Optional[dict[str, str]] = None
-SOCIAL_AUTH_SAML_SUPPORT_CONTACT: Optional[dict[str, str]] = None
+SOCIAL_AUTH_SAML_ORG_INFO: dict[str, dict[str, str]] | None = None
+SOCIAL_AUTH_SAML_TECHNICAL_CONTACT: dict[str, str] | None = None
+SOCIAL_AUTH_SAML_SUPPORT_CONTACT: dict[str, str] | None = None
SOCIAL_AUTH_SAML_ENABLED_IDPS: dict[str, SAMLIdPConfigDict] = {}
SOCIAL_AUTH_SAML_SECURITY_CONFIG: dict[str, Any] = {}
# Set this to True to enforce that any configured IdP needs to specify
@@ -97,7 +97,7 @@ SOCIAL_AUTH_SAML_SECURITY_CONFIG: dict[str, Any] = {}
SAML_REQUIRE_LIMIT_TO_SUBDOMAINS = False
# Historical name for SOCIAL_AUTH_GITHUB_KEY; still allowed in production.
-GOOGLE_OAUTH2_CLIENT_ID: Optional[str] = None
+GOOGLE_OAUTH2_CLIENT_ID: str | None = None
# Apple:
SOCIAL_AUTH_APPLE_SERVICES_ID = get_secret("social_auth_apple_services_id", development_only=True)
@@ -114,20 +114,20 @@ SOCIAL_AUTH_OIDC_FULL_NAME_VALIDATED = False
SOCIAL_AUTH_SYNC_CUSTOM_ATTRS_DICT: dict[str, dict[str, dict[str, str]]] = {}
# Other auth
-SSO_APPEND_DOMAIN: Optional[str] = None
-CUSTOM_HOME_NOT_LOGGED_IN: Optional[str] = None
+SSO_APPEND_DOMAIN: str | None = None
+CUSTOM_HOME_NOT_LOGGED_IN: str | None = None
VIDEO_ZOOM_CLIENT_ID = get_secret("video_zoom_client_id", development_only=True)
VIDEO_ZOOM_CLIENT_SECRET = get_secret("video_zoom_client_secret")
# Email gateway
EMAIL_GATEWAY_PATTERN = ""
-EMAIL_GATEWAY_LOGIN: Optional[str] = None
-EMAIL_GATEWAY_IMAP_SERVER: Optional[str] = None
-EMAIL_GATEWAY_IMAP_PORT: Optional[int] = None
-EMAIL_GATEWAY_IMAP_FOLDER: Optional[str] = None
+EMAIL_GATEWAY_LOGIN: str | None = None
+EMAIL_GATEWAY_IMAP_SERVER: str | None = None
+EMAIL_GATEWAY_IMAP_PORT: int | None = None
+EMAIL_GATEWAY_IMAP_FOLDER: str | None = None
# Not documented for in /etc/zulip/settings.py, since it's rarely needed.
-EMAIL_GATEWAY_EXTRA_PATTERN_HACK: Optional[str] = None
+EMAIL_GATEWAY_EXTRA_PATTERN_HACK: str | None = None
# Error reporting
ERROR_REPORTING = True
@@ -135,22 +135,22 @@ LOGGING_SHOW_MODULE = False
LOGGING_SHOW_PID = False
# Sentry.io error defaults to off
-SENTRY_DSN: Optional[str] = get_config("sentry", "project_dsn", None)
-SENTRY_TRACE_WORKER_RATE: Union[float, dict[str, float]] = 0.0
+SENTRY_DSN: str | None = get_config("sentry", "project_dsn", None)
+SENTRY_TRACE_WORKER_RATE: float | dict[str, float] = 0.0
SENTRY_TRACE_RATE: float = 0.0
SENTRY_PROFILE_RATE: float = 0.1
-SENTRY_FRONTEND_DSN: Optional[str] = get_config("sentry", "frontend_project_dsn", None)
+SENTRY_FRONTEND_DSN: str | None = get_config("sentry", "frontend_project_dsn", None)
SENTRY_FRONTEND_SAMPLE_RATE: float = 1.0
SENTRY_FRONTEND_TRACE_RATE: float = 0.1
# File uploads and avatars
# TODO: Rename MAX_FILE_UPLOAD_SIZE to have unit in name.
-DEFAULT_AVATAR_URI: Optional[str] = None
-DEFAULT_LOGO_URI: Optional[str] = None
+DEFAULT_AVATAR_URI: str | None = None
+DEFAULT_LOGO_URI: str | None = None
S3_AVATAR_BUCKET = ""
S3_AUTH_UPLOADS_BUCKET = ""
-S3_REGION: Optional[str] = None
-S3_ENDPOINT_URL: Optional[str] = None
+S3_REGION: str | None = None
+S3_ENDPOINT_URL: str | None = None
S3_ADDRESSING_STYLE: Literal["auto", "virtual", "path"] = "auto"
S3_SKIP_PROXY = True
S3_UPLOADS_STORAGE_CLASS: Literal[
@@ -161,17 +161,17 @@ S3_UPLOADS_STORAGE_CLASS: Literal[
"STANDARD",
"STANDARD_IA",
] = "STANDARD"
-S3_AVATAR_PUBLIC_URL_PREFIX: Optional[str] = None
-LOCAL_UPLOADS_DIR: Optional[str] = None
-LOCAL_AVATARS_DIR: Optional[str] = None
-LOCAL_FILES_DIR: Optional[str] = None
+S3_AVATAR_PUBLIC_URL_PREFIX: str | None = None
+LOCAL_UPLOADS_DIR: str | None = None
+LOCAL_AVATARS_DIR: str | None = None
+LOCAL_FILES_DIR: str | None = None
MAX_FILE_UPLOAD_SIZE = 25
# How many GB an organization on a paid plan can upload per user,
# on zulipchat.com.
UPLOAD_QUOTA_PER_USER_GB = 5
# Jitsi Meet video call integration; set to None to disable integration.
-JITSI_SERVER_URL: Optional[str] = "https://meet.jit.si"
+JITSI_SERVER_URL: str | None = "https://meet.jit.si"
# GIPHY API key.
GIPHY_API_KEY = get_secret("giphy_api_key")
@@ -217,7 +217,7 @@ NAME_CHANGES_DISABLED = False
AVATAR_CHANGES_DISABLED = False
PASSWORD_MIN_LENGTH = 6
PASSWORD_MIN_GUESSES = 10000
-PUSH_NOTIFICATION_BOUNCER_URL: Optional[str] = None
+PUSH_NOTIFICATION_BOUNCER_URL: str | None = None
PUSH_NOTIFICATION_REDACT_CONTENT = False
SUBMIT_USAGE_STATISTICS = True
PROMOTE_SPONSORING_ZULIP = True
@@ -399,7 +399,7 @@ USING_PGROONGA = False
# How Django should send emails. Set for most contexts in settings.py, but
# available for sysadmin override in unusual cases.
-EMAIL_BACKEND: Optional[str] = None
+EMAIL_BACKEND: str | None = None
# Whether to give admins a warning in the web app that email isn't set up.
# Set in settings.py when email isn't configured.
@@ -418,14 +418,14 @@ POST_MIGRATION_CACHE_FLUSHING = False
# Settings for APNS. Only needed on push.zulipchat.com or if
# rebuilding the mobile app with a different push notifications
# server.
-APNS_CERT_FILE: Optional[str] = None
-APNS_TOKEN_KEY_FILE: Optional[str] = None
+APNS_CERT_FILE: str | None = None
+APNS_TOKEN_KEY_FILE: str | None = None
APNS_TOKEN_KEY_ID = get_secret("apns_token_key_id", development_only=True)
APNS_TEAM_ID = get_secret("apns_team_id", development_only=True)
APNS_SANDBOX = True
# APNS_TOPIC is obsolete. Clients now pass the APNs topic to use.
# ZULIP_IOS_APP_ID is obsolete. Clients now pass the iOS app ID to use for APNs.
-ANDROID_FCM_CREDENTIALS_PATH: Optional[str] = None
+ANDROID_FCM_CREDENTIALS_PATH: str | None = None
# Limits related to the size of file uploads; last few in MB.
DATA_UPLOAD_MAX_MEMORY_SIZE = 25 * 1024 * 1024
@@ -448,7 +448,7 @@ INVITES_NEW_REALM_LIMIT_DAYS = [(1, 100)]
INVITES_NEW_REALM_DAYS = 7
# Controls for which links are published in portico footers/headers/etc.
-REGISTER_LINK_DISABLED: Optional[bool] = None
+REGISTER_LINK_DISABLED: bool | None = None
LOGIN_LINK_DISABLED = False
FIND_TEAM_LINK_DISABLED = True
@@ -458,11 +458,11 @@ ROOT_SUBDOMAIN_ALIASES = ["www"]
ROOT_DOMAIN_LANDING_PAGE = False
# Subdomain for serving endpoints to users from self-hosted deployments.
-SELF_HOSTING_MANAGEMENT_SUBDOMAIN: Optional[str] = None
+SELF_HOSTING_MANAGEMENT_SUBDOMAIN: str | None = None
# If using the Zephyr mirroring supervisord configuration, the
# hostname to connect to in order to transfer credentials from webathena.
-PERSONAL_ZMIRROR_SERVER: Optional[str] = None
+PERSONAL_ZMIRROR_SERVER: str | None = None
# When security-relevant links in emails expire.
CONFIRMATION_LINK_DEFAULT_VALIDITY_DAYS = 1
@@ -472,17 +472,17 @@ REALM_CREATION_LINK_VALIDITY_DAYS = 7
# Version number for ToS. Change this if you want to force every
# user to click through to re-accept terms of service before using
# Zulip again on the web.
-TERMS_OF_SERVICE_VERSION: Optional[str] = None
+TERMS_OF_SERVICE_VERSION: str | None = None
# HTML template path (e.g. "corporate/zulipchat_migration_tos.html")
# displayed to users when increasing TERMS_OF_SERVICE_VERSION when a
# user is to accept the terms of service for the first time, but
# already has an account. This primarily comes up when doing a data
# import.
-FIRST_TIME_TERMS_OF_SERVICE_TEMPLATE: Optional[str] = None
+FIRST_TIME_TERMS_OF_SERVICE_TEMPLATE: str | None = None
# Custom message (HTML allowed) to be displayed to explain why users
# need to re-accept the terms of service when a new major version is
# written.
-TERMS_OF_SERVICE_MESSAGE: Optional[str] = None
+TERMS_OF_SERVICE_MESSAGE: str | None = None
# Configuration for JWT auth (sign in and API key fetch)
JWT_AUTH_KEYS: dict[str, JwtAuthKey] = {}
@@ -494,7 +494,7 @@ SERVER_EMAIL = ZULIP_ADMINISTRATOR
ADMINS = (("Zulip Administrator", ZULIP_ADMINISTRATOR),)
# From address for welcome emails.
-WELCOME_EMAIL_SENDER: Optional[dict[str, str]] = None
+WELCOME_EMAIL_SENDER: dict[str, str] | None = None
# Whether to send periodic digests of activity.
SEND_DIGEST_EMAILS = True
@@ -502,11 +502,11 @@ SEND_DIGEST_EMAILS = True
INSTALLATION_NAME = EXTERNAL_HOST
# Used to change the Zulip logo in portico pages.
-CUSTOM_LOGO_URL: Optional[str] = None
+CUSTOM_LOGO_URL: str | None = None
# Random salt used when deterministically generating passwords in
# development.
-INITIAL_PASSWORD_SALT: Optional[str] = None
+INITIAL_PASSWORD_SALT: str | None = None
# Settings configuring the special instrumentation of the send_event
# code path used in generating API documentation for /events.
@@ -559,12 +559,12 @@ ARCHIVED_DATA_VACUUMING_DELAY_DAYS = 30
# are available to all realms.
BILLING_ENABLED = False
-CLOUD_FREE_TRIAL_DAYS: Optional[int] = int(get_secret("cloud_free_trial_days", "0"))
-SELF_HOSTING_FREE_TRIAL_DAYS: Optional[int] = int(get_secret("self_hosting_free_trial_days", "30"))
+CLOUD_FREE_TRIAL_DAYS: int | None = int(get_secret("cloud_free_trial_days", "0"))
+SELF_HOSTING_FREE_TRIAL_DAYS: int | None = int(get_secret("self_hosting_free_trial_days", "30"))
# Custom message (supports HTML) to be shown in the navbar of landing pages. Used mainly for
# making announcements.
-LANDING_PAGE_NAVBAR_MESSAGE: Optional[str] = None
+LANDING_PAGE_NAVBAR_MESSAGE: str | None = None
# Automatically catch-up soft deactivated users when running the
# `soft-deactivate-users` cron. Turn this off if the server has 10Ks of
@@ -573,7 +573,7 @@ LANDING_PAGE_NAVBAR_MESSAGE: Optional[str] = None
AUTO_CATCH_UP_SOFT_DEACTIVATED_USERS = True
# Enables Google Analytics on selected portico pages.
-GOOGLE_ANALYTICS_ID: Optional[str] = None
+GOOGLE_ANALYTICS_ID: str | None = None
# This is overridden by dev_settings.py for droplets.
IS_DEV_DROPLET = False
@@ -636,7 +636,7 @@ CAN_ACCESS_ALL_USERS_GROUP_LIMITS_PRESENCE = False
# in some places through the codebase.
SIGNED_ACCESS_TOKEN_VALIDITY_IN_SECONDS = 60
-CUSTOM_AUTHENTICATION_WRAPPER_FUNCTION: Optional[Callable[..., Any]] = None
+CUSTOM_AUTHENTICATION_WRAPPER_FUNCTION: Callable[..., Any] | None = None
# Whether we allow settings to be set to a collection of users and
# groups as described in api_docs/group-setting-values.md. Set to
diff --git a/zproject/dev_settings.py b/zproject/dev_settings.py
index e17310ed09e..f092300f563 100644
--- a/zproject/dev_settings.py
+++ b/zproject/dev_settings.py
@@ -1,6 +1,5 @@
import os
import pwd
-from typing import Optional
from scripts.lib.zulip_tools import deport
from zproject.settings_types import SCIMConfigDict
@@ -94,7 +93,7 @@ LOGIN_URL = "/devlogin/"
# For development convenience, configure the ToS/Privacy Policies
POLICIES_DIRECTORY = "corporate/policies"
TERMS_OF_SERVICE_VERSION = "1.0"
-TERMS_OF_SERVICE_MESSAGE: Optional[str] = "Description of changes to the ToS!"
+TERMS_OF_SERVICE_MESSAGE: str | None = "Description of changes to the ToS!"
EMBEDDED_BOTS_ENABLED = True
@@ -133,7 +132,7 @@ TWO_FACTOR_SMS_GATEWAY = "two_factor.gateways.fake.Fake"
# (C) If LDAP usernames are completely unrelated to email addresses.
#
# Fake LDAP data has e.g. ("ldapuser1", "[email protected]") for username/email.
-FAKE_LDAP_MODE: Optional[str] = None
+FAKE_LDAP_MODE: str | None = None
# FAKE_LDAP_NUM_USERS = 8
if FAKE_LDAP_MODE:
@@ -180,7 +179,7 @@ if FAKE_LDAP_MODE:
AUTHENTICATION_BACKENDS += ("zproject.backends.ZulipLDAPAuthBackend",)
BILLING_ENABLED = True
-LANDING_PAGE_NAVBAR_MESSAGE: Optional[str] = None
+LANDING_PAGE_NAVBAR_MESSAGE: str | None = None
# Our run-dev proxy uses X-Forwarded-Port to communicate to Django
# that the request is actually on port 9991, not port 9992 (the Django
@@ -194,7 +193,7 @@ SOCIAL_AUTH_SAML_SP_ENTITY_ID = "http://localhost:9991"
SOCIAL_AUTH_SUBDOMAIN = "auth"
-MEMCACHED_USERNAME: Optional[str] = None
+MEMCACHED_USERNAME: str | None = None
SCIM_CONFIG: dict[str, SCIMConfigDict] = {
"zulip": {
diff --git a/zproject/email_backends.py b/zproject/email_backends.py
index 2856cb908a0..5bbd4062538 100644
--- a/zproject/email_backends.py
+++ b/zproject/email_backends.py
@@ -2,7 +2,7 @@
import configparser
import logging
from email.message import Message
-from typing import MutableSequence, Sequence, Union
+from typing import MutableSequence, Sequence
from django.conf import settings
from django.core.mail import EmailMultiAlternatives
@@ -37,7 +37,7 @@ class EmailLogBackEnd(EmailBackend):
@staticmethod
def log_email(email: EmailMessage) -> None:
"""Used in development to record sent emails in a nice HTML log"""
- html_message: Union[bytes, EmailMessage, Message, str] = "Missing HTML message"
+ html_message: bytes | EmailMessage | Message | str = "Missing HTML message"
assert isinstance(email, EmailMultiAlternatives)
if len(email.alternatives) > 0:
html_message = email.alternatives[0][0]
diff --git a/zproject/sentry.py b/zproject/sentry.py
index e274c1ad418..84c77d879ab 100644
--- a/zproject/sentry.py
+++ b/zproject/sentry.py
@@ -1,5 +1,5 @@
import os
-from typing import TYPE_CHECKING, Any, Optional, Union
+from typing import TYPE_CHECKING, Any, Optional
import sentry_sdk
from django.utils.translation import override as override_language
@@ -50,7 +50,7 @@ def add_context(event: "Event", hint: "Hint") -> Optional["Event"]:
return event
-def traces_sampler(sampling_context: dict[str, Any]) -> Union[float, bool]:
+def traces_sampler(sampling_context: dict[str, Any]) -> float | bool:
from django.conf import settings
queue = sampling_context.get("queue")
@@ -63,7 +63,7 @@ def traces_sampler(sampling_context: dict[str, Any]) -> Union[float, bool]:
return settings.SENTRY_TRACE_RATE
-def setup_sentry(dsn: Optional[str], environment: str) -> None:
+def setup_sentry(dsn: str | None, environment: str) -> None:
from django.conf import settings
if not dsn:
diff --git a/zproject/settings_types.py b/zproject/settings_types.py
index c14d0a16d16..d448c24a4ce 100644
--- a/zproject/settings_types.py
+++ b/zproject/settings_types.py
@@ -1,4 +1,4 @@
-from typing import Optional, TypedDict
+from typing import TypedDict
class JwtAuthKey(TypedDict):
@@ -31,9 +31,9 @@ class SAMLIdPConfigDict(TypedDict, total=False):
class OIDCIdPConfigDict(TypedDict, total=False):
oidc_url: str
display_name: str
- display_icon: Optional[str]
+ display_icon: str | None
client_id: str
- secret: Optional[str]
+ secret: str | None
auto_signup: bool
diff --git a/zproject/template_loaders.py b/zproject/template_loaders.py
index 37a2132088f..696c2b15002 100644
--- a/zproject/template_loaders.py
+++ b/zproject/template_loaders.py
@@ -1,5 +1,4 @@
from pathlib import Path
-from typing import Union
from django.template.loaders import app_directories
from typing_extensions import override
@@ -7,11 +6,11 @@ from typing_extensions import override
class TwoFactorLoader(app_directories.Loader):
@override
- def get_dirs(self) -> list[Union[str, Path]]:
+ def get_dirs(self) -> list[str | Path]:
dirs = super().get_dirs()
# app_directories.Loader returns only a list of
# Path objects by calling get_app_template_dirs
- two_factor_dirs: list[Union[str, Path]] = []
+ two_factor_dirs: list[str | Path] = []
for d in dirs:
assert isinstance(d, Path)
if d.match("two_factor/*"):
diff --git a/zproject/test_extra_settings.py b/zproject/test_extra_settings.py
index 483b593d893..01c31fa9a1b 100644
--- a/zproject/test_extra_settings.py
+++ b/zproject/test_extra_settings.py
@@ -1,5 +1,4 @@
import os
-from typing import Optional
import ldap
from django_auth_ldap.config import LDAPSearch
@@ -155,8 +154,8 @@ HOME_NOT_LOGGED_IN = "/login/"
LOGIN_URL = "/accounts/login/"
# If dev_settings.py found a key or cert file to use here, ignore it.
-APNS_TOKEN_KEY_FILE: Optional[str] = None
-APNS_CERT_FILE: Optional[str] = None
+APNS_TOKEN_KEY_FILE: str | None = None
+APNS_CERT_FILE: str | None = None
# By default will not send emails when login occurs.
# Explicitly set this to True within tests that must have this on.
@@ -202,7 +201,7 @@ BIG_BLUE_BUTTON_URL = "https://bbb.example.com/bigbluebutton/"
# By default two factor authentication is disabled in tests.
# Explicitly set this to True within tests that must have this on.
TWO_FACTOR_AUTHENTICATION_ENABLED = False
-PUSH_NOTIFICATION_BOUNCER_URL: Optional[str] = None
+PUSH_NOTIFICATION_BOUNCER_URL: str | None = None
DEVELOPMENT_DISABLE_PUSH_BOUNCER_DOMAIN_CHECK = False
# Logging the emails while running the tests adds them
@@ -258,8 +257,8 @@ RATE_LIMITING_RULES: dict[str, list[tuple[int, int]]] = {
"sends_email_by_remote_server": [],
}
-CLOUD_FREE_TRIAL_DAYS: Optional[int] = None
-SELF_HOSTING_FREE_TRIAL_DAYS: Optional[int] = None
+CLOUD_FREE_TRIAL_DAYS: int | None = None
+SELF_HOSTING_FREE_TRIAL_DAYS: int | None = None
SCIM_CONFIG: dict[str, SCIMConfigDict] = {
"zulip": {
diff --git a/zproject/urls.py b/zproject/urls.py
index 41dd6497b4b..a7bed3f1575 100644
--- a/zproject/urls.py
+++ b/zproject/urls.py
@@ -1,5 +1,4 @@
import os
-from typing import Union
from django.conf import settings
from django.conf.urls import include
@@ -632,7 +631,7 @@ i18n_urls = [
]
# Make a copy of i18n_urls so that they appear without prefix for english
-urls: list[Union[URLPattern, URLResolver]] = list(i18n_urls)
+urls: list[URLPattern | URLResolver] = list(i18n_urls)
# Include the dual-use patterns twice
urls += [