Hacktoberfest 2026: los issues que los mantenedores marcaron para octubre, abiertos y aptos para principiantes. Explorar issues de Hacktoberfest

MetricWrapperBase labels() method static typing for label names

Abierto
#860 0 comentarios 1 reacción 0 asignados Ver en GitHub

Nadie ha tomado este issue todavía.

Evaluación

Dificultad
5/5
Tiempo estimado
Más de una semana
Aptitud para principiantes
30/100
Tipo de issue
Nueva funcionalidad
Claridad
Necesita aclaración
Estado de actividad
Estancado
Stack tecnológico
python

Línea de trabajo

Comienza revisando MetricWrapperBase y su método labels, junto con las ideas sobre TypeVarTuple y typing_extensions descritas en el issue. Determina si un enfoque que pueda comprobarse mediante tipos puede conservar el uso existente de labels y argumentos de palabra clave; se considera terminado cuando el diseño elegido detecta argumentos de label que no coinciden sin romper la compatibilidad hacia atrás.

Escrito por el modelo de indexación a partir del texto del issue.

Descripción

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.

Lenguaje dominante
Python
Estrellas
4.4k
Forks
876
Merge medio
8 d 4 h
PR fusionados (30 d)
1

Guía de contribución

Abrir la guía de contribución

Primeros pasos

  1. Lee el issue completo y luego la guía de contribución del proyecto.
  2. Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
  3. Haz un fork del repositorio y trabaja en una rama.
  4. Abre un pull request que haga referencia al número del issue.

Más de prometheus/client_python

Todos los issues de prometheus/client_python

Issues similares

Más issues de Python

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.