Skip to content

Commit

Permalink
chore: update typehints via __future__.annotations
Browse files Browse the repository at this point in the history
This commit changes all typehints from "old" ways of typehinting
(type comments, `Union`, etc.) to more modern ways, like using |
notation for unions, etc.
  • Loading branch information
JasonGrace2282 committed Aug 12, 2024
1 parent edec103 commit 5e627d4
Show file tree
Hide file tree
Showing 17 changed files with 146 additions and 124 deletions.
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from __future__ import annotations

import csv
import sys

Expand Down Expand Up @@ -54,7 +56,7 @@ def generate_single_username(

return f"{graduating_year}{first_stripped[0]}{last_stripped[:7]}".lower()

def find_next_available_username(self, used_username: str, username_set: set = None) -> str:
def find_next_available_username(self, used_username: str, username_set: set[str] | None = None) -> str:
"""Find the next available username.
Args:
Expand Down
5 changes: 3 additions & 2 deletions intranet/apps/eighth/forms/admin/activities.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from __future__ import annotations

import logging
from typing import List # noqa

from django import forms, http
from django.contrib.auth import get_user_model
Expand All @@ -11,7 +12,7 @@


class ActivityDisplayField(forms.ModelChoiceField):
cancelled_acts = None # type: List[EighthActivity]
cancelled_acts: list[EighthActivity] | None = None

def __init__(self, *args, **kwargs):
if "block" in kwargs:
Expand Down
81 changes: 42 additions & 39 deletions intranet/apps/eighth/models.py

Large diffs are not rendered by default.

2 changes: 2 additions & 0 deletions intranet/apps/eighth/tasks.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from __future__ import annotations

import calendar
import datetime
from typing import Collection
Expand Down
9 changes: 5 additions & 4 deletions intranet/apps/eighth/views/admin/groups.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
from __future__ import annotations

import csv
import logging
import re
from typing import List, Optional

from cacheops import invalidate_model, invalidate_obj
from django import http
Expand Down Expand Up @@ -155,7 +156,7 @@ def get_file_string(fileobj):
return filetext


def get_user_info(key: str, val) -> Optional[List[User]]:
def get_user_info(key: str, val) -> list[User] | None:
if key in ["username", "id"]:
try:
u = get_user_model().objects.filter(**{key: val})
Expand Down Expand Up @@ -199,7 +200,7 @@ def handle_group_input(filetext: str):
return find_users_input(lines)


def find_users_input(lines: List[str]):
def find_users_input(lines: list[str]):
sure_users = []
unsure_users = []
for line in lines:
Expand Down Expand Up @@ -486,7 +487,7 @@ def eighth_admin_signup_group_action(request, group_id, schact_id):
)


def eighth_admin_perform_group_signup(*, group_id: int, schact_id: int, request: Optional[http.HttpRequest], skip_users: set):
def eighth_admin_perform_group_signup(*, group_id: int, schact_id: int, request: http.HttpRequest | None, skip_users: set):
"""Performs sign up of all users in a specific group up for a
specific scheduled activity.
Expand Down
5 changes: 3 additions & 2 deletions intranet/apps/eighth/views/admin/hybrid.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from __future__ import annotations

import logging
from typing import Optional

from django import http
from django.contrib import messages
Expand Down Expand Up @@ -212,7 +213,7 @@ def eighth_admin_signup_group_action_hybrid(request, group_id, schact_virtual_id
)


def eighth_admin_perform_group_signup(*, group_id: int, schact_virtual_id: int, schact_person_id: int, request: Optional[http.HttpRequest]):
def eighth_admin_perform_group_signup(*, group_id: int, schact_virtual_id: int, schact_person_id: int, request: http.HttpRequest | None):
"""Performs sign up of all users in a specific group up for a
specific scheduled activity.
Expand Down
4 changes: 2 additions & 2 deletions intranet/apps/features/helpers.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from typing import Optional
from __future__ import annotations


def get_feature_context(request) -> Optional[str]:
def get_feature_context(request) -> str | None:
"""Given a Django request, returns the 'context' that should be used to select feature
announcements to display (one of ``dashboard``, ``login``, ``eighth_signup``, or ``None``).
Expand Down
10 changes: 6 additions & 4 deletions intranet/apps/notifications/emails.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
from __future__ import annotations

import logging
from typing import Collection, Mapping
from typing import Mapping, MutableSequence

from django.conf import settings
from django.core.mail import EmailMultiAlternatives
Expand All @@ -13,11 +15,11 @@ def email_send(
html_template: str,
data: Mapping[str, object],
subject: str,
emails: Collection[str], # pylint: disable=unsubscriptable-object
headers: Mapping[str, str] = None, # pylint: disable=unsubscriptable-object
emails: MutableSequence[str],
headers: Mapping[str, str] | None = None,
bcc: bool = False,
*,
custom_logger: logging.Logger = None,
custom_logger: logging.Logger | None = None,
) -> EmailMultiAlternatives:
"""Send an HTML/Plaintext email with the following fields.
If we are not in production and settings.FORCE_EMAIL_SEND is not set, does not actually send the email
Expand Down
16 changes: 9 additions & 7 deletions intranet/apps/printing/views.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
from __future__ import annotations

import logging
import math
import os
import re
import subprocess
import tempfile
from io import BytesIO
from typing import Dict, Optional

import magic
from django.conf import settings
Expand Down Expand Up @@ -62,14 +63,15 @@ def set_user_ratelimit_status(username: str) -> None:
cache.incr(cache_key)


def get_printers() -> Dict[str, str]:
def get_printers() -> dict[str, str] | list:
"""Returns a dictionary mapping name:description for available printers.
This requires that a CUPS client be configured on the server.
Otherwise, this returns an empty dictionary.
Returns:
A dictionary mapping name:description for available printers.
A dictionary mapping name:description for available printers, or
an empty list if cups isn't installed or lpstat fails
"""

key = "printing:printers"
Expand Down Expand Up @@ -116,7 +118,7 @@ def get_printers() -> Dict[str, str]:
return printers


def convert_soffice(tmpfile_name: str) -> Optional[str]:
def convert_soffice(tmpfile_name: str) -> str | None:
"""Converts a doc or docx to a PDF with soffice.
Args:
Expand Down Expand Up @@ -147,7 +149,7 @@ def convert_soffice(tmpfile_name: str) -> Optional[str]:
return None


def convert_pdf(tmpfile_name: str, cmdname: str = "ps2pdf") -> Optional[str]:
def convert_pdf(tmpfile_name: str, cmdname: str = "ps2pdf") -> str | None:
new_name = f"{tmpfile_name}.pdf"
try:
output = subprocess.check_output([cmdname, tmpfile_name, new_name], stderr=subprocess.STDOUT, universal_newlines=True)
Expand Down Expand Up @@ -209,7 +211,7 @@ def get_mimetype(tmpfile_name: str) -> str:
return mimetype


def convert_file(tmpfile_name: str, orig_fname: str) -> Optional[str]:
def convert_file(tmpfile_name: str, orig_fname: str) -> str | None:
detected = get_mimetype(tmpfile_name)

add_breadcrumb(category="printing", message=f"Detected file type {detected}", level="debug")
Expand Down Expand Up @@ -241,7 +243,7 @@ def convert_file(tmpfile_name: str, orig_fname: str) -> Optional[str]:
raise InvalidInputPrintingError(f"Invalid file type {detected}")


def check_page_range(page_range: str, max_pages: int) -> Optional[int]:
def check_page_range(page_range: str, max_pages: int) -> int | None:
"""Returns the number of pages included in the range, or None if it is an invalid range.
Args:
Expand Down
5 changes: 3 additions & 2 deletions intranet/apps/signage/views.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from __future__ import annotations

import datetime
import logging
from typing import Optional

from django import http
from django.conf import settings
Expand All @@ -20,7 +21,7 @@
logger = logging.getLogger(__name__)


def check_internal_ip(request) -> Optional[HttpResponse]:
def check_internal_ip(request) -> HttpResponse | None:
"""
A method to determine if a request is allowed to load a signage page.
Expand Down
6 changes: 3 additions & 3 deletions intranet/apps/templatetags/paginate.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from typing import List, Union
from __future__ import annotations

from django import template

Expand All @@ -13,8 +13,8 @@ def query_transform(request, **kwargs):
return query.urlencode()


@register.filter # TODO: replace return type with list[int | None]
def page_list(paginator, current_page) -> List[Union[int, None]]:
@register.filter
def page_list(paginator, current_page) -> list[int | None]:
"""Pagination
If there is a ``None`` in the output, it should be replaced
Expand Down
Loading

0 comments on commit 5e627d4

Please sign in to comment.