Skip to content

Commit ae205d7

Browse files
authored
Enable pyupgrade lint rules and autofix errors. (#1246)
* Enable pyupgrade lint rules and autofix errors. * Use appropriate exception type. * Update ruff.toml
1 parent 427a188 commit ae205d7

55 files changed

Lines changed: 228 additions & 253 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

lambdas/ack_backend/src/update_ack_file.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
import os
55
import time
66
from copy import deepcopy
7-
from datetime import datetime, timezone
7+
from datetime import UTC, datetime
88
from io import BytesIO, StringIO
99

1010
from botocore.exceptions import ClientError
@@ -40,7 +40,7 @@
4040

4141

4242
def _generated_date() -> str:
43-
return datetime.now(timezone.utc).isoformat()[:-13] + ".000Z"
43+
return datetime.now(UTC).isoformat()[:-13] + ".000Z"
4444

4545

4646
def _make_ack_data_dict_identifier_information(

lambdas/ack_backend/tests/utils/utils_for_ack_backend_tests.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@
22

33
import json
44
from copy import deepcopy
5-
from typing import Optional
65

76
from boto3 import client as boto3_client
87

@@ -12,7 +11,7 @@
1211
firehose_client = boto3_client("firehose", region_name=REGION_NAME)
1312

1413

15-
def add_audit_entry_to_table(dynamodb_client, batch_event_message_id: str, record_count: Optional[int] = None) -> None:
14+
def add_audit_entry_to_table(dynamodb_client, batch_event_message_id: str, record_count: int | None = None) -> None:
1615
"""Add an entry to the audit table"""
1716
audit_table_entry = {"status": {"S": "Preprocessed"}, "message_id": {"S": batch_event_message_id}}
1817

lambdas/backend/src/controller/aws_apig_event_utils.py

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,5 @@
11
"""Utility module for interacting with the AWS API Gateway event provided to controllers"""
22

3-
from typing import Optional
4-
53
from aws_lambda_typing.events import APIGatewayProxyEventV1
64

75
from controller.constants import E_TAG_HEADER_NAME, SUPPLIER_SYSTEM_HEADER_NAME
@@ -19,7 +17,7 @@ def get_path_parameter(event: APIGatewayProxyEventV1, param_name: str) -> str:
1917

2018
def get_supplier_system_header(event: APIGatewayProxyEventV1) -> str:
2119
"""Retrieves the supplier system header from the API Gateway event. Raises an Unauthorized error if not present."""
22-
supplier_system: Optional[str] = dict_utils.get_field(dict(event), "headers", SUPPLIER_SYSTEM_HEADER_NAME)
20+
supplier_system: str | None = dict_utils.get_field(dict(event), "headers", SUPPLIER_SYSTEM_HEADER_NAME)
2321

2422
if supplier_system is None:
2523
# SupplierSystem header must be provided for looking up permissions
@@ -31,7 +29,7 @@ def get_supplier_system_header(event: APIGatewayProxyEventV1) -> str:
3129
def get_resource_version_header(event: APIGatewayProxyEventV1) -> str:
3230
"""Retrieves the resource version header from the API Gateway event. Raises a ResourceVersionNotProvided if not
3331
present."""
34-
resource_version_header: Optional[str] = dict_utils.get_field(dict(event), "headers", E_TAG_HEADER_NAME)
32+
resource_version_header: str | None = dict_utils.get_field(dict(event), "headers", E_TAG_HEADER_NAME)
3533

3634
if resource_version_header is None:
3735
raise ResourceVersionNotProvidedError(resource_type="Immunization")

lambdas/backend/src/controller/aws_apig_response_utils.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,9 @@
11
"""Utility module providing helper functions for dealing with response formats for AWS API Gateway"""
22

33
import json
4-
from typing import Optional
54

65

7-
def create_response(status_code: int, body: Optional[dict | str] = None, headers: Optional[dict] = None) -> dict:
6+
def create_response(status_code: int, body: dict | str | None = None, headers: dict | None = None) -> dict:
87
"""Creates response body as per Lambda -> API Gateway proxy integration"""
98
if body is not None:
109
if isinstance(body, dict):

lambdas/backend/src/controller/fhir_api_exception_handler.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
import functools
44
import uuid
5-
from typing import Callable, Type
5+
from collections.abc import Callable
66

77
from common.clients import logger
88
from common.models.errors import (
@@ -31,7 +31,7 @@
3131
create_operation_outcome,
3232
)
3333

34-
_CUSTOM_EXCEPTION_TO_STATUS_MAP: dict[Type[Exception], int] = {
34+
_CUSTOM_EXCEPTION_TO_STATUS_MAP: dict[type[Exception], int] = {
3535
InconsistentResourceVersionError: 400,
3636
InconsistentIdentifierError: 400, # Identifier refers to the local FHIR identifier composed of system and value.
3737
InconsistentIdError: 400, # ID refers to the top-level ID of the FHIR resource.

lambdas/backend/src/controller/parameter_parser.py

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
import datetime
22
from dataclasses import dataclass, field
3-
from typing import Optional
43

54
from common.models.constants import RedisHashKeys
65
from common.models.utils.generic_utils import nhs_number_mod11_check
@@ -25,9 +24,9 @@
2524
class SearchParams:
2625
patient_identifier: str
2726
immunization_targets: set[str]
28-
date_from: Optional[datetime.date]
29-
date_to: Optional[datetime.date]
30-
include: Optional[str]
27+
date_from: datetime.date | None
28+
date_to: datetime.date | None
29+
include: str | None
3130

3231
def __repr__(self):
3332
return str(self.__dict__)
@@ -111,7 +110,7 @@ def process_mandatory_params(params: dict[str, list[str]]) -> tuple[str, list[st
111110

112111
def process_optional_params(
113112
params: dict[str, list[str]],
114-
) -> tuple[Optional[datetime.date], Optional[datetime.date], Optional[str]]:
113+
) -> tuple[datetime.date | None, datetime.date | None, str | None]:
115114
"""Parse optional params (date.from, date.to, _include).
116115
Raises ParameterExceptionError for any validation error.
117116
"""
@@ -205,7 +204,7 @@ def check_elements_valid(elements: list[str]) -> bool:
205204
return set(elements).issubset({IdentifierSearchElement.ID, IdentifierSearchElement.META})
206205

207206

208-
def validate_and_retrieve_identifier_search_params(params: dict[str, list[str]]) -> tuple[str, Optional[set[str]]]:
207+
def validate_and_retrieve_identifier_search_params(params: dict[str, list[str]]) -> tuple[str, set[str] | None]:
209208
contains_no_patient_vacc_type_params = check_identifier_search_params_contain_no_incorrect_keys(params)
210209

211210
if not contains_no_patient_vacc_type_params:
Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,3 @@
11
def load_string(file_path: str):
2-
with open(file_path, "r", encoding="utf-8") as f:
2+
with open(file_path, encoding="utf-8") as f:
33
return f.read()

lambdas/backend/src/log_structure.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -33,8 +33,8 @@ def _get_operation_outcome(result) -> dict:
3333
operation_outcome = {}
3434
status = "500"
3535
status_code = "Exception"
36-
diagnostics = str()
37-
record = str()
36+
diagnostics = ""
37+
record = ""
3838
if isinstance(result, dict):
3939
status = str(result["statusCode"])
4040
status_code = "Completed successfully"

lambdas/backend/src/repository/fhir_repository.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
import os
22
import time
33
from dataclasses import dataclass
4-
from typing import Optional
54

65
import boto3
76
import botocore.exceptions
@@ -96,7 +95,7 @@ def __init__(self, table: Table):
9695

9796
def get_immunization_by_identifier(
9897
self, identifier: Identifier
99-
) -> tuple[Optional[dict], Optional[ImmunizationRecordMetadata]]:
98+
) -> tuple[dict | None, ImmunizationRecordMetadata | None]:
10099
response = self.table.query(
101100
IndexName="IdentifierGSI",
102101
KeyConditionExpression=Key("IdentifierPK").eq(self._make_identifier_pk(identifier)),
@@ -120,7 +119,7 @@ def get_immunization_by_identifier(
120119

121120
def get_immunization_resource_and_metadata_by_id(
122121
self, imms_id: str, include_deleted: bool = False
123-
) -> tuple[Optional[dict], Optional[ImmunizationRecordMetadata]]:
122+
) -> tuple[dict | None, ImmunizationRecordMetadata | None]:
124123
"""Retrieves the immunization resource and metadata from the VEDS table"""
125124
response = self.table.get_item(Key={"PK": _make_immunization_pk(imms_id)})
126125
item = response.get("Item")

lambdas/backend/src/service/fhir_service.py

Lines changed: 14 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
import logging
44
import os
55
import uuid
6-
from typing import Any, Optional, cast
6+
from typing import Any, cast
77
from uuid import uuid4
88

99
from fhir.resources.R4B.bundle import (
@@ -73,7 +73,7 @@ def __init__(
7373
self.validator = validator
7474

7575
def get_immunization_by_identifier(
76-
self, identifier: Identifier, supplier_name: str, elements: Optional[set[str]]
76+
self, identifier: Identifier, supplier_name: str, elements: set[str] | None
7777
) -> FhirBundle:
7878
"""
7979
Get an Immunization by its ID. Returns a FHIR Bundle containing the search results.
@@ -195,10 +195,10 @@ def search_immunizations(
195195
nhs_number: str,
196196
vaccine_types: set[str],
197197
supplier_system: str,
198-
date_from: Optional[datetime.date],
199-
date_to: Optional[datetime.date],
200-
include: Optional[str],
201-
invalid_immunization_targets: Optional[list[str]] = None,
198+
date_from: datetime.date | None,
199+
date_to: datetime.date | None,
200+
include: str | None,
201+
invalid_immunization_targets: list[str] | None = None,
202202
) -> FhirBundle:
203203
"""
204204
Finds all instances of Immunization(s) for a specified patient for the given specified vaccine type(s).
@@ -301,9 +301,9 @@ def search_immunizations(
301301
def _filter_search_results_by_date_and_status(
302302
self,
303303
immunizations: list[dict],
304-
date_from: Optional[datetime.date],
305-
date_to: Optional[datetime.date],
306-
status: Optional[str],
304+
date_from: datetime.date | None,
305+
date_to: datetime.date | None,
306+
status: str | None,
307307
) -> list[dict]:
308308
return [
309309
immunization
@@ -313,7 +313,7 @@ def _filter_search_results_by_date_and_status(
313313
and validate_has_status(immunization, status)
314314
]
315315

316-
def is_valid_date_from(self, immunization: dict, date_from: Optional[datetime.date]):
316+
def is_valid_date_from(self, immunization: dict, date_from: datetime.date | None):
317317
"""
318318
Returns False if immunization occurrence is earlier than the date_from, or True otherwise
319319
(also returns True if date_from is None)
@@ -327,7 +327,7 @@ def is_valid_date_from(self, immunization: dict, date_from: Optional[datetime.da
327327

328328
return occurrence_datetime.date() >= date_from
329329

330-
def is_valid_date_to(self, immunization: dict, date_to: Optional[datetime.date]):
330+
def is_valid_date_to(self, immunization: dict, date_to: datetime.date | None):
331331
"""
332332
Returns False if immunization occurrence is later than the date_to, or True otherwise
333333
(also returns True if date_to is None)
@@ -343,9 +343,9 @@ def is_valid_date_to(self, immunization: dict, date_to: Optional[datetime.date])
343343

344344
@staticmethod
345345
def make_identifier_search_bundle(
346-
resource: Optional[dict],
347-
version_id: Optional[int],
348-
elements: Optional[set[str]],
346+
resource: dict | None,
347+
version_id: int | None,
348+
elements: set[str] | None,
349349
identifier: Identifier,
350350
base_url: str,
351351
) -> FhirBundle:

0 commit comments

Comments
 (0)