Skip to content

Commit 0af2a3c

Browse files
committed
refactor(parameters): add from __future__ import annotations
and update code according to ruff rules TCH, UP006, UP007, UP037 and FA100.
1 parent 2d59b7a commit 0af2a3c

File tree

5 files changed

+186
-189
lines changed

5 files changed

+186
-189
lines changed

aws_lambda_powertools/utilities/parameters/appconfig.py

Lines changed: 21 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -2,27 +2,29 @@
22
AWS App Config configuration retrieval and caching utility
33
"""
44

5+
from __future__ import annotations
6+
57
import os
68
import warnings
7-
from typing import TYPE_CHECKING, Dict, Optional, Union
9+
from typing import TYPE_CHECKING
810

911
import boto3
10-
from botocore.config import Config
11-
12-
from aws_lambda_powertools.utilities.parameters.types import TransformOptions
13-
from aws_lambda_powertools.warnings import PowertoolsDeprecationWarning
14-
15-
if TYPE_CHECKING:
16-
from mypy_boto3_appconfigdata.client import AppConfigDataClient
1712

1813
from aws_lambda_powertools.shared import constants
1914
from aws_lambda_powertools.shared.functions import (
2015
resolve_env_var_choice,
2116
resolve_max_age,
2217
)
18+
from aws_lambda_powertools.warnings import PowertoolsDeprecationWarning
2319

2420
from .base import DEFAULT_MAX_AGE_SECS, DEFAULT_PROVIDERS, BaseProvider
2521

22+
if TYPE_CHECKING:
23+
from botocore.config import Config
24+
from mypy_boto3_appconfigdata.client import AppConfigDataClient
25+
26+
from aws_lambda_powertools.utilities.parameters.types import TransformOptions
27+
2628

2729
class AppConfigProvider(BaseProvider):
2830
"""
@@ -72,11 +74,11 @@ class AppConfigProvider(BaseProvider):
7274
def __init__(
7375
self,
7476
environment: str,
75-
application: Optional[str] = None,
76-
config: Optional[Config] = None,
77-
boto_config: Optional[Config] = None,
78-
boto3_session: Optional[boto3.session.Session] = None,
79-
boto3_client: Optional["AppConfigDataClient"] = None,
77+
application: str | None = None,
78+
config: Config | None = None,
79+
boto_config: Config | None = None,
80+
boto3_session: boto3.session.Session | None = None,
81+
boto3_client: AppConfigDataClient | None = None,
8082
):
8183
"""
8284
Initialize the App Config client
@@ -105,9 +107,9 @@ def __init__(
105107
self.environment = environment
106108
self.current_version = ""
107109

108-
self._next_token: Dict[str, str] = {} # nosec - token for get_latest_configuration executions
110+
self._next_token: dict[str, str] = {} # nosec - token for get_latest_configuration executions
109111
# Dict to store the recently retrieved value for a specific configuration.
110-
self.last_returned_value: Dict[str, bytes] = {}
112+
self.last_returned_value: dict[str, bytes] = {}
111113

112114
super().__init__(client=self.client)
113115

@@ -145,7 +147,7 @@ def _get(self, name: str, **sdk_options) -> bytes:
145147

146148
return self.last_returned_value[name]
147149

148-
def _get_multiple(self, path: str, **sdk_options) -> Dict[str, str]:
150+
def _get_multiple(self, path: str, **sdk_options) -> dict[str, str]:
149151
"""
150152
Retrieving multiple parameter values is not supported with AWS App Config Provider
151153
"""
@@ -155,12 +157,12 @@ def _get_multiple(self, path: str, **sdk_options) -> Dict[str, str]:
155157
def get_app_config(
156158
name: str,
157159
environment: str,
158-
application: Optional[str] = None,
160+
application: str | None = None,
159161
transform: TransformOptions = None,
160162
force_fetch: bool = False,
161-
max_age: Optional[int] = None,
163+
max_age: int | None = None,
162164
**sdk_options,
163-
) -> Union[str, list, dict, bytes]:
165+
) -> str | bytes | list | dict:
164166
"""
165167
Retrieve a configuration value from AWS App Config.
166168

aws_lambda_powertools/utilities/parameters/base.py

Lines changed: 26 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -9,28 +9,20 @@
99
import os
1010
from abc import ABC, abstractmethod
1111
from datetime import datetime, timedelta
12-
from typing import (
13-
Any,
14-
Callable,
15-
Dict,
16-
NamedTuple,
17-
Optional,
18-
Tuple,
19-
Union,
20-
cast,
21-
overload,
22-
)
12+
from typing import TYPE_CHECKING, Any, Callable, NamedTuple, cast, overload
2313

