Skip to content

Inconsistent behavior of flush_metrics with raise_on_empty_metrics parameter #7467

@jotafeldmann

Description

@jotafeldmann

Summary

The current implementation of metrics.flush_metrics does not fully align with its documentation regarding the raise_on_empty_metrics parameter.

Details

According to the documentation:

Parameters
----------
raise_on_empty_metrics : bool, optional
    raise exception if no metrics are emitted, by default False

This suggests that setting raise_on_empty_metrics=False should prevent exceptions from being raised, regardless of whether metrics are present.

However, in practice, when calling:

metrics.flush_metrics(raise_on_empty_metrics=False)

The code still evaluates the presence of metrics due to the current implementation, raising an error:

if not raise_on_empty_metrics and not self.metric_set:

Suggested Fix

To make the behavior consistent with the documented intent, the check could be simplified to:

if not raise_on_empty_metrics:

This change ensures that no exception is raised if the user explicitly disables it, regardless of whether metrics are set.

Rationale

The documentation indicates that the sole purpose of the raise_on_empty_metrics flag is to control whether an exception is thrown when no metrics are emitted. If users pass False, they are intentionally choosing to suppress exceptions, so the existence (or absence) of metrics should not alter that behavior.

Environment

  • Library: aws-lambda-powertools
  • Version: [please fill in]
  • Runtime: Python 3.12 on AWS Lambda

Additional Context

This proposal would bring the implementation in line with the documented behavior, improving consistency and reducing potential confusion for developers.

Metadata

Metadata

Labels

Type

No type

Projects

Status

Working on it

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions