MetricWrapperBase labels() method static typing for label names
Ninguém assumiu esta issue ainda.
Avaliação
- Dificuldade
- 5/5
- Tempo estimado
- Mais de uma semana
- Facilidade para iniciantes
- 30/100
- Tipo de issue
- Funcionalidade
- Clareza
- Precisa de esclarecimento
- Status de atividade
- Estagnada
- Stack de tecnologia
- python
- Domínio
- developer-experience
Direção de pesquisa
Comece revisando MetricWrapperBase e seu método labels, juntamente com as ideias sobre TypeVarTuple e typing_extensions descritas na issue. Determine se uma abordagem verificável por tipos pode preservar o uso existente de labels e argumentos nomeados; considera-se concluído quando o design escolhido detectar argumentos de label incompatíveis sem quebrar a compatibilidade retroativa.
Escrita pelo modelo de indexação a partir do texto da issue.
Descrição
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")

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.
- Linguagem predominante
- Python
- Estrelas
- 4.4k
- Forks
- 876
- Merge médio
- 8d 4h
- PRs com merge (30d)
- 1
Guia de contribuição
Primeiros passos
- Leia a issue inteira e depois o guia de contribuição do projeto.
- Comente na issue dizendo que vai assumir — evita que duas pessoas façam o mesmo trabalho.
- Faça um fork do repositório e trabalhe em uma branch.
- Abra um pull request que referencie o número da issue.
Mais de prometheus/client_python
-
bug
Dificuldade 2/5 1-3 horas Facilidade para iniciantes 70/100
prometheus/client_python#1177 · 1 comentário ·
-
Dificuldade 4/5 3-5 dias Facilidade para iniciantes 45/100
prometheus/client_python#1210 ·
-
Dificuldade 2/5 1-3 horas Facilidade para iniciantes 58/100
prometheus/client_python#1199 · 1 reação ·
-
Dificuldade 5/5 Mais de uma semana Facilidade para iniciantes 35/100
prometheus/client_python#1176 ·
-
Dificuldade 1/5 1-3 horas Facilidade para iniciantes 52/100
prometheus/client_python#1126 · 2 comentários ·
Todas as issues de prometheus/client_python
Issues semelhantes
-
agent-ready documentation needs-triage
Dificuldade 1/5 1-3 horas Facilidade para iniciantes 88/100
-
documentation
Dificuldade 1/5 Menos de uma hora Facilidade para iniciantes 91/100
-
workflow-status page template still says reusable workflows are "triggered only by workflow_call:" Aberta
Dificuldade 1/5 Menos de uma hora Facilidade para iniciantes 92/100
-
instance instance add
Dificuldade 1/5 Menos de uma hora Facilidade para iniciantes 72/100
searxng/searx-instances#939 · 1 comentário ·
-
area-deployment area-integrations triage:bot-seen
Dificuldade 2/5 Meio dia Facilidade para iniciantes 86/100