Skip to content

Commit 0c4c677

Browse files
author
Om Pathak
committed
Make clear() a no-op for label-less metrics instead of raising AttributeError
Fixes #707. clear() unconditionally acquired self._lock, which is never created for metrics with no labelnames, causing an AttributeError. Per discussion in the issue (csmarchbanks, roidelapluie, sdfordham, tomprince), a label-less metric has no labelsets to clear, so clear() now treats this as a no-op rather than raising. Signed-off-by: Om Pathak <ompathak@gmail.com>
1 parent c0e416d commit 0c4c677

2 files changed

Lines changed: 8 additions & 0 deletions

File tree

prometheus_client/metrics.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -254,6 +254,8 @@ def remove_by_labels(self, labels: dict[str, str]) -> None:
254254

255255
def clear(self) -> None:
256256
"""Remove all labelsets from the metric"""
257+
if not self._labelnames:
258+
return
257259
if 'prometheus_multiproc_dir' in os.environ or 'PROMETHEUS_MULTIPROC_DIR' in os.environ:
258260
warnings.warn(
259261
"Clearing labels has not been implemented in multi-process mode yet",

tests/test_core.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,12 @@ def test_reset(self):
5959
def test_repr(self):
6060
self.assertEqual(repr(self.counter), "prometheus_client.metrics.Counter(c)")
6161

62+
def test_clear_without_labels_is_noop(self):
63+
self.counter.inc()
64+
self.assertEqual(1, self.registry.get_sample_value('c_total'))
65+
self.counter.clear() # should not raise
66+
self.assertEqual(1, self.registry.get_sample_value('c_total'))
67+
6268
def test_negative_increment_raises(self):
6369
self.assertRaises(ValueError, self.counter.inc, -1)
6470

0 commit comments

Comments
 (0)