8000 Annotate few functions and methods (#705) · reinaldoca/client_python@822b8e9 · GitHub
[go: up one dir, main page]

Skip to content

Commit 822b8e9

Browse files
authored
Annotate few functions and methods (prometheus#705)
Signed-off-by: Derek Kulinski <d@kulinski.us>
1 parent ff19604 commit 822b8e9

File tree

7 files changed

+69
-54
lines changed

7 files changed

+69
-54
lines changed

prometheus_client/context_managers.py

Lines changed: 13 additions & 4 deletions
< 8000 tr class="diff-line-row">
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,30 @@
11
from timeit import default_timer
2+
from types import TracebackType
3+
from typing import (
4+
Any, Callable, Literal, Optional, Type, TYPE_CHECKING, TypeVar,
5+
)
26

37
from .decorator import decorate
48

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

614
class ExceptionCounter:
7-
def __init__(self, counter, exception):
15+
def __init__(self, counter: "Counter", exception: Type[BaseException]) -> None:
816
self._counter = counter
917
self._exception = exception
1018

11-
def __enter__(self):
19+
def __enter__(self) -> None:
1220
pass
1321

14-
def __exit__(self, typ, value, traceback):
22+
def __exit__(self, typ: Optional[Type[BaseException]], value: Optional[BaseException], traceback: Optional[TracebackType]) -> Literal[False]:
1523
if isinstance(value, self._exception):
1624
self._counter.inc()
25+
return False
1726

18-
def __call__(self, f):
27+
def __call__(self, f: "F") -> "F":
1928
def wrapped(func, *args, **kwargs):
2029
with self:
2130
return func(*args, **kwargs)

prometheus_client/metrics.py

Lines changed: 38 additions & 32 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 = ''
@@ -56,8 +62,8 @@ def _validate_exemplar(exemplar):
5662

5763

5864
class MetricWrapperBase:
59-
_type = None
60-
_reserved_labelnames = ()
65+
_type: Optional[str] = None
66+
_reserved_labelnames: Sequence[str] = ()
6167

6268
def _is_observable(self):
6369
# Whether this metric is observable, i.e.
@@ -94,20 +100,20 @@ def __repr__(self):
94100
metric_type = type(self)
95101
return f"{metric_type.__module__}.{metric_type.__name__}({self._name})"
96102

97-
def __init__(self,
98-
name,
99-
documentation,
100-
labelnames=(),
101-
namespace='',
102-
subsystem='',
103-
unit='',
104-
registry=REGISTRY,
105-
_labelvalues=None,
106-
):
103+
def __init__(self: T,
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 ())
110-
self._kwargs = {}
116+
self._kwargs: Dict[str, Any] = {}
111117
self._documentation = documentation
112118
self._unit = unit
113119

@@ -117,7 +123,7 @@ def __init__(self,
117123
if self._is_parent():
118124
# Prepare the fields needed for child metrics.
119125
self._lock = Lock()
120-
self._metrics = {}
126+
self._metrics: Dict[Sequence[str], T] = {}
121127

122128
if self._is_observable():
123129
self._metric_init()
@@ -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 = {}
@@ -212,7 +218,7 @@ def _multi_samples(self):
212218
for suffix, sample_labels, value, timestamp, exemplar in metric._samples():
213219
yield (suffix, dict(series_labels + list(sample_labels.items())), value, timestamp, exemplar)
214220

215-
def _child_samples(self): # pragma: no cover
221+
def _child_samples(self) -> Sequence[Tuple[str, Dict[str, str], float]]: # pragma: no cover
216222
raise NotImplementedError('_child_samples() must be implemented by %r' % self)
217223

218224
def _metric_init(self): # pragma: no cover
@@ -258,12 +264,12 @@ def f():
258264
"""
259265
_type = 'counter'
260266

261-
def _metric_init(self):
267+
def _metric_init(self) -> None:
262268
self._value = values.ValueClass(self._type, self._name, self._name + '_total', self._labelnames,
263269
self._labelvalues)
264270
self._created = time.time()
265271

266-
def inc(self, amount=1, exemplar=None):
272+
def inc(self, amount: float=1, exemplar: Optional[Dict[str, str]]=None) -> None:
267273
"""Increment counter by the given amount."""
268274
self._raise_if_not_observable()
269275
if amount < 0:
@@ -273,7 +279,7 @@ def inc(self, amount=1, exemplar=None):
273279
_validate_exemplar(exemplar)
274280
self._value.set_exemplar(Exemplar(exemplar, amount, time.time()))
275281

276-
def count_exceptions(self, exception=Exception):
282+
def count_exceptions(self, exception: Type[BaseException]=Exception) -> ExceptionCounter:
277283
"""Count exceptions in a block of code or function.
278284
279285
Can be used as a function decorator or context manager.
@@ -667,15 +673,15 @@ class Enum(MetricWrapperBase):
667673
_type = 'stateset'
668674

669675
def __init__(self,
670-
name,
671-
documentation,
672-
labelnames=(),
673-
namespace='',
674-
subsystem='',
675-
unit='',
676-
registry=REGISTRY,
677-
_labelvalues=None,
678-
states=None,
676+
name: str,
677+
documentation: str,
678+
labelnames: Sequence[str]=(),
679+
namespace: str='',
680+
subsystem: str='',
681+
unit: str='',
682+
registry: CollectorRegistry=REGISTRY,
683+
_labelvalues: Optional[Sequence[str]]=None,
684+
states: Optional[Sequence[str]]=None,
679685
):
680686
super().__init__(
681687
name=name,
@@ -693,11 +699,11 @@ def __init__(self,
693699
raise ValueError(f'No states provided for Enum metric: {name}')
694700
self._kwargs['states'] = self._states = states
695701

696-
def _metric_init(self):
702+
def _metric_init(self) -> None:
697703
self._value = 0
698704
self._lock = Lock()
699705

700-
def state(self, state):
706+
def state(self, state: str) -> None:
701707
"""Set enum metric state."""
702708
self._raise_if_not_observable()
703709
with self._lock:

prometheus_client/openmetrics/parser.py

Lines changed: 1 addition & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,14 @@
11
#!/usr/bin/python
22

33

4+
import io as StringIO
45
import math
56
import re
67

78
from ..metrics_core import Metric, METRIC_LABEL_NAME_RE
89
from ..samples import Exemplar, Sample, Timestamp
910
from ..utils import floatToGoString
1011

11-
try:
12-
import StringIO
13-
except ImportError:
14-
# Python 3
15-
import io as StringIO
16-
1712

1813
def text_string_to_metric_families(text):
1914
"""Parse Openmetrics text format from a unicode string.

prometheus_client/parser.py

Lines changed: 1 addition & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,9 @@
1+
import io as StringIO
12
import re
23

34
from .metrics_core import Metric
45
from .samples import Sample
56

6-
try:
7-
import StringIO
8-
except ImportError:
9-
# Python 3
10-
import io as StringIO
11-
127

138
def text_string_to_metric_families(text):
149
"""Parse Prometheus text format from a unicode string.

prometheus_client/py.typed

Whitespace-only changes.

prometheus_client/samples.py

Lines changed: 13 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
from collections import namedtuple
1+
from typing import Dict, NamedTuple, Optional
22

33

44
class Timestamp:
@@ -36,8 +36,15 @@ def __gt__(self, other):
3636
# Timestamp can be a float containing a unixtime in seconds,
3737
# a Timestamp object, or None.
3838
# Exemplar can be an Exemplar object, or None.
39-
Sample = namedtuple('Sample', ['name', 'labels', 'value', 'timestamp', 'exemplar'])
40-
Sample.__new__.__defaults__ = (None, None)
41-
42-
Exemplar = namedtuple('Exemplar', ['labels', 'value', 'timestamp'])
43-
Exemplar.__new__.__defaults__ = (None,)
39+
class Exemplar(NamedTuple):
40+
labels: Dict[str, str]
41+
value: float
42+
timestamp: Optional[float] = None
43+
44+
45+
class Sample(NamedTuple):
46+
name: str
47+
labels: Dict[str, str]
48+
value: float
49+
timestamp: Optional[float] = None
50+
exemplar: Optional[Exemplar] = None

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)
0