Skip to content

Commit 83d3d78

Browse files
committed
fix: raise ValueError when clear() called on metric without labels (#1140)
Metrics without labels never initialize _lock or _metrics (only parent metrics with labelnames do). Calling clear() on such a metric raised an unhelpful AttributeError. Guard with the same ValueError pattern that remove() already uses, matching maintainer guidance that clear() is not intended for label-less metrics. Fixes #1140. Also addresses duplicate #949.
1 parent 6133347 commit 83d3d78

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+
raise ValueError('No label names were set when constructing %s' % self)
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
@@ -620,6 +620,12 @@ def test_clear(self):
620620
self.assertEqual(None, self.registry.get_sample_value('c_total', {'l': 'x'}))
621621
self.assertEqual(None, self.registry.get_sample_value('c_total', {'l': 'y'}))
622622

623+
def test_clear_no_labels_raises(self):
624+
"""clear() on a metric without labels should raise ValueError, not AttributeError."""
625+
no_labels = Counter('c_no_labels', 'help', registry=self.registry)
626+
no_labels.inc()
627+
self.assertRaises(ValueError, no_labels.clear)
628+
623629
def test_incorrect_label_count_raises(self):
624630
self.assertRaises(ValueError, self.counter.labels)
625631
self.assertRaises(ValueError, self.counter.labels, 'a', 'b')

0 commit comments

Comments
 (0)