Skip to content

Commit 9d8748a

Browse files
authored
Avoid unnecessary typing imports (#199)
- Use collection keyword instead of typing.{Dict|List|Tuple|Set} - replace typing.Union with `|`
1 parent 39c41e3 commit 9d8748a

File tree

5 files changed

+34
-36
lines changed

5 files changed

+34
-36
lines changed

jbi/__init__.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,6 @@
44
This part of the code is not aware of the HTTP context it runs in.
55
"""
66
from enum import Enum
7-
from typing import Dict, Tuple
87

98

109
class Operation(str, Enum):
@@ -22,4 +21,4 @@ class Operation(str, Enum):
2221
LINK = "link"
2322

2423

25-
ActionResult = Tuple[bool, Dict]
24+
ActionResult = tuple[bool, dict]

jbi/log.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,6 @@
66
import sys
77
import time
88
from datetime import datetime
9-
from typing import Dict
109

1110
from fastapi import Request
1211

@@ -46,7 +45,7 @@
4645

4746
def format_request_summary_fields(
4847
request: Request, request_time: float, status_code: int
49-
) -> Dict:
48+
) -> dict:
5049
"""Prepare Fields for Mozlog request summary"""
5150

5251
current_time = time.time()

jbi/models.py

Lines changed: 26 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
import warnings
1010
from inspect import signature
1111
from types import ModuleType
12-
from typing import Any, Callable, Dict, List, Literal, Mapping, Optional, Set, Union
12+
from typing import Any, Callable, Literal, Mapping, Optional
1313
from urllib.parse import ParseResult, urlparse
1414

1515
from pydantic import BaseModel, EmailStr, Field, PrivateAttr, root_validator, validator
@@ -30,13 +30,13 @@ class Action(YamlModel):
3030
whiteboard_tag: str
3131
module: str = "jbi.actions.default"
3232
# TODO: Remove the tbd literal option when all actions have contact info # pylint: disable=fixme
33-
contact: Union[EmailStr, List[EmailStr], Literal["tbd"]]
33+
contact: EmailStr | list[EmailStr] | Literal["tbd"]
3434
description: str
3535
enabled: bool = False
3636
allow_private: bool = False
3737
parameters: dict = {}
3838
_caller: Callable = PrivateAttr(default=None)
39-
_required_jira_permissions: Set[str] = PrivateAttr(default=None)
39+
_required_jira_permissions: set[str] = PrivateAttr(default=None)
4040

4141
@property
4242
def caller(self) -> Callable:
@@ -48,7 +48,7 @@ def caller(self) -> Callable:
4848
return self._caller
4949

5050
@property
51-
def required_jira_permissions(self) -> Set[str]:
51+
def required_jira_permissions(self) -> set[str]:
5252
"""Return the required Jira permissions for this action to be executed."""
5353
if not self._required_jira_permissions:
5454
action_module: ModuleType = importlib.import_module(self.module)
@@ -61,7 +61,7 @@ def validate_action_config(cls, values): # pylint: disable=no-self-argument
6161
"""Validate action: exists, has init function, and has expected params"""
6262
try:
6363
module: str = values["module"] # type: ignore
64-
action_parameters: Optional[Dict[str, Any]] = values["parameters"]
64+
action_parameters: Optional[dict[str, Any]] = values["parameters"]
6565
action_module: ModuleType = importlib.import_module(module)
6666
if not action_module:
6767
raise TypeError("Module is not found.")
@@ -81,7 +81,7 @@ class Actions(YamlModel):
8181
Actions is the container model for the list of actions in the configuration file
8282
"""
8383

84-
__root__: List[Action] = Field(..., min_items=1)
84+
__root__: list[Action] = Field(..., min_items=1)
8585

8686
@functools.cached_property
8787
def by_tag(self) -> Mapping[str, Action]:
@@ -102,7 +102,7 @@ def get(self, tag: Optional[str]) -> Optional[Action]:
102102
return self.by_tag.get(tag.lower()) if tag else None
103103

104104
@functools.cached_property
105-
def configured_jira_projects_keys(self) -> Set[str]:
105+
def configured_jira_projects_keys(self) -> set[str]:
106106
"""Return the list of Jira project keys from all configured actions"""
107107
return {
108108
action.parameters["jira_project_key"]
@@ -112,7 +112,7 @@ def configured_jira_projects_keys(self) -> Set[str]:
112112

113113
@validator("__root__")
114114
def validate_actions( # pylint: disable=no-self-argument
115-
cls, actions: List[Action]
115+
cls, actions: list[Action]
116116
):
117117
"""
118118
Inspect the list of actions:
@@ -160,11 +160,11 @@ class BugzillaWebhookEvent(BaseModel):
160160
action: str
161161
time: Optional[datetime.datetime]
162162
user: Optional[BugzillaWebhookUser]
163-
changes: Optional[List[BugzillaWebhookEventChange]]
163+
changes: Optional[list[BugzillaWebhookEventChange]]
164164
target: Optional[str]
165165
routing_key: Optional[str]
166166

167-
def changed_fields(self) -> Optional[List[str]]:
167+
def changed_fields(self) -> Optional[list[str]]:
168168
"""Returns the names of changed fields in a bug"""
169169
if self.changes:
170170
return [c.field for c in self.changes]
@@ -184,7 +184,7 @@ class BugzillaWebhookAttachment(BaseModel):
184184
creation_time: Optional[datetime.datetime]
185185
description: Optional[str]
186186
file_name: Optional[str]
187-
flags: Optional[List]
187+
flags: Optional[list]
188188
id: int
189189
is_obsolete: Optional[bool]
190190
is_patch: Optional[bool]
@@ -211,34 +211,34 @@ class BugzillaBug(BaseModel):
211211
product: Optional[str]
212212
component: Optional[str]
213213
whiteboard: Optional[str]
214-
keywords: Optional[List]
215-
flags: Optional[List]
216-
groups: Optional[List]
214+
keywords: Optional[list]
215+
flags: Optional[list]
216+
groups: Optional[list]
217217
status: Optional[str]
218218
resolution: Optional[str]
219-
see_also: Optional[List]
219+
see_also: Optional[list]
220220
summary: Optional[str]
221221
severity: Optional[str]
222222
priority: Optional[str]
223223
creator: Optional[str]
224224
assigned_to: Optional[str]
225225
comment: Optional[BugzillaWebhookComment]
226226

227-
def get_whiteboard_as_list(self) -> List[str]:
227+
def get_whiteboard_as_list(self) -> list[str]:
228228
"""Convert string whiteboard into list, splitting on ']' and removing '['."""
229229
if self.whiteboard is not None:
230230
split_list = self.whiteboard.replace("[", "").split("]")
231231
return [x.strip() for x in split_list if x not in ["", " "]]
232232
return []
233233

234-
def get_whiteboard_with_brackets_as_list(self) -> List[str]:
234+
def get_whiteboard_with_brackets_as_list(self) -> list[str]:
235235
"""Convert string whiteboard into list, splitting on ']' and removing '['; then re-adding."""
236236
wb_list = self.get_whiteboard_as_list()
237237
if wb_list is not None and len(wb_list) > 0:
238238
return [f"[{element}]" for element in wb_list]
239239
return []
240240

241-
def get_jira_labels(self) -> List[str]:
241+
def get_jira_labels(self) -> list[str]:
242242
"""
243243
whiteboard labels are added as a convenience for users to search in jira;
244244
bugzilla is an expected label in Jira
@@ -251,9 +251,9 @@ def get_jira_labels(self) -> List[str]:
251251

252252
return ["bugzilla"] + wb_list + wb_bracket_list
253253

254-
def get_potential_whiteboard_config_list(self) -> List[str]:
254+
def get_potential_whiteboard_config_list(self) -> list[str]:
255255
"""Get all possible tags from `whiteboard` field"""
256-
converted_list: List = []
256+
converted_list: list = []
257257
for whiteboard in self.get_whiteboard_as_list():
258258
first_tag = whiteboard.strip().lower().split(sep="-", maxsplit=1)[0]
259259
if first_tag:
@@ -266,7 +266,7 @@ def issue_type(self) -> str:
266266
type_map: dict = {"enhancement": "Task", "task": "Task", "defect": "Bug"}
267267
return type_map.get(self.type, "Task")
268268

269-
def map_as_jira_issue(self) -> Dict:
269+
def map_as_jira_issue(self) -> dict:
270270
"""Extract bug info as jira issue dictionary"""
271271
return {
272272
"summary": self.summary,
@@ -304,7 +304,7 @@ def extract_from_see_also(self):
304304

305305
def lookup_action(self, actions: Actions) -> Action:
306306
"""Find first matching action from bug's whiteboard list"""
307-
tags: List[str] = self.get_potential_whiteboard_config_list()
307+
tags: list[str] = self.get_potential_whiteboard_config_list()
308308
for tag in tags:
309309
if action := actions.get(tag):
310310
return action
@@ -354,10 +354,10 @@ def map_as_comments(
354354
self,
355355
status_log_enabled: bool = True,
356356
assignee_log_enabled: bool = True,
357-
) -> List[str]:
357+
) -> list[str]:
358358
"""Extract update dict and comment list from Webhook Event"""
359359

360-
comments: List = []
360+
comments: list = []
361361
bug: BugzillaBug = self.bug # type: ignore
362362

363363
if self.event.changes:
@@ -396,5 +396,5 @@ def bugzilla_object(self) -> BugzillaBug:
396396
class BugzillaApiResponse(BaseModel):
397397
"""Bugzilla Response Object"""
398398

399-
faults: Optional[List]
400-
bugs: Optional[List[BugzillaBug]]
399+
faults: Optional[list]
400+
bugs: Optional[list[BugzillaBug]]

jbi/router.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
Core FastAPI app (setup, middleware)
33
"""
44
from pathlib import Path
5-
from typing import Dict, List, Optional
5+
from typing import Optional
66

77
from fastapi import APIRouter, Body, Depends, Request, Response
88
from fastapi.encoders import jsonable_encoder
@@ -87,7 +87,7 @@ def get_whiteboard_tags(
8787
@router.get("/jira_projects/")
8888
def get_jira_projects():
8989
"""API for viewing projects that are currently accessible by API"""
90-
visible_projects: List[Dict] = jira_visible_projects()
90+
visible_projects: list[dict] = jira_visible_projects()
9191
return [project["key"] for project in visible_projects]
9292

9393

jbi/services.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33

44
import concurrent.futures
55
import logging
6-
from typing import TYPE_CHECKING, Dict, List
6+
from typing import TYPE_CHECKING
77

88
import backoff
99
import bugzilla as rh_bugzilla
@@ -20,7 +20,7 @@
2020
logger = logging.getLogger(__name__)
2121

2222

23-
ServiceHealth = Dict[str, bool]
23+
ServiceHealth = dict[str, bool]
2424

2525

2626
class InstrumentedClient:
@@ -77,10 +77,10 @@ def get_jira():
7777
)
7878

7979

80-
def jira_visible_projects(jira=None) -> List[Dict]:
80+
def jira_visible_projects(jira=None) -> list[dict]:
8181
"""Return list of projects that are visible with the configured Jira credentials"""
8282
jira = jira or get_jira()
83-
projects: List[Dict] = jira.projects(included_archived=None)
83+
projects: list[dict] = jira.projects(included_archived=None)
8484
return projects
8585

8686

0 commit comments

Comments
 (0)