11from threading import Lock
22import time
33import types
4+ from typing import (
5+ Any , Callable , Dict , Optional , Sequence , Tuple , Type , TypeVar ,
6+ )
47
58from . import values # retain this import style for testability
69from .context_managers import ExceptionCounter , InprogressTracker , Timer
710from .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
1215from .samples import Exemplar
1316from .utils import floatToGoString , INF
1417
18+ T = TypeVar ('T' , bound = 'MetricWrapperBase' )
19+ F = TypeVar ("F" , bound = Callable [..., Any ])
20+
1521
1622def _build_full_name (metric_type , name , namespace , subsystem , unit ):
1723 full_name = ''
@@ -56,8 +62,8 @@ def _validate_exemplar(exemplar):
5662
5763
5864class 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 :
0 commit comments