Skip to content

refactor(metrics): use standard collections for types #6472

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Apr 15, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion aws_lambda_powertools/metrics/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
import warnings
from collections import defaultdict
from contextlib import contextmanager
from typing import TYPE_CHECKING, Any, Callable, Generator
from typing import TYPE_CHECKING, Any

from aws_lambda_powertools.metrics.exceptions import (
MetricResolutionError,
Expand All @@ -34,6 +34,8 @@
from aws_lambda_powertools.shared.functions import resolve_env_var_choice

if TYPE_CHECKING:
from collections.abc import Callable, Generator

from aws_lambda_powertools.metrics.types import MetricNameUnitResolution

logger = logging.getLogger(__name__)
Expand Down
4 changes: 3 additions & 1 deletion aws_lambda_powertools/metrics/metrics.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
# NOTE: keeps for compatibility
from __future__ import annotations

from typing import TYPE_CHECKING, Any, Callable
from typing import TYPE_CHECKING, Any

from aws_lambda_powertools.metrics.provider.cloudwatch_emf.cloudwatch import AmazonCloudWatchEMFProvider

if TYPE_CHECKING:
from collections.abc import Callable

from aws_lambda_powertools.metrics.base import MetricResolution, MetricUnit
from aws_lambda_powertools.metrics.provider.cloudwatch_emf.types import CloudWatchEMFOutput
from aws_lambda_powertools.shared.types import AnyCallableT
Expand Down
26 changes: 14 additions & 12 deletions tests/functional/metrics/conftest.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
from typing import Any, Dict, List, Union
from __future__ import annotations

from typing import Any

import pytest

Expand All @@ -20,51 +22,51 @@ def reset_metric_set():


@pytest.fixture
def metric_with_resolution() -> Dict[str, Union[str, int]]:
def metric_with_resolution() -> dict[str, str | int]:
return {"name": "single_metric", "unit": MetricUnit.Count, "value": 1, "resolution": MetricResolution.High}


@pytest.fixture
def metric() -> Dict[str, str]:
def metric() -> dict[str, str]:
return {"name": "single_metric", "unit": MetricUnit.Count, "value": 1}


@pytest.fixture
def metric_datadog() -> Dict[str, str]:
def metric_datadog() -> dict[str, str]:
return {"name": "single_metric", "value": 1, "timestamp": 1691678198, "powertools": "datadog"}


@pytest.fixture
def metrics() -> List[Dict[str, str]]:
def metrics() -> list[dict[str, str]]:
return [
{"name": "metric_one", "unit": MetricUnit.Count, "value": 1},
{"name": "metric_two", "unit": MetricUnit.Count, "value": 1},
]


@pytest.fixture
def metrics_same_name() -> List[Dict[str, str]]:
def metrics_same_name() -> list[dict[str, str]]:
return [
{"name": "metric_one", "unit": MetricUnit.Count, "value": 1},
{"name": "metric_one", "unit": MetricUnit.Count, "value": 5},
]


@pytest.fixture
def dimension() -> Dict[str, str]:
def dimension() -> dict[str, str]:
return {"name": "test_dimension", "value": "test"}


@pytest.fixture
def dimensions() -> List[Dict[str, str]]:
def dimensions() -> list[dict[str, str]]:
return [
{"name": "test_dimension", "value": "test"},
{"name": "test_dimension_2", "value": "test"},
]


@pytest.fixture
def non_str_dimensions() -> List[Dict[str, Any]]:
def non_str_dimensions() -> list[dict[str, Any]]:
return [
{"name": "test_dimension", "value": True},
{"name": "test_dimension_2", "value": 3},
Expand All @@ -82,15 +84,15 @@ def service() -> str:


@pytest.fixture
def metadata() -> Dict[str, str]:
def metadata() -> dict[str, str]:
return {"key": "username", "value": "test"}


@pytest.fixture
def a_hundred_metrics() -> List[Dict[str, str]]:
def a_hundred_metrics() -> list[dict[str, str]]:
return [{"name": f"metric_{i}", "unit": "Count", "value": 1} for i in range(100)]


@pytest.fixture
def a_hundred_metric_values() -> List[Dict[str, str]]:
def a_hundred_metric_values() -> list[dict[str, str]]:
return [{"name": "metric", "unit": "Count", "value": i} for i in range(100)]
2 changes: 2 additions & 0 deletions tests/functional/metrics/datadog/test_metrics_datadog.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from __future__ import annotations

import json
import warnings
from collections import namedtuple
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
from __future__ import annotations

import datetime
import json
import warnings
from collections import namedtuple
from typing import Dict, List, Optional, Union
from typing import Any

import pytest

Expand All @@ -29,10 +31,10 @@


def serialize_metrics(
metrics: List[Dict],
dimensions: List[Dict],
metrics: list[dict[str, Any]],
dimensions: list[dict[str, Any]],
namespace: str,
metadatas: Optional[List[Dict]] = None,
metadatas: list[dict] | None = None,
) -> CloudWatchEMFOutput:
"""Helper function to build EMF object from a list of metrics, dimensions"""
my_metrics = AmazonCloudWatchEMFProvider(namespace=namespace)
Expand All @@ -51,11 +53,11 @@ def serialize_metrics(


def serialize_single_metric(
metric: Dict,
dimension: Dict,
metric: dict[str, Any],
dimension: dict[str, Any],
namespace: str,
metadata: Optional[Dict] = None,
timestamp: Union[int, datetime.datetime, None] = None,
metadata: dict[str, Any] | None = None,
timestamp: int | datetime.datetime | None = None,
) -> CloudWatchEMFOutput:
"""Helper function to build EMF object from a given metric, dimension and namespace"""
my_metrics = AmazonCloudWatchEMFProvider(namespace=namespace)
Expand All @@ -71,7 +73,7 @@ def serialize_single_metric(
return my_metrics.serialize_metric_set()


def remove_timestamp(metrics: List):
def remove_timestamp(metrics: list):
"""Helper function to remove Timestamp key from EMF objects as they're built at serialization"""
for metric in metrics:
del metric["_aws"]["Timestamp"]
Expand All @@ -81,7 +83,7 @@ def capture_metrics_output(capsys):
return json.loads(capsys.readouterr().out.strip())


def capture_metrics_output_multiple_emf_objects(capsys) -> List[CloudWatchEMFOutput]:
def capture_metrics_output_multiple_emf_objects(capsys) -> list[CloudWatchEMFOutput]:
return [json.loads(line.strip()) for line in capsys.readouterr().out.split("\n") if line]


Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
from __future__ import annotations

import json
from typing import Any, List
from typing import Any

from aws_lambda_powertools.metrics import (
SchemaValidationError,
Expand All @@ -15,9 +17,9 @@ def capture_metrics_output(capsys):

class FakeMetricsProvider(BaseProvider):
def __init__(self):
self.metric_store: List = []
self.metric_store: list = []

def add_metric(self, name: str, value: float, tag: List = None, *args, **kwargs):
def add_metric(self, name: str, value: float, tag: list = None, *args, **kwargs):
self.metric_store.append({"name": name, "value": value})

def serialize_metric_set(self, raise_on_empty_metrics: bool = False, *args, **kwargs):
Expand Down
2 changes: 2 additions & 0 deletions tests/unit/metrics/conftest.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from __future__ import annotations

import pytest


Expand Down
2 changes: 2 additions & 0 deletions tests/unit/metrics/test_functions.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from __future__ import annotations

import warnings

import pytest
Expand Down
2 changes: 2 additions & 0 deletions tests/unit/metrics/test_unit_datadog.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from __future__ import annotations

import pytest

from aws_lambda_powertools.metrics.exceptions import SchemaValidationError
Expand Down
Loading