Skip to content

Commit da5953e

Browse files
author
Derek Kulinski
committed
Annotate few functions and methods
1 parent 09fb459 commit da5953e

5 files changed

Lines changed: 32 additions & 1 deletion

File tree

prometheus_client/context_managers.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,23 +1,34 @@
11
from __future__ import unicode_literals
22

33
from timeit import default_timer
4+
from types import TracebackType
5+
from typing import Any, Callable, Optional, TYPE_CHECKING, Type, TypeVar
46

57
from .decorator import decorate
68

9+
if TYPE_CHECKING:
10+
from . import Counter
11+
F = TypeVar("F", bound=Callable[..., Any])
12+
713

814
class ExceptionCounter(object):
915
def __init__(self, counter, exception):
16+
# type: (Counter, Type[BaseException]) -> None
1017
self._counter = counter
1118
self._exception = exception
1219

1320
def __enter__(self):
21+
# type: () -> None
1422
pass
1523

1624
def __exit__(self, typ, value, traceback):
25+
# type: (Optional[Type[BaseException]], Optional[BaseException] , Optional[TracebackType]) -> bool
1726
if isinstance(value, self._exception):
1827
self._counter.inc()
28+
return False
1929

2030
def __call__(self, f):
31+
# type: (F) -> F
2132
def wrapped(func, *args, **kwargs):
2233
with self:
2334
return func(*args, **kwargs)

prometheus_client/decorator.py

Lines changed: 4 additions & 0 deletions
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 TypeVar, Callable, Any
43+
44+
F = TypeVar("F", bound=Callable[..., Any])
4245

4346
__version__ = '4.0.10'
4447

@@ -227,6 +230,7 @@ def create(cls, obj, body, evaldict, defaults=None,
227230

228231

229232
def decorate(func, caller):
233+
# type: (F, F) -> F
230234
"""
231235
decorate(func, caller) decorates a function using a caller.
232236
"""

prometheus_client/metrics.py

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,16 +2,20 @@
22
from threading import Lock
33
import time
44
import types
5+
from typing import Any, Callable, Dict, Optional, Sequence, Tuple, Type, TypeVar
56

67
from . import values # retain this import style for testability
78
from .context_managers import ExceptionCounter, InprogressTracker, Timer
89
from .metrics_core import (
910
Metric, METRIC_LABEL_NAME_RE, METRIC_NAME_RE,
1011
RESERVED_METRIC_LABEL_NAME_RE,
1112
)
12-
from .registry import REGISTRY
13+
from .registry import CollectorRegistry, REGISTRY
1314
from .utils import floatToGoString, INF
1415

16+
T = TypeVar('T', bound='MetricWrapperBase')
17+
F = TypeVar("F", bound=Callable[..., Any])
18+
1519
if sys.version_info > (3,):
1620
unicode = str
1721
create_bound_method = types.MethodType
@@ -97,6 +101,7 @@ def __init__(self,
97101
registry=REGISTRY,
98102
_labelvalues=None,
99103
):
104+
# type: (str, str, Sequence[str], str, str, str, CollectorRegistry, Optional[Sequence[str]]) -> None
100105
self._name = _build_full_name(self._type, name, namespace, subsystem, unit)
101106
self._labelnames = _validate_labelnames(self, labelnames)
102107
self._labelvalues = tuple(_labelvalues or ())
@@ -121,6 +126,7 @@ def __init__(self,
121126
registry.register(self)
122127

123128
def labels(self, *labelvalues, **labelkwargs):
129+
# type: (T, *str, **str) -> T
124130
"""Return the child for the given labelset.
125131
126132
All metrics can have labels, allowing grouping of related time series.
@@ -187,6 +193,7 @@ def remove(self, *labelvalues):
187193
del self._metrics[labelvalues]
188194

189195
def clear(self):
196+
# type: () -> None
190197
"""Remove all labelsets from the metric"""
191198
with self._lock:
192199
self._metrics = {}
@@ -206,6 +213,7 @@ def _multi_samples(self):
206213
yield (suffix, dict(series_labels + list(sample_labels.items())), value)
207214

208215
def _child_samples(self): # pragma: no cover
216+
# type: () -> Sequence[Tuple[str, Dict[str, str], float]]
209217
raise NotImplementedError('_child_samples() must be implemented by %r' % self)
210218

211219
def _metric_init(self): # pragma: no cover
@@ -252,18 +260,21 @@ def f():
252260
_type = 'counter'
253261

254262
def _metric_init(self):
263+
# type: () -> None
255264
self._value = values.ValueClass(self._type, self._name, self._name + '_total', self._labelnames,
256265
self._labelvalues)
257266
self._created = time.time()
258267

259268
def inc(self, amount=1):
269+
# type: (float) -> None
260270
"""Increment counter by the given amount."""
261271
self._raise_if_not_observable()
262272
if amount < 0:
263273
raise ValueError('Counters can only be incremented by non-negative amounts.')
264274
self._value.inc(amount)
265275

266276
def count_exceptions(self, exception=Exception):
277+
# type: (Type[BaseException]) -> ExceptionCounter
267278
"""Count exceptions in a block of code or function.
268279
269280
Can be used as a function decorator or context manager.
@@ -663,6 +674,7 @@ def __init__(self,
663674
_labelvalues=None,
664675
states=None,
665676
):
677+
# type: (str, str, Sequence[str], str, str, str, CollectorRegistry, Optional[Sequence[str]], Optional[Sequence[str]]) -> None
666678
super(Enum, self).__init__(
667679
name=name,
668680
documentation=documentation,
@@ -684,6 +696,7 @@ def _metric_init(self):
684696
self._lock = Lock()
685697

686698
def state(self, state):
699+
# type: (str) -> None
687700
"""Set enum metric state."""
688701
self._raise_if_not_observable()
689702
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
@@ -27,6 +27,9 @@
2727
'prometheus_client.openmetrics',
2828
'prometheus_client.twisted',
2929
],
30+
package_data = {
31+
'prometheus_client': ['py.typed']
32+
},
3033
extras_require={
3134
'twisted': ['twisted'],
3235
},

0 commit comments

Comments
 (0)