2414
from aws_lambda_powertools.shared import constants, user_agent
2515
from aws_lambda_powertools.shared.functions import resolve_max_age
26-
from aws_lambda_powertools.utilities.parameters.types import TransformOptions
2716

2817
from .exceptions import GetParameterError, TransformParameterError
2918

19+
if TYPE_CHECKING:
20+
from aws_lambda_powertools.utilities.parameters.types import TransformOptions
21+
3022
DEFAULT_MAX_AGE_SECS = "300"
3123

3224
# These providers will be dynamically initialized on first use of the helper functions
33-
DEFAULT_PROVIDERS: Dict[str, Any] = {}
25+
DEFAULT_PROVIDERS: dict[str, Any] = {}
3426
TRANSFORM_METHOD_JSON = "json"
3527
TRANSFORM_METHOD_BINARY = "binary"
3628
SUPPORTED_TRANSFORM_METHODS = [TRANSFORM_METHOD_JSON, TRANSFORM_METHOD_BINARY]
@@ -45,7 +37,7 @@
4537

4638

4739
class ExpirableValue(NamedTuple):
48-
value: str | bytes | Dict[str, Any]
40+
value: str | bytes | dict[str, Any]
4941
ttl: datetime
5042

5143

@@ -54,7 +46,7 @@ class BaseProvider(ABC):
5446
Abstract Base Class for Parameter providers
5547
"""
5648

57-
store: Dict[Tuple, ExpirableValue]
49+
store: dict[tuple, ExpirableValue]
5850

5951
def __init__(self, *, client=None, resource=None):
6052
"""
@@ -65,19 +57,19 @@ def __init__(self, *, client=None, resource=None):
6557
if resource is not None:
6658
user_agent.register_feature_to_resource(resource=resource, feature="parameters")
6759

68-
self.store: Dict[Tuple, ExpirableValue] = {}
60+
self.store: dict[tuple, ExpirableValue] = {}
6961

70-
def has_not_expired_in_cache(self, key: Tuple) -> bool:
62+
def has_not_expired_in_cache(self, key: tuple) -> bool:
7163
return key in self.store and self.store[key].ttl >= datetime.now()
7264

