1
1
from threading import Lock
2
2
import time
3
3
import types
4
+ from typing import (
5
+ Any , Callable , Dict , Optional , Sequence , Tuple , Type , TypeVar ,
6
+ )
4
7
5
8
from . import values # retain this import style for testability
6
9
from .context_managers import ExceptionCounter , InprogressTracker , Timer
7
10
from .metrics_core import (
8
11
Metric , METRIC_LABEL_NAME_RE , METRIC_NAME_RE ,
9
12
RESERVED_METRIC_LABEL_NAME_RE ,
10
13
)
11
- from .registry import REGISTRY
14
+ from .registry import CollectorRegistry , REGISTRY
12
15
from .samples import Exemplar
13
16
from .utils import floatToGoString , INF
14
17
18
+ T = TypeVar ('T' , bound = 'MetricWrapperBase' )
19
+ F = TypeVar ("F" , bound = Callable [..., Any ])
20
+
15
21
16
22
def _build_full_name (metric_type , name , namespace , subsystem , unit ):
17
23
full_name = ''
@@ -56,8 +62,8 @@ def _validate_exemplar(exemplar):
56
62
57
63
58
64
class MetricWrapperBase :
59
- _type = None
60
- _reserved_labelnames = ()
65
+ _type : Optional [ str ] = None
66
+ _reserved_labelnames : Sequence [ str ] = ()
61
67
62
68
def _is_observable (self ):
63
69
# Whether this metric is observable, i.e.
@@ -94,20 +100,20 @@ def
9E88
__repr__(self):
94
100
metric_type = type (self )
95
101
return f"{ metric_type .__module__ } .{ metric_type .__name__ } ({ self ._name } )"
96
102
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 :
107
113
self ._name = _build_full_name (self ._type , name , namespace , subsystem , unit )
108
114
self ._labelnames = _validate_labelnames (self , labelnames )
109
115
self ._labelvalues = tuple (_labelvalues or ())
110
- self ._kwargs = {}
116
+ self ._kwargs : Dict [ str , Any ] = {}
111
117
self ._documentation = documentation
112
118
self ._unit = unit
113
119
@@ -117,7 +123,7 @@ def __init__(self,
117
123
if self ._is_parent ():
118
124
# Prepare the fields needed for child metrics.
119
125
self ._lock = Lock ()
120
- self ._metrics = {}
126
+ self ._metrics : Dict [ Sequence [ str ], T ] = {}
121
127
122
128
if self ._is_observable ():
123
129
self ._metric_init ()
@@ -127,7 +133,7 @@ def __init__(self,
127
133
if registry :
128
134
registry .register (self )
129
135
130
- def labels (self , * labelvalues , ** labelkwargs ) :
136
+ def labels (self : T , * labelvalues : str , ** labelkwargs : str ) -> T :
131
137
"""Return the child for the given labelset.
132
138
133
139
All metrics can have labels, allowing grouping of related time series.
@@ -193,7 +199,7 @@ def remove(self, *labelvalues):
193
199
with self ._lock :
194
200
del self ._metrics [labelvalues ]
195
201
196
- def clear (self ):
202
+ def clear (self ) -> None :
197
203
"""Remove all labelsets from the metric"""
198
204
with self ._lock :
199
205
self ._metrics = {}
@@ -212,7 +218,7 @@ def _multi_samples(self):
212
218
for suffix , sample_labels , value , timestamp , exemplar in metric ._samples ():
213
219
yield (suffix , dict (series_labels + list (sample_labels .items ())), value , timestamp , exemplar )
214
220
215
- def _child_samples (self ): # pragma: no cover
221
+ def _child_samples (self ) -> Sequence [ Tuple [ str , Dict [ str , str ], float ]] : # pragma: no cover
216
222
raise NotImplementedError ('_child_samples() must be implemented by %r' % self )
217
223
218
224
def _metric_init (self ): # pragma: no cover
@@ -258,12 +264,12 @@ def f():
258
264
"""
259
265
_type = 'counter'
260
266
261
- def _metric_init (self ):
267
+ def _metric_init (self ) -> None :
262
268
self ._value = values .ValueClass (self ._type , self ._name , self ._name + '_total' , self ._labelnames ,
263
269
self ._labelvalues )
264
270
self ._created = time .time ()
265
271
266
- def inc (self , amount = 1 , exemplar = None ):
272
+ def inc (self , amount : float = 1 , exemplar : Optional [ Dict [ str , str ]] = None ) -> None :
267
273
"""Increment counter by the given amount."""
268
274
self ._raise_if_not_observable ()
269
275
if amount < 0 :
@@ -273,7 +279,7 @@ def inc(self, amount=1, exemplar=None):
273
279
_validate_exemplar (exemplar )
274
280
self ._value .set_exemplar (Exemplar (exemplar , amount , time .time ()))
275
281
276
- def count_exceptions (self , exception = Exception ):
282
+ def count_exceptions (self , exception : Type [ BaseException ] = Exception ) -> ExceptionCounter :
277
283
"""Count exceptions in a block of code or function.
278
284
279
285
Can be used as a function decorator or context manager.
@@ -667,15 +673,15 @@ class Enum(MetricWrapperBase):
667
673
_type = 'stateset'
668
674
669
675
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 ,
679
685
):
680
686
super ().__init__ (
681
687
name = name ,
@@ -693,11 +699,11 @@ def __init__(self,
693
699
raise ValueError (f'No states provided for Enum metric: { name } ' )
694
700
self ._kwargs ['states' ] = self ._states = states
695
701
696
- def _metric_init (self ):
702
+ def _metric_init (self ) -> None :
697
703
self ._value = 0
698
704
self ._lock = Lock ()
699
705
700
- def state (self , state ) :
706
+ def state (self , state : str ) -> None :
701
707
"""Set enum metric state."""
702
708
self ._raise_if_not_observable ()
703
709
with self ._lock :
0 commit comments