Skip to content

Commit b9226ff

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

File tree

5 files changed

+37
-1
lines changed

5 files changed

+37
-1
lines changed

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, TYPE_CHECKING, 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 Any, Callable, TypeVar
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: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,16 +2,22 @@
22
from threading import Lock
33
import time
44
import types
5+
from typing import (
6+
Any, Callable, Dict, Optional, Sequence, Tuple, Type, TypeVar,
7+
)
58

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

18+
T = TypeVar('T', bound='MetricWrapperBase')
19+
F = TypeVar("F", bound=Callable[..., Any])
20+
1521
if sys.version_info > (3,):
1622
unicode = str
1723
create_bound_method = types.MethodType
@@ -97,6 +103,7 @@ def __init__(self,
97103
registry=REGISTRY,
98104
_labelvalues=None,
99105
):
106+
# type: (str, str, Sequence[str], str, str, str, CollectorRegistry, Optional[Sequence[str]]) -> None
100107
self._name = _build_full_name(self._type, name, namespace, subsystem, unit)
101108
self._labelnames = _validate_labelnames(self, labelnames)
102109
self._labelvalues = tuple(_labelvalues or ())
@@ -121,6 +128,7 @@ def __init__(self,
121128
registry.register(self)
122129

123130
def labels(self, *labelvalues, **labelkwargs):
131+
# type: (T, *str, **str) -> T
124132
"""Return the child for the given labelset.
125133
126134
All metrics can have labels, allowing grouping of related time series.
@@ -187,6 +195,7 @@ def remove(self, *labelvalues):
187195
del self._metrics[labelvalues]
188196

189197
def clear(self):
198+
# type: () -> None
190199
"""Remove all labelsets from the metric"""
191200
with self._lock:
192201
self._metrics = {}
@@ -206,6 +215,7 @@ def _multi_samples(self):
206215
yield (suffix, dict(series_labels + list(sample_labels.items())), value)
207216

208217
def _child_samples(self): # pragma: no cover
218+
# type: () -> Sequence[Tuple[str, Dict[str, str], float]]
209219
raise NotImplementedError('_child_samples() must be implemented by %r' % self)
210220

211221
def _metric_init(self): # pragma: no cover
@@ -252,18 +262,21 @@ def f():
252262
_type = 'counter'
253263

254264
def _metric_init(self):
265+
# type: () -> None
255266
self._value = values.ValueClass(self._type, self._name, self._name + '_total', self._labelnames,
256267
self._labelvalues)
257268
self._created = time.time()
258269

259270
def inc(self, amount=1):
271+
# type: (float) -> None
260272
"""Increment counter by the given amount."""
261273
self._raise_if_not_observable()
262274
if amount < 0:
263275
raise ValueError('Counters can only be incremented by non-negative amounts.')
264276
self._value.inc(amount)
265277

266278
def count_exceptions(self, exception=Exception):
279+
# type: (Type[BaseException]) -> ExceptionCounter
267280
"""Count exceptions in a block of code or function.
268281
269282
Can be used as a function decorator or context manager.
@@ -663,6 +676,7 @@ def __init__(self,
663676
_labelvalues=None,
664677
states=None,
665678
):
679+
# type: (str, str, Sequence[str], str, str, str, CollectorRegistry, Optional[Sequence[str]], Optional[Sequence[str]]) -> None
666680
super(Enum, self).__init__(
667681
name=name,
668682
documentation=documentation,
@@ -684,6 +698,7 @@ def _metric_init(self):
684698
self._lock = Lock()
685699

686700
def state(self, state):
701+
# type: (str) -> None
687702
"""Set enum metric state."""
688703
self._raise_if_not_observable()
689704
with self._lock:

prometheus_client/py.typed

Whitespace-only changes.

setup.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,12 @@
2727
'prometheus_client.openmetrics',
2828
'prometheus_client.twisted',
2929
],
30+
package_data={
31+
'prometheus_client': ['py.typed']
32+
},
33+
install_requires=[
34+
'typing; python_version<"3.5"'
35+
],
3036
extras_require={
3137
'twisted': ['twisted'],
3238
},

0 commit comments

Comments
 (0)