Skip to content

Commit 423b00a

Browse files
refactor(parameters): add from __future__ import annotations (#4976)
* refactor(parameters): add from __future__ import annotations and update code according to ruff rules TCH, UP006, UP007, UP037 and FA100. * Fixing constants + absolute imports * Fixing constants + absolute imports --------- Co-authored-by: Leandro Damascena <[email protected]>
1 parent e69b192 commit 423b00a

File tree

6 files changed

+220
-212
lines changed

6 files changed

+220
-212
lines changed

aws_lambda_powertools/utilities/parameters/appconfig.py

+22-20
Original file line numberDiff line numberDiff line change
@@ -2,26 +2,28 @@
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.utilities.parameters.base import BaseProvider
19+
from aws_lambda_powertools.utilities.parameters.constants import DEFAULT_MAX_AGE_SECS, DEFAULT_PROVIDERS
20+
from aws_lambda_powertools.warnings import PowertoolsDeprecationWarning
21+
22+
if TYPE_CHECKING:
23+
from botocore.config import Config
24+
from mypy_boto3_appconfigdata.client import AppConfigDataClient
2325

24-
from .base import DEFAULT_MAX_AGE_SECS, DEFAULT_PROVIDERS, BaseProvider
26+
from aws_lambda_powertools.utilities.parameters.types import TransformOptions
2527

2628

2729
class AppConfigProvider(BaseProvider):
@@ -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

+30-50
Original file line numberDiff line numberDiff line change
@@ -4,48 +4,28 @@
44

55
from __future__ import annotations
66

7-
import base64
8-
import json
97
import os
108
from abc import ABC, abstractmethod
119
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-
)
10+
from typing import TYPE_CHECKING, Any, Callable, NamedTuple, cast, overload
2311

2412
from aws_lambda_powertools.shared import constants, user_agent
2513
from aws_lambda_powertools.shared.functions import resolve_max_age
26-
from aws_lambda_powertools.utilities.parameters.types import TransformOptions
27-
28-
from .exceptions import GetParameterError, TransformParameterError
14+
from aws_lambda_powertools.utilities.parameters.exceptions import GetParameterError, TransformParameterError
2915

30-
DEFAULT_MAX_AGE_SECS = "300"
16+
if TYPE_CHECKING:
17+
from aws_lambda_powertools.utilities.parameters.types import TransformOptions
3118

32-
# These providers will be dynamically initialized on first use of the helper functions
33-
DEFAULT_PROVIDERS: Dict[str, Any] = {}
34-
TRANSFORM_METHOD_JSON = "json"
35-
TRANSFORM_METHOD_BINARY = "binary"
36-
SUPPORTED_TRANSFORM_METHODS = [TRANSFORM_METHOD_JSON, TRANSFORM_METHOD_BINARY]
3719

38-
TRANSFORM_METHOD_MAPPING = {
39-
TRANSFORM_METHOD_JSON: json.loads,
40-
TRANSFORM_METHOD_BINARY: base64.b64decode,
41-
".json": json.loads,
42-
".binary": base64.b64decode,
43-
None: lambda x: x,
44-
}
20+
from aws_lambda_powertools.utilities.parameters.constants import (
21+
DEFAULT_MAX_AGE_SECS,
22+
DEFAULT_PROVIDERS,
23+
TRANSFORM_METHOD_MAPPING,
24+
)
4525

4626

4727
class ExpirableValue(NamedTuple):
48-
value: str | bytes | Dict[str, Any]
28+
value: str | bytes | dict[str, Any]
4929
ttl: datetime
5030

5131

@@ -54,7 +34,7 @@ class BaseProvider(ABC):
5434
Abstract Base Class for Parameter providers
5535
"""
5636

57-
store: Dict[Tuple, ExpirableValue]
37+
store: dict[tuple, ExpirableValue]
5838

5939
def __init__(self, *, client=None, resource=None):
6040
"""
@@ -65,19 +45,19 @@ def __init__(self, *, client=None, resource=None):
6545
if resource is not None:
6646
user_agent.register_feature_to_resource(resource=resource, feature="parameters")
6747

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

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

