Skip to content

Commit 0b78243

Browse files
committed
Annotate few functions and methods
Signed-off-by: Derek Kulinski <d@kulinski.us>
1 parent ff19604 commit 0b78243

File tree

5 files changed

+51
-31
lines changed

5 files changed

+51
-31
lines changed

prometheus_client/context_managers.py

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,28 @@
11
from timeit import default_timer
2+
from types import TracebackType
3+
from typing import Any, Callable, Optional, Type, TYPE_CHECKING, TypeVar
24

35
from .decorator import decorate
46

7+
if TYPE_CHECKING:
8+
from . import Counter
9+
F = TypeVar("F", bound=Callable[..., Any])
10+
511

612
class ExceptionCounter:
7-
def __init__(self, counter, exception):
13+
def __init__(self, counter: "Counter", exception: Type[BaseException]) -> None:
814
self._counter = counter
915
self._exception = exception
1016

11-
def __enter__(self):
17+
def __enter__(self) -> None:
1218
pass
1319

14-
def __exit__(self, typ, value, traceback):
20+
def __exit__(self, typ: Optional[Type[BaseException]], value: Optional[BaseException], traceback: Optional[TracebackType]) -> bool:
1521
if isinstance(value, self._exception):
1622
self._counter.inc()
23+
return False
1724

18-
def __call__(self, f):
25+
def __call__(self, f: "F") -> "F":
1926
def wrapped(func, *args, **kwargs):
2027
with self:
2128
return func(*args, **kwargs)

prometheus_client/decorator.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,9 @@
3939
import operator
4040
import re
4141
import sys
42+
from typing import Any, Callable, TypeVar
43+
44+
F = TypeVar("F", bound=Callable[..., Any])
4245

4346
__version__ = '4.0.10'
4447

@@ -226,7 +229,7 @@ def create(cls, obj, body, evaldict, defaults=None,
226229
evaldict, addsource, **attrs)
227230

228231

229-
def decorate(func, caller):
232+
def decorate(func: F, caller: F) -> F:
230233
"""
231234
decorate(func, caller) decorates a function using a caller.
232235
"""

prometheus_client/metrics.py

Lines changed: 33 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,23 @@
11
from threading import Lock
22
import time
33
import types
4+
from typing import (
5+
Any, Callable, Dict, Optional, Sequence, Tuple, Type, TypeVar,
6+
)
47

58
from . import values # retain this import style for testability
69
from .context_managers import ExceptionCounter, InprogressTracker, Timer
710
from .metrics_core import (
811
Metric, METRIC_LABEL_NAME_RE, METRIC_NAME_RE,
912
RESERVED_METRIC_LABEL_NAME_RE,
1013
)
11-
from .registry import REGISTRY
14+
from .registry import CollectorRegistry, REGISTRY
1215
from .samples import Exemplar
1316
from .utils import floatToGoString, INF
1417

18+
T = TypeVar('T', bound='MetricWrapperBase')
19+
F = TypeVar("F", bound=Callable[..., Any])
20+
1521

1622
def _build_full_name(metric_type, name, namespace, subsystem, unit):
1723
full_name = ''
@@ -95,15 +101,15 @@ def __repr__(self):
95101
return f"{metric_type.__module__}.{metric_type.__name__}({self._name})"
96102