7365
def get(
7466
self,
7567
name: str,
76-
max_age: Optional[int] = None,
68+
max_age: int | None = None,
7769
transform: TransformOptions = None,
7870
force_fetch: bool = False,
7971
**sdk_options,
80-
) -> Optional[Union[str, dict, bytes]]:
72+
) -> str | bytes | dict | None:
8173
"""
8274
Retrieve a parameter value or return the cached value
8375
@@ -114,7 +106,7 @@ def get(
114106
# of supported transform is small and the probability that a given
115107
# parameter will always be used in a specific transform, this should be
116108
# an acceptable tradeoff.
117-
value: Optional[Union[str, bytes, dict]] = None
109+
value: str | bytes | dict | None = None
118110
key = self._build_cache_key(name=name, transform=transform)
119111

120112
# If max_age is not set, resolve it from the environment variable, defaulting to DEFAULT_MAX_AGE_SECS
@@ -139,7 +131,7 @@ def get(
139131
return value
140132

141133
@abstractmethod
142-
def _get(self, name: str, **sdk_options) -> Union[str, bytes, Dict[str, Any]]:
134+
def _get(self, name: str, **sdk_options) -> str | bytes | dict[str, Any]:
143135
"""
144136
Retrieve parameter value from the underlying parameter store
145137
"""
@@ -154,12 +146,12 @@ def set(self, name: str, value: Any, *, overwrite: bool = False, **kwargs):
154146
def get_multiple(
155147
self,
156148
path: str,
157-
max_age: Optional[int] = None,
149+
max_age: int | None = None,
158150
transform: TransformOptions = None,
159151
raise_on_transform_error: bool = False,
160152
force_fetch: bool = False,
161153
**sdk_options,
162-
) -> Union[Dict[str, str], Dict[str, dict], Dict[str, bytes]]:
154+
) -> dict[str, str] | dict[str, bytes] | dict[str, dict]:
163155
"""
164156
Retrieve multiple parameters based on a path prefix
165157
@@ -211,7 +203,7 @@ def get_multiple(
211203
return values
212204

213205
@abstractmethod
214-
def _get_multiple(self, path: str, **sdk_options) -> Dict[str, str]:
206+
def _get_multiple(self, path: str, **sdk_options) -> dict[str, str]:
215207
"""
216208
Retrieve multiple parameter values from the underlying parameter store
217209
"""
@@ -220,10 +212,10 @@ def _get_multiple(self, path: str, **sdk_options) -> Dict[str, str]:
220212
def clear_cache(self):
221213
self.store.clear()
222214

223-
def fetch_from_cache(self, key: Tuple):
215+
def fetch_from_cache(self, key: tuple):
224216
return self.store[key].value if key in self.store else {}
225217

226-
def add_to_cache(self, key: Tuple, value: Any, max_age: int):
218+
def add_to_cache(self, key: tuple, value: Any, max_age: int):
227219
if max_age <= 0:
228220
return
229221

@@ -248,7 +240,7 @@ def _build_cache_key(
248240
249241
Returns
250242
-------
251-
Tuple[str, TransformOptions, bool]
243+
tuple[str, TransformOptions, bool]
252244
Cache key
253245
"""
254246
return (name, transform, is_nested)
@@ -294,28 +286,28 @@ def get_transform_method(value: str, transform: TransformOptions = None) -> Call
294286

295287
@overload
296288
def transform_value(
297-
value: Dict[str, Any],
289+
value: dict[str, Any],
298290
transform: TransformOptions,
299291
raise_on_transform_error: bool = False,
300292
key: str = "",
301-
) -> Dict[str, Any]: ...
293+
) -> dict[str, Any]: ...
302294

303295

304296
@overload
305297
def transform_value(
306-
value: Union[str, bytes, Dict[str, Any]],
298+
value: str | bytes | dict[str, Any],
307299
transform: TransformOptions,
308300
raise_on_transform_error: bool = False,
309301
key: str = "",
310-
) -> Optional[Union[str, bytes, Dict[str, Any]]]: ...
302+
) -> str | bytes | dict[str, Any] | None: ...
311303

312304

313305
def transform_value(
314-
value: Union[str, bytes, Dict[str, Any]],
306+
value: str | bytes | dict[str, Any],
315307
transform: TransformOptions,
316308
raise_on_transform_error: bool = True,
317309
key: str = "",
318-
) -> Optional[Union[str, bytes, Dict[str, Any]]]:
310+
) -> str | bytes | dict[str, Any] | None:
319311
"""
320312
Transform a value using one of the available options.
321313
@@ -348,7 +340,7 @@ def transform_value(
348340
# where one of the keys might fail during transform, e.g. `{"a": "valid", "b": "{"}`
349341
# expected: `{"a": "valid", "b": None}`
350342

351-
transformed_values: Dict[str, Any] = {}
343+
transformed_values: dict[str, Any] = {}
352344
for dict_key, dict_value in value.items():
353345
transform_method = get_transform_method(value=dict_key, transform=transform)
354346
try:

aws_lambda_powertools/utilities/parameters/dynamodb.py

Lines changed: 10 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -2,18 +2,20 @@
22
Amazon DynamoDB parameter retrieval and caching utility
33
"""
44

5+
from __future__ import annotations
6+
57
import warnings
6-
from typing import TYPE_CHECKING, Dict, Optional
8+
from typing import TYPE_CHECKING
79

810
import boto3
911
from boto3.dynamodb.conditions import Key
10-
from botocore.config import Config
1112

1213
from aws_lambda_powertools.warnings import PowertoolsDeprecationWarning
1314

1415
from .base import BaseProvider
1516

1617
if TYPE_CHECKING:
18+
from botocore.config import Config
1719
from mypy_boto3_dynamodb.service_resource import DynamoDBServiceResource
1820

1921

@@ -156,11 +158,11 @@ def __init__(
156158
key_attr: str = "id",
157159
sort_attr: str = "sk",
158160
value_attr: str = "value",
159-
endpoint_url: Optional[str] = None,
160-
config: Optional[Config] = None,
161-
boto_config: Optional[Config] = None,
162-
boto3_session: Optional[boto3.session.Session] = None,
163-
boto3_client: Optional["DynamoDBServiceResource"] = None,
161+
endpoint_url: str | None = None,
162+
config: Config | None = None,
163+
boto_config: Config | None = None,
164+
boto3_session: boto3.session.Session | None = None,
165+
boto3_client: DynamoDBServiceResource | None = None,
164166
):
165167
"""
166168
Initialize the DynamoDB client
@@ -203,7 +205,7 @@ def _get(self, name: str, **sdk_options) -> str:
203205
# without a breaking change within ABC return type
204206
return self.table.get_item(**sdk_options)["Item"][self.value_attr] # type: ignore[return-value]
205207

206-
def _get_multiple(self, path: str, **sdk_options) -> Dict[str, str]:
208+
def _get_multiple(self, path: str, **sdk_options) -> dict[str, str]:
207209
"""
208210
Retrieve multiple parameter values from Amazon DynamoDB
209211

0 commit comments

Comments
 (0)