7353
def get(
7454
self,
7555
name: str,
76-
max_age: Optional[int] = None,
56+
max_age: int | None = None,
7757
transform: TransformOptions = None,
7858
force_fetch: bool = False,
7959
**sdk_options,
80-
) -> Optional[Union[str, dict, bytes]]:
60+
) -> str | bytes | dict | None:
8161
"""
8262
Retrieve a parameter value or return the cached value
8363
@@ -114,7 +94,7 @@ def get(
11494
# of supported transform is small and the probability that a given
11595
# parameter will always be used in a specific transform, this should be
11696
# an acceptable tradeoff.
117-
value: Optional[Union[str, bytes, dict]] = None
97+
value: str | bytes | dict | None = None
11898
key = self._build_cache_key(name=name, transform=transform)
11999

120100
# If max_age is not set, resolve it from the environment variable, defaulting to DEFAULT_MAX_AGE_SECS
@@ -139,7 +119,7 @@ def get(
139119
return value
140120

141121
@abstractmethod
142-
def _get(self, name: str, **sdk_options) -> Union[str, bytes, Dict[str, Any]]:
122+
def _get(self, name: str, **sdk_options) -> str | bytes | dict[str, Any]:
143123
"""
144124
Retrieve parameter value from the underlying parameter store
145125
"""
@@ -154,12 +134,12 @@ def set(self, name: str, value: Any, *, overwrite: bool = False, **kwargs):
154134
def get_multiple(
155135
self,
156136
path: str,
157-
max_age: Optional[int] = None,
137+
max_age: int | None = None,
158138
transform: TransformOptions = None,
159139
raise_on_transform_error: bool = False,
160140
force_fetch: bool = False,
161141
**sdk_options,
162-
) -> Union[Dict[str, str], Dict[str, dict], Dict[str, bytes]]:
142+
) -> dict[str, str] | dict[str, bytes] | dict[str, dict]:
163143
"""
164144
Retrieve multiple parameters based on a path prefix
165145
@@ -211,7 +191,7 @@ def get_multiple(
211191
return values
212192

213193
@abstractmethod
214-
def _get_multiple(self, path: str, **sdk_options) -> Dict[str, str]:
194+
def _get_multiple(self, path: str, **sdk_options) -> dict[str, str]:
215195
"""
216196
Retrieve multiple parameter values from the underlying parameter store
217197
"""
@@ -220,10 +200,10 @@ def _get_multiple(self, path: str, **sdk_options) -> Dict[str, str]:
220200
def clear_cache(self):
221201
self.store.clear()
222202

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

226-
def add_to_cache(self, key: Tuple, value: Any, max_age: int):
206+
def add_to_cache(self, key: tuple, value: Any, max_age: int):
227207
if max_age <= 0:
228208
return
229209

@@ -248,7 +228,7 @@ def _build_cache_key(
248228
249229
Returns
250230
-------
251-
Tuple[str, TransformOptions, bool]
231+
tuple[str, TransformOptions, bool]
252232
Cache key
253233
"""
254234
return (name, transform, is_nested)
@@ -294,28 +274,28 @@ def get_transform_method(value: str, transform: TransformOptions = None) -> Call
294274

295275
@overload
296276
def transform_value(
297-
value: Dict[str, Any],
277+
value: dict[str, Any],
298278
transform: TransformOptions,
299279
raise_on_transform_error: bool = False,
300280
key: str = "",
301-
) -> Dict[str, Any]: ...
281+
) -> dict[str, Any]: ...
302282

303283

304284
@overload
305285
def transform_value(
306-
value: Union[str, bytes, Dict[str, Any]],
286+
value: str | bytes | dict[str, Any],
307287
transform: TransformOptions,
308288
raise_on_transform_error: bool = False,
309289
key: str = "",
310-
) -> Optional[Union[str, bytes, Dict[str, Any]]]: ...
290+
) -> str | bytes | dict[str, Any] | None: ...
311291

312292

313293
def transform_value(
314-
value: Union[str, bytes, Dict[str, Any]],
294+
value: str | bytes | dict[str, Any],
315295
transform: TransformOptions,
316296
raise_on_transform_error: bool = True,
317297
key: str = "",
318-
) -> Optional[Union[str, bytes, Dict[str, Any]]]:
298+
) -> str | bytes | dict[str, Any] | None:
319299
"""
320300
Transform a value using one of the available options.
321301
@@ -348,7 +328,7 @@ def transform_value(
348328
# where one of the keys might fail during transform, e.g. `{"a": "valid", "b": "{"}`
349329
# expected: `{"a": "valid", "b": None}`
350330

351-
transformed_values: Dict[str, Any] = {}
331+
transformed_values: dict[str, Any] = {}
352332
for dict_key, dict_value in value.items():
353333
transform_method = get_transform_method(value=dict_key, transform=transform)
354334
try:
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
from __future__ import annotations
2+
3+
import base64
4+
import json
5+
from typing import Any, Literal
6+
7+
SSM_PARAMETER_TYPES = Literal["String", "StringList", "SecureString"]
8+
SSM_PARAMETER_TIER = Literal["Standard", "Advanced", "Intelligent-Tiering"]
9+
10+
DEFAULT_MAX_AGE_SECS = "300"
11+
12+
# These providers will be dynamically initialized on first use of the helper functions
13+
DEFAULT_PROVIDERS: dict[str, Any] = {}
14+
TRANSFORM_METHOD_JSON = "json"
15+
TRANSFORM_METHOD_BINARY = "binary"
16+
TRANSFORM_METHOD_MAPPING = {
17+
TRANSFORM_METHOD_JSON: json.loads,
18+
TRANSFORM_METHOD_BINARY: base64.b64decode,
19+
".json": json.loads,
20+
".binary": base64.b64decode,
21+
None: lambda x: x,
22+
}

aws_lambda_powertools/utilities/parameters/dynamodb.py

+11-10
Original file line numberDiff line numberDiff line change
@@ -2,18 +2,19 @@
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

13+
from aws_lambda_powertools.utilities.parameters.base import BaseProvider
1214
from aws_lambda_powertools.warnings import PowertoolsDeprecationWarning
1315

14-
from .base import BaseProvider
15-
1616
if TYPE_CHECKING:
17+
from botocore.config import Config
1718
from mypy_boto3_dynamodb.service_resource import DynamoDBServiceResource
1819

1920

@@ -156,11 +157,11 @@ def __init__(
156157
key_attr: str = "id",
157158
sort_attr: str = "sk",
158159
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,
160+
endpoint_url: str | None = None,
161+
config: Config | None = None,
162+
boto_config: Config | None = None,
163+
boto3_session: boto3.session.Session | None = None,
164+
boto3_client: DynamoDBServiceResource | None = None,
164165
):
165166
"""
166167
Initialize the DynamoDB client
@@ -203,7 +204,7 @@ def _get(self, name: str, **sdk_options) -> str:
203204
# without a breaking change within ABC return type
204205
return self.table.get_item(**sdk_options)["Item"][self.value_attr] # type: ignore[return-value]
205206

206-
def _get_multiple(self, path: str, **sdk_options) -> Dict[str, str]:
207+
def _get_multiple(self, path: str, **sdk_options) -> dict[str, str]:
207208
"""
208209
Retrieve multiple parameter values from Amazon DynamoDB
209210

0 commit comments

Comments
 (0)