Skip to content

Commit b5d54eb

Browse files
authored
refactor(metrics): add from __future__ import annotations (#4944)
and update code according to ruff rules TCH, UP006, UP007, UP037 and FA100.
1 parent 2989ec1 commit b5d54eb

File tree

8 files changed

+113
-100
lines changed

8 files changed

+113
-100
lines changed

aws_lambda_powertools/metrics/base.py

Lines changed: 30 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
import warnings
1010
from collections import defaultdict
1111
from contextlib import contextmanager
12-
from typing import Any, Callable, Dict, Generator, List, Optional, Union
12+
from typing import TYPE_CHECKING, Any, Callable, Generator
1313

1414
from aws_lambda_powertools.metrics.exceptions import (
1515
MetricResolutionError,
@@ -24,10 +24,12 @@
2424
from aws_lambda_powertools.metrics.provider.cold_start import (
2525
reset_cold_start_flag, # noqa: F401 # backwards compatibility
2626
)
27-
from aws_lambda_powertools.metrics.types import MetricNameUnitResolution
2827
from aws_lambda_powertools.shared import constants
2928
from aws_lambda_powertools.shared.functions import resolve_env_var_choice
3029

30+
if TYPE_CHECKING:
31+
from aws_lambda_powertools.metrics.types import MetricNameUnitResolution
32+
3133
logger = logging.getLogger(__name__)
3234

3335
# Maintenance: alias due to Hyrum's law
@@ -66,10 +68,10 @@ class MetricManager:
6668

6769
def __init__(
6870
self,
69-
metric_set: Dict[str, Any] | None = None,
70-
dimension_set: Dict | None = None,
71+
metric_set: dict[str, Any] | None = None,
72+
dimension_set: dict | None = None,
7173
namespace: str | None = None,
72-
metadata_set: Dict[str, Any] | None = None,
74+
metadata_set: dict[str, Any] | None = None,
7375
service: str | None = None,
7476
):
7577
self.metric_set = metric_set if metric_set is not None else {}
@@ -110,11 +112,11 @@ def add_metric(
110112
----------
111113
name : str
112114
Metric name
113-
unit : Union[MetricUnit, str]
115+
unit : MetricUnit | str
114116
`aws_lambda_powertools.helper.models.MetricUnit`
115117
value : float
116118
Metric value
117-
resolution : Union[MetricResolution, int]
119+
resolution : MetricResolution | int
118120
`aws_lambda_powertools.helper.models.MetricResolution`
119121
120122
Raises
@@ -129,7 +131,7 @@ def add_metric(
129131

130132
unit = self._extract_metric_unit_value(unit=unit)
131133
resolution = self._extract_metric_resolution_value(resolution=resolution)
132-
metric: Dict = self.metric_set.get(name, defaultdict(list))
134+
metric: dict = self.metric_set.get(name, defaultdict(list))
133135
metric["Unit"] = unit
134136
metric["StorageResolution"] = resolution
135137
metric["Value"].append(float(value))
@@ -147,19 +149,19 @@ def add_metric(
147149

148150
def serialize_metric_set(
149151
self,
150-
metrics: Dict | None = None,
151-
dimensions: Dict | None = None,
152-
metadata: Dict | None = None,
153-
) -> Dict:
152+
metrics: dict | None = None,
153+
dimensions: dict | None = None,
154+
metadata: dict | None = None,
155+
) -> dict:
154156
"""Serializes metric and dimensions set
155157
156158
Parameters
157159
----------
158-
metrics : Dict, optional
160+
metrics : dict, optional
159161
Dictionary of metrics to serialize, by default None
160-
dimensions : Dict, optional
162+
dimensions : dict, optional
161163
Dictionary of dimensions to serialize, by default None
162-
metadata: Dict, optional
164+
metadata: dict, optional
163165
Dictionary of metadata to serialize, by default None
164166
165167
Example
@@ -172,7 +174,7 @@ def serialize_metric_set(
172174
173175
Returns
174176
-------
175-
Dict
177+
dict
176178
Serialized metrics following EMF specification
177179
178180
Raises
@@ -206,8 +208,8 @@ def serialize_metric_set(
206208
#
207209
# In case using high-resolution metrics, add StorageResolution field
208210
# Example: [ { "Name": "metric_name", "Unit": "Count", "StorageResolution": 1 } ] # noqa ERA001
209-
metric_definition: List[MetricNameUnitResolution] = []
210-
metric_names_and_values: Dict[str, float] = {} # { "metric_name": 1.0 }
211+
metric_definition: list[MetricNameUnitResolution] = []
212+
metric_names_and_values: dict[str, float] = {} # { "metric_name": 1.0 }
211213

212214
for metric_name in metrics:
213215
metric: dict = metrics[metric_name]
@@ -354,10 +356,10 @@ def flush_metrics(self, raise_on_empty_metrics: bool = False) -> None:
354356

355357
def log_metrics(
356358
self,
357-
lambda_handler: Callable[[Dict, Any], Any] | Optional[Callable[[Dict, Any, Optional[Dict]], Any]] = None,
359+
lambda_handler: Callable[[dict, Any], Any] | Callable[[dict, Any, dict | None], Any] | None = None,
358360
capture_cold_start_metric: bool = False,
359361
raise_on_empty_metrics: bool = False,
360-
default_dimensions: Dict[str, str] | None = None,
362+
default_dimensions: dict[str, str] | None = None,
361363
):
362364
"""Decorator to serialize and publish metrics at the end of a function execution.
363365
@@ -385,7 +387,7 @@ def handler(event, context):
385387
captures cold start metric, by default False
386388
raise_on_empty_metrics : bool, optional
387389
raise exception if no metrics are emitted, by default False
388-
default_dimensions: Dict[str, str], optional
390+
default_dimensions: dict[str, str], optional
389391
metric dimensions as key=value that will always be present
390392
391393
Raises
@@ -420,12 +422,12 @@ def decorate(event, context, *args, **kwargs):
420422

421423
return decorate
422424

423-
def _extract_metric_resolution_value(self, resolution: Union[int, MetricResolution]) -> int:
425+
def _extract_metric_resolution_value(self, resolution: int | MetricResolution) -> int:
424426
"""Return metric value from metric unit whether that's str or MetricResolution enum
425427
426428
Parameters
427429
----------
428-
unit : Union[int, MetricResolution]
430+
unit : int | MetricResolution
429431
Metric resolution
430432
431433
Returns
@@ -448,12 +450,12 @@ def _extract_metric_resolution_value(self, resolution: Union[int, MetricResoluti
448450
f"Invalid metric resolution '{resolution}', expected either option: {self._metric_resolutions}", # noqa: E501
449451
)
450452

451-
def _extract_metric_unit_value(self, unit: Union[str, MetricUnit]) -> str:
453+
def _extract_metric_unit_value(self, unit: str | MetricUnit) -> str:
452454
"""Return metric value from metric unit whether that's str or MetricUnit enum
453455
454456
Parameters
455457
----------
456-
unit : Union[str, MetricUnit]
458+
unit : str | MetricUnit
457459
Metric unit
458460
459461
Returns
@@ -566,7 +568,7 @@ def single_metric(
566568
value: float,
567569
resolution: MetricResolution | int = 60,
568570
namespace: str | None = None,
569-
default_dimensions: Dict[str, str] | None = None,
571+
default_dimensions: dict[str, str] | None = None,
570572
) -> Generator[SingleMetric, None, None]:
571573
"""Context manager to simplify creation of a single metric
572574
@@ -604,7 +606,7 @@ def single_metric(
604606
Metric value
605607
namespace: str
606608
Namespace for metrics
607-
default_dimensions: Dict[str, str], optional
609+
default_dimensions: dict[str, str], optional
608610
Metric dimensions as key=value that will always be present
609611
610612
@@ -624,7 +626,7 @@ def single_metric(
624626
SchemaValidationError
625627
When metric object fails EMF schema validation
626628
""" # noqa: E501
627-
metric_set: Dict | None = None
629+
metric_set: dict | None = None
628630
try:
629631
metric: SingleMetric = SingleMetric(namespace=namespace)
630632
metric.add_metric(name=name, unit=unit, value=value, resolution=resolution)

aws_lambda_powertools/metrics/functions.py

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
from __future__ import annotations
22

33
from datetime import datetime
4-
from typing import List
54

65
from aws_lambda_powertools.metrics.provider.cloudwatch_emf.exceptions import (
76
MetricResolutionError,
@@ -11,12 +10,12 @@
1110
from aws_lambda_powertools.shared import constants
1211

1312

14-
def extract_cloudwatch_metric_resolution_value(metric_resolutions: List, resolution: int | MetricResolution) -> int:
13+
def extract_cloudwatch_metric_resolution_value(metric_resolutions: list, resolution: int | MetricResolution) -> int:
1514
"""Return metric value from CloudWatch metric unit whether that's str or MetricResolution enum
1615
1716
Parameters
1817
----------
19-
unit : Union[int, MetricResolution]
18+
resolution : int | MetricResolution
2019
Metric resolution
2120
2221
Returns
@@ -40,12 +39,12 @@ def extract_cloudwatch_metric_resolution_value(metric_resolutions: List, resolut
4039
)
4140

4241

43-
def extract_cloudwatch_metric_unit_value(metric_units: List, metric_valid_options: List, unit: str | MetricUnit) -> str:
42+
def extract_cloudwatch_metric_unit_value(metric_units: list, metric_valid_options: list, unit: str | MetricUnit) -> str:
4443
"""Return metric value from CloudWatch metric unit whether that's str or MetricUnit enum
4544
4645
Parameters
4746
----------
48-
unit : Union[str, MetricUnit]
47+
unit : str | MetricUnit
4948
Metric unit
5049
5150
Returns

aws_lambda_powertools/metrics/metrics.py

Lines changed: 15 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,14 @@
11
# NOTE: keeps for compatibility
22
from __future__ import annotations
33

4-
from typing import Any, Dict
4+
from typing import TYPE_CHECKING, Any
55

6-
from aws_lambda_powertools.metrics.base import MetricResolution, MetricUnit
76
from aws_lambda_powertools.metrics.provider.cloudwatch_emf.cloudwatch import AmazonCloudWatchEMFProvider
8-
from aws_lambda_powertools.metrics.provider.cloudwatch_emf.types import CloudWatchEMFOutput
9-
from aws_lambda_powertools.shared.types import AnyCallableT
7+
8+
if TYPE_CHECKING:
9+
from aws_lambda_powertools.metrics.base import MetricResolution, MetricUnit
10+
from aws_lambda_powertools.metrics.provider.cloudwatch_emf.types import CloudWatchEMFOutput
11+
from aws_lambda_powertools.shared.types import AnyCallableT
1012

1113

1214
class Metrics:
@@ -72,10 +74,10 @@ def lambda_handler():
7274
# and not get caught by accident with metrics data loss, or data deduplication
7375
# e.g., m1 and m2 add metric ProductCreated, however m1 has 'version' dimension but m2 doesn't
7476
# Result: ProductCreated is created twice as we now have 2 different EMF blobs
75-
_metrics: Dict[str, Any] = {}
76-
_dimensions: Dict[str, str] = {}
77-
_metadata: Dict[str, Any] = {}
78-
_default_dimensions: Dict[str, Any] = {}
77+
_metrics: dict[str, Any] = {}
78+
_dimensions: dict[str, str] = {}
79+
_metadata: dict[str, Any] = {}
80+
_default_dimensions: dict[str, Any] = {}
7981

8082
def __init__(
8183
self,
@@ -116,9 +118,9 @@ def add_dimension(self, name: str, value: str) -> None:
116118

117119
def serialize_metric_set(
118120
self,
119-
metrics: Dict | None = None,
120-
dimensions: Dict | None = None,
121-
metadata: Dict | None = None,
121+
metrics: dict | None = None,
122+
dimensions: dict | None = None,
123+
metadata: dict | None = None,
122124
) -> CloudWatchEMFOutput:
123125
return self.provider.serialize_metric_set(metrics=metrics, dimensions=dimensions, metadata=metadata)
124126

@@ -146,7 +148,7 @@ def log_metrics(
146148
lambda_handler: AnyCallableT | None = None,
147149
capture_cold_start_metric: bool = False,
148150
raise_on_empty_metrics: bool = False,
149-
default_dimensions: Dict[str, str] | None = None,
151+
default_dimensions: dict[str, str] | None = None,
150152
**kwargs,
151153
):
152154
return self.provider.log_metrics(
@@ -163,7 +165,7 @@ def set_default_dimensions(self, **dimensions) -> None:
163165
164166
Parameters
165167
----------
166-
dimensions : Dict[str, Any], optional
168+
dimensions : dict[str, Any], optional
167169
metric dimensions as key=value
168170
169171
Example

aws_lambda_powertools/metrics/provider/base.py

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -3,11 +3,13 @@
33
import functools
44
import logging
55
from abc import ABC, abstractmethod
6-
from typing import Any
6+
from typing import TYPE_CHECKING, Any
77

88
from aws_lambda_powertools.metrics.provider import cold_start
9-
from aws_lambda_powertools.shared.types import AnyCallableT
10-
from aws_lambda_powertools.utilities.typing import LambdaContext
9+
10+
if TYPE_CHECKING:
11+
from aws_lambda_powertools.shared.types import AnyCallableT
12+
from aws_lambda_powertools.utilities.typing import LambdaContext
1113

1214
logger = logging.getLogger(__name__)
1315

@@ -40,7 +42,7 @@ def add_metric(self, *args: Any, **kwargs: Any) -> Any:
4042
4143
Returns
4244
----------
43-
Dict
45+
dict
4446
A combined metrics dictionary.
4547
4648
Raises
@@ -66,7 +68,7 @@ def serialize_metric_set(self, *args: Any, **kwargs: Any) -> Any:
6668
6769
Returns
6870
----------
69-
Dict
71+
dict
7072
Serialized metrics
7173
7274
Raises
@@ -172,7 +174,7 @@ def handler(event, context):
172174
captures cold start metric, by default False
173175
raise_on_empty_metrics : bool, optional
174176
raise exception if no metrics are emitted, by default False
175-
default_dimensions: Dict[str, str], optional
177+
default_dimensions: dict[str, str], optional
176178
metric dimensions as key=value that will always be present
177179
178180
Raises

0 commit comments

Comments
 (0)