Skip to content

Conversation

@veeceey
Copy link
Contributor

@veeceey veeceey commented Feb 8, 2026

Summary

Adds a clear() method to CollectorRegistry that removes all collectors from the registry at once. This reduces boilerplate when clearing registries, as users no longer need to manually unregister each collector individually.

Changes

  • Added clear() method to CollectorRegistry class in prometheus_client/registry.py
  • Added test case test_clear_works() to verify the method works correctly
  • The method clears all collectors and resets the target_info

Usage Example

Before:

registry = CollectorRegistry()
g1 = Gauge("Metric1", "Description1", registry=registry)
g2 = Gauge("Metric2", "Description2", registry=registry)
g3 = Gauge("Metric3", "Description3", registry=registry)

# Remove the gauges from the registry manually
registry.unregister(g1)
registry.unregister(g2)
registry.unregister(g3)

After:

registry = CollectorRegistry()
g1 = Gauge("Metric1", "Description1", registry=registry)
g2 = Gauge("Metric2", "Description2", registry=registry)
g3 = Gauge("Metric3", "Description3", registry=registry)

# Remove all collectors at once
registry.clear()

Test Plan

  • Added comprehensive test case that verifies:
    • Multiple metrics can be registered
    • clear() removes all collectors
    • After clearing, the same metric names can be registered again without conflicts
  • All existing tests still pass

Fixes #1141

This commit adds a clear() method to CollectorRegistry that removes
all collectors from the registry at once, reducing boilerplate when
clearing registries.

Fixes prometheus#1141

Signed-off-by: Varun Chawla <varun_6april@hotmail.com>
@veeceey veeceey force-pushed the fix/issue-1141-add-registry-clear-method branch from d9e3278 to b00ed3e Compare February 8, 2026 07:38
@csmarchbanks
Copy link
Member

Thank you for your contribution! That said, I don't think we want a clear() method on CollectorRegistry so I am going to close this. I described why I think it is a problematic behavior to support in #1141 (comment).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Add clear() function to CollectorRegistry.

2 participants