Hacktoberfest 2026: những issue maintainer đã đánh dấu cho tháng Mười, đang mở và phù hợp người mới. Xem issue Hacktoberfest

MetricWrapperBase labels() method static typing for label names

Đang mở
#860 0 bình luận 1 reaction 0 người được giao Xem trên GitHub

Chưa có ai nhận issue này.

Đánh giá

Độ khó
5/5
Thời gian dự kiến
Hơn một tuần
Mức phù hợp với người mới
30/100
Loại issue
Tính năng
Độ rõ ràng
Cần làm rõ
Mức độ hoạt động
Đình trệ
Công nghệ
python
Lĩnh vực
developer-experience

Hướng nghiên cứu

Bắt đầu bằng cách xem xét MetricWrapperBase và phương thức labels của nó, cùng với các ý tưởng về TypeVarTuple và typing_extensions được mô tả trong issue. Xác định xem có thể sử dụng một phương pháp kiểm tra được bằng kiểu để duy trì cách sử dụng label và đối số từ khóa hiện tại hay không; công việc được xem là hoàn tất khi thiết kế được chọn phát hiện các đối số label không khớp mà không làm hỏng khả năng tương thích ngược.

Do mô hình lập chỉ mục viết ra từ nội dung của issue.

Mô tả

Hi, recently I was thinking about possible improvement for MetricWrapperBase and friends labels method.

Very common use case is described even in Counter's docstring:

from prometheus_client import Counter

c = Counter('my_requests_total', 'HTTP Failures', ['method', 'endpoint'])
c.labels('get', '/').inc()
c.labels('post', '/submit').inc()

But when having N different counters, especially with different number of label names, and legacy large codebase or just very hard to test edge cases in your code (or the effort to test them all is not acceptable for some reason) where you use metrics, after some time you end up with typo errors when number of arguments do not match those specified, for example with above example counter:

try:
    do_something()
except VeryRareException:
    if int(time.time()) % 99999 == 0: 
          c.labels('get').inc() # Surprise!!! ValueError

Maybe we can do better somehow? This would be extra useful if we could pass label names like ['method', 'endpoint'] in a way that type checkers could understand and yield errors even before actually running code. Ideally with 100% backward compability with existing implementations (that one will be hard).

To just give some silly ideas, there is for example TypeVarTuple https://docs.python.org/3/library/typing.html#typing.TypeVarTuple that could at least do the job but only with partial backward compability, here PoC for MetricWrapperBase:

Disclaimer both TypeVarTuple and Self are Python 3.11+

from typing import TypeVarTuple, Self

...

LabelNames = TypeVarTuple("LabelNames")

class MetricWrapperBase(Collector,Generic[*LabelNames]):
    ...
    def __init__(self,
                 name: str,
                 documentation: str,
                 labelnames: tuple[*LabelNames] = (),
                 namespace: str = '',
                 subsystem: str = '',
                 unit: str = '',
                 registry: Optional[CollectorRegistry] = REGISTRY,
                 _labelvalues: Optional[Sequence[str]] = None,
                 ) -> None:
                 ...

    def labels(self: T, *labelvalues: *LabelNames) -> Self:
        ... # breaking changes there, only args

With that we have desire result

x = MetricWrapperBase("x", "y", ("short name", "data"))
x.labels("Ok name", "Ok data")
x.labels("Forgot second arg")

image

Of course this is very far from perfect, note only tuples could be used (no list) and in labels only args not kwargs. Also Python 3.11 is questionable but there is typing_extensions lib plus that could always live as a optional stubs only or some nasty overloads.

I am not by any means python typing ninja, but maybe someone could come up with better ideas! Or have some thoughts on this topic, I am observing new typing features on every python release, there may be now solutions that didn't exist couple of years ago.

Ngôn ngữ chính
Python
Star
4.4k
Fork
876
Merge trung bình
8 ngày 4 giờ
Pull request đã merge (30 ngày)
1

Hướng dẫn đóng góp

Mở hướng dẫn đóng góp

Bắt đầu từ đâu

  1. Đọc hết issue, rồi đọc hướng dẫn đóng góp của dự án.
  2. Bình luận trên issue rằng bạn sẽ nhận — tránh hai người làm cùng một việc.
  3. Fork repository và làm thay đổi trên một nhánh.
  4. Mở pull request có tham chiếu số hiệu của issue.

Issue khác của prometheus/client_python

Tất cả issue của prometheus/client_python

Issue tương tự

Thêm issue về Python

Nhận issue mới trong hộp thư của bạn

Bản tóm tắt ngắn những issue GitHub phù hợp với người mới.