97103
def __init__(self,
98-
name,
99-
documentation,
100-
labelnames=(),
101-
namespace='',
102-
subsystem='',
103-
unit='',
104-
registry=REGISTRY,
105-
_labelvalues=None,
106-
):
104+
name: str,
105+
documentation: str,
106+
labelnames: Sequence[str]=(),
107+
namespace: str='',
108+
subsystem: str='',
109+
unit: str='',
110+
registry: CollectorRegistry=REGISTRY,
111+
_labelvalues: Optional[Sequence[str]]=None,
112+
) -> None:
107113
self._name = _build_full_name(self._type, name, namespace, subsystem, unit)
108114
self._labelnames = _validate_labelnames(self, labelnames)
109115
self._labelvalues = tuple(_labelvalues or ())
@@ -127,7 +133,7 @@ def __init__(self,
127133
if registry:
128134
registry.register(self)
129135

130-
def labels(self, *labelvalues, **labelkwargs):
136+
def labels(self: T, *labelvalues: str, **labelkwargs: str) -> T:
131137
"""Return the child for the given labelset.
132138
133139
All metrics can have labels, allowing grouping of related time series.
@@ -193,7 +199,7 @@ def remove(self, *labelvalues):
193199
with self._lock:
194200
del self._metrics[labelvalues]
195201

196-
def clear(self):
202+
def clear(self) -> None:
197203
"""Remove all labelsets from the metric"""
198204
with self._lock:
199205
self._metrics = {}
@@ -213,6 +219,7 @@ def _multi_samples(self):
213219
yield (suffix, dict(series_labels + list(sample_labels.items())), value, timestamp, exemplar)
214220

215221
def _child_samples(self): # pragma: no cover
222+
# type: () -> Sequence[Tuple[str, Dict[str, str], float]]
216223
raise NotImplementedError('_child_samples() must be implemented by %r' % self)
217224

218225
def _metric_init(self): # pragma: no cover
@@ -258,12 +265,12 @@ def f():
258265
"""
259266
_type = 'counter'
260267

261-
def _metric_init(self):
268+
def _metric_init(self) -> None:
262269
self._value = values.ValueClass(self._type, self._name, self._name + '_total', self._labelnames,
263270
self._labelvalues)
264271
self._created = time.time()
265272

266-
def inc(self, amount=1, exemplar=None):
273+
def inc(self, amount: float=1, exemplar: Optional[Dict[str, str]]=None) -> None:
267274
"""Increment counter by the given amount."""
268275
self._raise_if_not_observable()
269276
if amount < 0:
@@ -273,7 +280,7 @@ def inc(self, amount=1, exemplar=None):
273280
_validate_exemplar(exemplar)
274281
self._value.set_exemplar(Exemplar(exemplar, amount, time.time()))
275282

276-
def count_exceptions(self, exception=Exception):
283+
def count_exceptions(self, exception: Type[BaseException]=Exception) -> ExceptionCounter:
277284
"""Count exceptions in a block of code or function.
278285
279286
Can be used as a function decorator or context manager.
@@ -667,15 +674,15 @@ class Enum(MetricWrapperBase):
667674
_type = 'stateset'
668675

669676
def __init__(self,
670-
name,
671-
documentation,
672-
labelnames=(),
673-
namespace='',
674-
subsystem='',
675-
unit='',
676-
registry=REGISTRY,
677-
_labelvalues=None,
678-
states=None,
677+
name: str,
678+
documentation: str,
679+
labelnames: Sequence[str]=(),
680+
namespace: str='',
681+
subsystem: str='',
682+
unit: str='',
683+
registry: CollectorRegistry=REGISTRY,
684+
_labelvalues: Optional[Sequence[str]]=None,
685+
states: Optional[Sequence[str]]=None,
679686
):
680687
super().__init__(
681688
name=name,
@@ -693,11 +700,11 @@ def __init__(self,
693700
raise ValueError(f'No states provided for Enum metric: {name}')
694701
self._kwargs['states'] = self._states = states
695702

696-
def _metric_init(self):
703+
def _metric_init(self) -> None:
697704
self._value = 0
698705
self._lock = Lock()
699706

700-
def state(self, state):
707+
def state(self, state: str) -> None:
701708
"""Set enum metric state."""
702709
self._raise_if_not_observable()
703710
with self._lock:

prometheus_client/py.typed

Whitespace-only changes.

setup.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,9 @@
2323
'prometheus_client.openmetrics',
2424
'prometheus_client.twisted',
2525
],
26+
package_data={
27+
'prometheus_client': ['py.typed']
28+
},
2629
extras_require={
2730
'twisted': ['twisted'],
2831
},

0 commit comments

Comments
 (0)