Skip to content

Commit

Permalink
🏷️ [#1718] Update typehints to use PEP585 generics
Browse files Browse the repository at this point in the history
  • Loading branch information
stevenbal committed Mar 18, 2024
1 parent 761f3e2 commit 3a9dbb4
Show file tree
Hide file tree
Showing 73 changed files with 464 additions and 547 deletions.
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import logging
from datetime import date
from typing import List

from django.core.management.base import BaseCommand
from django.db.models.query import QuerySet
from django.urls import reverse

from mail_editor.helpers import find_template
Expand Down Expand Up @@ -37,7 +37,7 @@ def handle(self, *args, **options):
f"The email was sent to the user {receiver} about {actions.count()} expiring actions"
)

def send_email(self, receiver: User, actions: List[Action]):
def send_email(self, receiver: User, actions: QuerySet[Action]):
actions_link = build_absolute_url(reverse("profile:action_list"))
template = find_template("expiring_action")
context = {
Expand Down
8 changes: 4 additions & 4 deletions src/open_inwoner/accounts/views/contactmoments.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import logging
from datetime import datetime
from typing import Optional, TypedDict
from typing import TypedDict

from django.contrib.auth.mixins import AccessMixin
from django.http import Http404, HttpResponseRedirect
Expand Down Expand Up @@ -82,7 +82,7 @@ class KlantContactMomentBaseView(
def get_kcm_data(
self,
kcm: KlantContactMoment,
local_kcm_mapping: Optional[dict[str, KlantContactMomentAnswer]] = None,
local_kcm_mapping: dict[str, KlantContactMomentAnswer] | None = None,
) -> KCMDict:
data = {
"registered_date": kcm.contactmoment.registratiedatum,
Expand Down Expand Up @@ -114,8 +114,8 @@ def get_context_data(self, **kwargs):
def get_kcm_subject(
self,
kcm: KlantContactMoment,
e_suite_subject_code: str,
) -> Optional[str]:
e_suite_subject_code: str | None,
) -> str | None:
"""
Try to determine the subject ('onderwerp') of a contactmoment
"""
Expand Down
7 changes: 3 additions & 4 deletions src/open_inwoner/accounts/views/inbox.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import logging
from typing import List, Optional
from urllib.parse import unquote

from django.contrib.auth.mixins import LoginRequiredMixin
Expand Down Expand Up @@ -91,7 +90,7 @@ def annotate_conversations(self, conversations):
c.other_user_full_name = " ".join(p for p in parts if p)
return conversations

def get_other_user(self, conversations: dict) -> Optional[User]:
def get_other_user(self, conversations: dict) -> User | None:
"""
Return the User instance of the "other user" in the conversation (if any).
"""
Expand All @@ -105,7 +104,7 @@ def get_other_user(self, conversations: dict) -> Optional[User]:

return get_object_or_404(User, uuid=other_user_uuid)

def get_messages(self, other_user: User) -> List[Message]:
def get_messages(self, other_user: User) -> list[Message]:
"""
Returns the messages (MessageType) of the current conversation.
"""
Expand All @@ -127,7 +126,7 @@ def get_status(self, messages: MessageQuerySet) -> str:
return ""
return f"{_('Laatste bericht ontvangen op')} {formats.date_format(messages[-1].created_on)}"

def mark_messages_seen(self, other_user: Optional[User]):
def mark_messages_seen(self, other_user: User | None):
if not other_user:
return

Expand Down
5 changes: 3 additions & 2 deletions src/open_inwoner/accounts/views/profile.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from collections.abc import Generator
from datetime import date
from typing import Any, Generator, Union
from typing import Any

from django.contrib import messages
from django.contrib.auth.mixins import LoginRequiredMixin
Expand Down Expand Up @@ -53,7 +54,7 @@ def crumbs(self):
@staticmethod
def stringify(
items: list, string_func: callable, lump: bool = False
) -> Union[Generator, str]:
) -> Generator | str:
"""
Create string representation(s) of `items` for display
Expand Down
3 changes: 1 addition & 2 deletions src/open_inwoner/accounts/views/registration.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
from typing import Optional
from urllib.parse import unquote

from django.contrib import messages
Expand Down Expand Up @@ -42,7 +41,7 @@ def get_initial(self):

return initial

def get_invite(self) -> Optional[Invite]:
def get_invite(self) -> Invite | None:
"""return Invite model instance if the user registers after accepting invite"""
invite_key = unquote(self.request.GET.get("invite", ""))
if not invite_key:
Expand Down
4 changes: 1 addition & 3 deletions src/open_inwoner/api/pdc/serializers.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
from typing import List

from drf_spectacular.utils import extend_schema_field
from filer.models import File, Image
from rest_framework import serializers
Expand Down Expand Up @@ -129,7 +127,7 @@ class Meta:
model = ProductLocation
fields = ("name", "street", "housenumber", "postcode", "city", "coordinates")

@extend_schema_field(List[str])
@extend_schema_field(list[str])
def get_coordinates(self, obj):
return obj.geometry.coords

Expand Down
3 changes: 1 addition & 2 deletions src/open_inwoner/cms/cases/views/mixins.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import logging
from typing import Optional

from django.contrib.auth.mixins import AccessMixin, LoginRequiredMixin
from django.template.response import TemplateResponse
Expand Down Expand Up @@ -131,7 +130,7 @@ def handle_no_permission(self):

return super().handle_no_permission()

def get_case(self, client, kwargs) -> Optional[Zaak]:
def get_case(self, client, kwargs) -> Zaak | None:
case_uuid = kwargs.get("object_id")
if not case_uuid:
return None
Expand Down
15 changes: 7 additions & 8 deletions src/open_inwoner/cms/cases/views/status.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
import logging
from collections import defaultdict
from datetime import datetime
from typing import List, Optional

from django.conf import settings
from django.contrib import messages
Expand Down Expand Up @@ -61,7 +60,7 @@ class SimpleFile:
name: str
size: int
url: str
created: Optional[datetime] = None
created: datetime | None = None


class OuterCaseDetailView(
Expand Down Expand Up @@ -96,7 +95,7 @@ class InnerCaseDetailView(
template_name = "pages/cases/status_inner.html"
form_class = CaseUploadForm
contact_form_class = CaseContactForm
case: Optional[Zaak] = None
case: Zaak | None = None

def store_statustype_mapping(self, zaaktype_identificatie):
# Filter on ZaakType identificatie to avoid eSuite situation where one statustype
Expand Down Expand Up @@ -255,7 +254,7 @@ def get_context_data(self, **kwargs):

return context

def get_second_status_preview(self, statustypen: list) -> Optional[StatusType]:
def get_second_status_preview(self, statustypen: list) -> StatusType | None:
"""
Get the relevant status type to display preview of second case status
Expand Down Expand Up @@ -535,10 +534,10 @@ def get_initiator_display(case: Zaak) -> str:

@staticmethod
def get_statuses_data(
statuses: List[Status],
statuses: list[Status],
lookup: TranslationLookup,
statustype_config_mapping: Optional[dict] = None,
) -> List[dict]:
statustype_config_mapping: dict | None = None,
) -> list[dict]:
return [
{
"date": s.datum_status_gezet,
Expand Down Expand Up @@ -578,7 +577,7 @@ def get_statuses_data(
]

@staticmethod
def get_case_document_files(case: Zaak, client: ZakenClient) -> List[SimpleFile]:
def get_case_document_files(case: Zaak, client: ZakenClient) -> list[SimpleFile]:
if not client:
return []

Expand Down
6 changes: 2 additions & 4 deletions src/open_inwoner/cms/tests/cms_tools.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
from typing import Tuple

from django.conf import settings
from django.contrib.auth.models import AnonymousUser
from django.test import RequestFactory
Expand Down Expand Up @@ -30,7 +28,7 @@ def create_homepage():
return p


def _init_plugin(plugin_class, plugin_data=None) -> Tuple[dict, str]:
def _init_plugin(plugin_class, plugin_data=None) -> tuple[dict, str]:
if plugin_data is None:
plugin_data = dict()

Expand Down Expand Up @@ -60,7 +58,7 @@ def get_request(*, user=None, session_vars=None):

def render_plugin(
plugin_class, plugin_data=None, *, user=None, session_vars=None
) -> Tuple[str, dict]:
) -> tuple[str, dict]:
model_instance = _init_plugin(plugin_class, plugin_data)
request = get_request(user=user, session_vars=session_vars)

Expand Down
7 changes: 3 additions & 4 deletions src/open_inwoner/components/templatetags/messages_tags.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import datetime
from typing import List, Union

from django import template
from django.forms import Form
Expand Down Expand Up @@ -39,14 +38,14 @@ def messages(
- subject: string | The title that will be displayed above the messages.
"""

def get_dates(message_list: MessageQuerySet) -> List[datetime.date]:
def get_dates(message_list: MessageQuerySet) -> list[datetime.date]:
"""
Returns a list of dates to render message(s) for.
"""
dates = sorted(set(m.created_on.date() for m in message_list))
return dates

def get_date_text(date) -> Union[str, datetime.date]:
def get_date_text(date) -> str | datetime.date:
""" "
Formats a date to a text value (if required).
"""
Expand All @@ -59,7 +58,7 @@ def get_date_text(date) -> Union[str, datetime.date]:

return date

def get_messages_by_date(message_list: MessageQuerySet) -> List[dict]:
def get_messages_by_date(message_list: MessageQuerySet) -> list[dict]:
"""
Returns a dict containing the date, it's text value and the messages sent on that date.
"""
Expand Down
18 changes: 9 additions & 9 deletions src/open_inwoner/components/templatetags/table_tags.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from typing import List, Optional, TypedDict
from typing import TypedDict

from django import template
from django.urls import reverse
Expand All @@ -19,12 +19,12 @@ class TableHeaderConfig(TypedDict):


class TableRowConfig(TypedDict):
headers: List[TableHeaderConfig]
cells: List[TableCellConfig]
headers: list[TableHeaderConfig]
cells: list[TableCellConfig]


class TableConfig(TypedDict):
body: List[TableRowConfig]
body: list[TableRowConfig]


@register.inclusion_tag("components/table/table.html")
Expand All @@ -48,14 +48,14 @@ def case_table(case: dict, **kwargs) -> dict:
"""

# build rows for data we actually have
rows: List[TableRowConfig] = []
rows: list[TableRowConfig] = []

def add_row_if_not_empty(key, label):
value = case.get(key)
if not value:
return

row = {"headers": [{"text": label}], "cells": [{"text": value}]}
row: TableRowConfig = {"headers": [{"text": label}], "cells": [{"text": value}]}

rows.append(row)

Expand All @@ -74,7 +74,7 @@ def add_row_if_not_empty(key, label):


@register.inclusion_tag("components/table/table.html")
def contactmoment_table(kcm: KCMDict, zaak: Optional[Zaak] = None, **kwargs) -> dict:
def contactmoment_table(kcm: KCMDict, zaak: Zaak | None = None, **kwargs) -> dict:
"""
Renders a table below the dashboard for additional values related to a Zaak (case).
Expand All @@ -89,14 +89,14 @@ def contactmoment_table(kcm: KCMDict, zaak: Optional[Zaak] = None, **kwargs) ->
"""

# build rows for data we actually have
rows: List[TableRowConfig] = []
rows: list[TableRowConfig] = []

def add_row_if_not_empty(key, label):
value = kcm.get(key)
if not value:
return

row = {"headers": [{"text": label}], "cells": [{"text": value}]}
row: TableRowConfig = {"headers": [{"text": label}], "cells": [{"text": value}]}

rows.append(row)

Expand Down
4 changes: 1 addition & 3 deletions src/open_inwoner/components/tests/abstract.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
from typing import Union

from django.template import Context, Template
from django.test import RequestFactory

Expand Down Expand Up @@ -335,7 +333,7 @@ def assertContents(self, args={}, data={}, contents_context={}) -> str:
self.assertIn(contents_html, html)
return contents_html

def get_contents(self, context: Union[Context, dict] = {}) -> str:
def get_contents(self, context: Context | dict = {}) -> str:
"""
Renders contents HTML.
Expand Down
6 changes: 2 additions & 4 deletions src/open_inwoner/components/utils.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
from typing import Optional

from django import template
from django.template import Context, Template
from django.template.library import InclusionNode, parse_bits
Expand Down Expand Up @@ -163,7 +161,7 @@ def __call__(self, **kwargs) -> str:
"""
return self.render(kwargs)

def render(self, tag_args: Optional[dict] = None) -> str:
def render(self, tag_args: dict | None = None) -> str:
"""
Renders the template tag with arguments.
Expand All @@ -178,7 +176,7 @@ def render(self, tag_args: Optional[dict] = None) -> str:
template = self.get_template(tag_args)
return template.render(context)

def get_template(self, tag_args: Optional[dict] = None):
def get_template(self, tag_args: dict | None = None):
"""
Returns the (Django) Template instance (in order to render the tag).
A templates str is constructed and then passed to a django.template.Template, the resulting instance is
Expand Down
3 changes: 1 addition & 2 deletions src/open_inwoner/configurations/models.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import os
from typing import Optional

from django.conf import settings
from django.contrib.flatpages.models import FlatPage
Expand Down Expand Up @@ -591,7 +590,7 @@ def openid_enabled_for_admin(self):
def openid_enabled_for_regular_users(self):
return self.openid_display == OpenIDDisplayChoices.regular

def get_help_text(self, request) -> Optional[str]:
def get_help_text(self, request) -> str | None:
match = request.resolver_match
path = request.get_full_path()
if not match:
Expand Down
6 changes: 2 additions & 4 deletions src/open_inwoner/custom_csp/middleware.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
from typing import Dict, List

from .models import CSPSetting


Expand All @@ -12,7 +10,7 @@ class UpdateCSPMiddleware:
def __init__(self, get_response):
self.get_response = get_response

def get_csp_update(self) -> Dict[str, List[str]]:
def get_csp_update(self) -> dict[str, list[str]]:
update = dict()

# known standard stuff from commonn settings
Expand Down Expand Up @@ -45,7 +43,7 @@ def __call__(self, request):
return response


def _merge_list_values(left, right) -> List[str]:
def _merge_list_values(left, right) -> list[str]:
# combine strings or lists to a list with unique values
if isinstance(left, str):
left = [left]
Expand Down
Loading

0 comments on commit 3a9dbb4

Please sign in to comment.