10000 Upgrade Python syntax with pyupgrade --py36-plus · prometheus/client_python@4fb81cc · GitHub
[go: up one dir, main page]

Skip to content

Commit 4fb81cc

Browse files
committed
Upgrade Python syntax with pyupgrade --py36-plus
Signed-off-by: Hugo van Kemenade <hugovk@users.noreply.github.com>
1 parent ac02b74 commit 4fb81cc

32 files changed

+113
-170
lines changed

prometheus_client/bridge/graphite.py

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
#!/usr/bin/python
2-
from __future__ import unicode_literals
32

43
import logging
54
import re
@@ -22,7 +21,7 @@ def _sanitize(s):
2221

2322
class _RegularPush(threading.Thread):
2423
def __init__(self, pusher, interval, prefix):
25-
super(_RegularPush, self).__init__()
24+
super().__init__()
2625
self._pusher = pusher
2726
self._interval = interval
2827
self._prefix = prefix
@@ -41,11 +40,11 @@ def run(self):
4140
time.sleep(wait_until - now)
4241
try:
4342
self._pusher.push(prefix=self._prefix)
44-
except IOError:
43+
except OSError:
4544
logging.exception("Push failed")
4645

4746

48-
class GraphiteBridge(object):
47+
class GraphiteBridge:
4948
def __init__(self, address, registry=REGISTRY, timeout_seconds=30, _timer=time.time, tags=False):
5049
self._address = address
5150
self._registry = registry
@@ -76,8 +75,7 @@ def push(self, prefix=''):
7675
for k, v in sorted(s.labels.items())])
7776
else:
7877
labelstr = ''
79-
output.append('{0}{1}{2} {3} {4}\n'.format(
80-
prefixstr, _sanitize(s.name), labelstr, float(s.value), now))
78+
output.append(f'{prefixstr}{_sanitize(s.name)}{labelstr} {float(s.value)} {now}\n')
8179

8280
conn = socket.create_connection(self._address, self._timeout)
8381
conn.sendall(''.join(output).encode('ascii'))

prometheus_client/context_managers.py

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,9 @@
1-
from __future__ import unicode_literals
2-
31
from timeit import default_timer
42

53
from .decorator import decorate
64

75

8-
class ExceptionCounter(object):
6+
class ExceptionCounter:
97
def __init__(self, counter, exception):
108
self._counter = counter
119
self._exception = exception
@@ -25,7 +23,7 @@ def wrapped(func, *args, **kwargs):
2523
return decorate(f, wrapped)
2624

2725

28-
class InprogressTracker(object):
26+
class InprogressTracker:
2927
def __init__(self, gauge):
3028
self._gauge = gauge
3129

@@ -43,7 +41,7 @@ def wrapped(func, *args, **kwargs):
4341
return decorate(f, wrapped)
4442

4543

46-
class Timer(object):
44+
class Timer:
4745
def __init__(self, callback):
4846
self._callback = callback
4947

prometheus_client/core.py

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,3 @@
1-
from __future__ import unicode_literals
2-
31
from .metrics import Counter, Enum, Gauge, Histogram, Info, Summary
42
from .metrics_core import (
53
CounterMetricFamily, GaugeHistogramMetricFamily, GaugeMetricFamily,

prometheus_client/decorator.py

Lines changed: 5 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -31,9 +31,9 @@
3131
Decorator module, see http://pypi.python.org/pypi/decorator
3232
for the documentation.
3333
"""
34-
from __future__ import print_function
3534

3635
import collections
36+
from contextlib import _GeneratorContextManager
3737
import inspect
3838
from inspect import getfullargspec
3939
import itertools
@@ -63,7 +63,7 @@ def getargspec(f):
6363

6464

6565
# basic functionality
66-
class FunctionMaker(object):
66+
class FunctionMaker:
6767
"""
6868
An object with the ability to create functions with a given signature.
6969
It has attributes name, doc, module, signature, defaults, dict and
@@ -100,7 +100,7 @@ def __init__(self, func=None, name=None, signature=None,
100100
allargs.append('*') # single star syntax
101101
for a in self.kwonlyargs:
102102
allargs.append('%s=None' % a)
103-
allshortargs.append('%s=%s' % (a, a))
103+
allshortargs.append(f'{a}={a}')
104104
if self.varkw:
105105
allargs.append('**' + self.varkw)
106106
allshortargs.append('**' + self.varkw)
@@ -154,7 +154,7 @@ def make(self, src_templ, evaldict=None, addsource=False, **attrs):
154154
self.shortsignature.split(',')])
155155
for n in names:
156156
if n in ('_func_', '_call_'):
157-
raise NameError('%s is overridden in\n%s' % (n, src))
157+
raise NameError(f'{n} is overridden in\n{src}')
158158

159159
if not src.endswith('\n'): # add a newline for old Pythons
160160
src += '\n'
@@ -240,8 +240,6 @@ def decorator(caller, _func=None):
240240

241241
# ####################### contextmanager ####################### #
242242

243-
from contextlib import _GeneratorContextManager
244-
245243

246244
class ContextManager(_GeneratorContextManager):
247245
def __call__(self, func):
@@ -329,7 +327,7 @@ def ancestors(*types):
329327
n_vas = len(vas)
330328
if n_vas > 1:
331329
raise RuntimeError(
332-
'Ambiguous dispatch for %s: %s' % (t, vas))
330+
f'Ambiguous dispatch for {t}: {vas}')
333331
elif n_vas == 1:
334332
va, = vas
335333
mro = type('t', (t, va), {}).__mro__[1:]

prometheus_client/exposition.py

Lines changed: 18 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,3 @@
1-
from __future__ import unicode_literals
2-
31
import base64
42
from contextlib import closing
53
from http.server import BaseHTTPRequestHandler
@@ -19,7 +17,7 @@
1917
from .registry import REGISTRY
2018
from .utils import floatToGoString
2119

22-
CONTENT_TYPE_LATEST = str('text/plain; version=0.0.4; charset=utf-8')
20+
CONTENT_TYPE_LATEST = 'text/plain; version=0.0.4; charset=utf-8'
2321
"""Content type of the latest text format"""
2422
PYTHON376_OR_NEWER = sys.version_info > (3, 7, 5)
2523

@@ -85,7 +83,7 @@ def _bake_output(registry, accept_header, params):
8583
if 'name[]' in params:
8684
registry = registry.restricted_registry(params['name[]'])
8785
output = encoder(registry)
88-
return str('200 OK'), (str('Content-Type'), content_type), output
86+
return '200 OK', ('Content-Type', content_type), output
8987

9088

9189
def make_wsgi_app(registry=REGISTRY):
@@ -97,8 +95,8 @@ def prometheus_app(environ, start_response):
9795
params = parse_qs(environ.get('QUERY_STRING', ''))
9896
if environ['PATH_INFO'] == '/favicon.ico':
9997
# Serve empty response for browsers
100-
status = str('200 OK')
101-
header = (str(''), str(''))
98+
status = '200 OK'
99+
header = ('', '')
102100
output = b''
103101
else:
104102
# Bake output
@@ -143,17 +141,16 @@ def generate_latest(registry=REGISTRY):
143141
def sample_line(line):
144142
if line.labels:
145143
labelstr = '{{{0}}}'.format(','.join(
146-
['{0}="{1}"'.format(
144+
['{}="{}"'.format(
147145
k, v.replace('\\', r'\\').replace('\n', r'\n').replace('"', r'\"'))
148146
for k, v in sorted(line.labels.items())]))
149147
else:
150148
labelstr = ''
151149
timestamp = ''
152150
if line.timestamp is not None:
153151
# Convert to milliseconds.
154-
timestamp = ' {0:d}'.format(int(float(line.timestamp) * 1000))
155-
return '{0}{1} {2}{3}\n'.format(
156-
line.name, labelstr, floatToGoString(line.value), timestamp)
152+
timestamp = f' {int(float(line.timestamp) * 1000):d}'
153+
return f'{line.name}{labelstr} {floatToGoString(line.value)}{timestamp}\n'
157154

158155
output = []
159156
for metric in registry.collect():
@@ -175,9 +172,9 @@ def sample_line(line):
175172
elif mtype == 'unknown':
176173
mtype = 'untyped'
177174

178-
output.append('# HELP {0} {1}\n'.format(
175+
output.append('# HELP {} {}\n'.format(
179176
mname, metric.documentation.replace('\\', r'\\').replace('\n', r'\n')))
180-
output.append('# TYPE {0} {1}\n'.format(mname, mtype))
177+
output.append(f'# TYPE {mname} {mtype}\n')
181178

182179
om_samples = {}
183180
for s in metric.samples:
@@ -193,9 +190,9 @@ def sample_line(line):
193190
raise
194191

195192
for suffix, lines in sorted(om_samples.items()):
196-
output.append('# HELP {0}{1} {2}\n'.format(metric.name, suffix,
197-
metric.documentation.replace('\\', r'\\').replace('\n', r'\n')))
198-
output.append('# TYPE {0}{1} gauge\n'.format(metric.name, suffix))
193+
output.append('# HELP {}{} {}\n'.format(metric.name, suffix,
194+
metric.documentation.replace('\\', r'\\').replace('\n', r'\n')))
195+
output.append(f'# TYPE {metric.name}{suffix} gauge\n')
199196
output.extend(lines)
200197
return ''.join(output).encode('utf-8')
201198

@@ -250,7 +247,7 @@ def write_to_textfile(path, registry):
250247
251248
This is intended for use with the Node exporter textfile collector.
252249
The path must end in .prom for the textfile collector to process it."""
253-
tmppath = '%s.%s.%s' % (path, os.getpid(), threading.current_thread().ident)
250+
tmppath = f'{path}.{os.getpid()}.{threading.current_thread().ident}'
254251
with open(tmppath, 'wb') as f:
255252
f.write(generate_latest(registry))
256253

@@ -270,8 +267,7 @@ def handle():
270267
request.add_header(k, v)
271268
resp = build_opener(base_handler).open(request, timeout=timeout)
272269
if resp.code >= 400:
273-
raise IOError("error talking to pushgateway: {0} {1}".format(
274-
resp.code, resp.msg))
270+
raise OSError(f"error talking to pushgateway: {resp.code} {resp.msg}")
275271

276272
return handle
277273

@@ -308,7 +304,7 @@ def handle():
308304
"""Handler that implements HTTP Basic Auth.
309305
"""
310306
if username is not None and password is not None:
311-
auth_value = '{0}:{1}'.format(username, password).encode('utf-8')
307+
auth_value = f'{username}:{password}'.encode()
312308
auth_token = base64.b64encode(auth_value)
313309
auth_header = b'Basic ' + auth_token
314310
headers.append(['Authorization', auth_header])
@@ -418,8 +414,8 @@ def _use_gateway(method, gateway, job, registry, grouping_key, timeout, handler)
418414
PYTHON376_OR_NEWER
419415
and gateway_url.scheme not in ['http', 'https']
420416
):
421-
gateway = 'http://{0}'.format(gateway)
422-
url = '{0}/metrics/{1}/{2}'.format(gateway, *_escape_grouping_key("job", job))
417+
gateway = f'http://{gateway}'
418+
url = '{}/metrics/{}/{}'.format(gateway, *_escape_grouping_key("job", job))
423419

424420
data = b''
425421
if method != 'DELETE':
@@ -428,7 +424,7 @@ def _use_gateway(method, gateway, job, registry, grouping_key, timeout, handler)
428424
if grouping_key is None:
429425
grouping_key = {}
430426
url += ''.join(
431-
'/{0}/{1}'.format(*_escape_grouping_key(str(k), str(v)))
427+
'/{}/{}'.format(*_escape_grouping_key(str(k), str(v)))
432428
for k, v in sorted(grouping_key.items()))
433429

434430
handler(

prometheus_client/gc_collector.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,11 @@
1-
from __future__ import unicode_literals
2-
31
import gc
42
import platform
53

64
from .metrics_core import CounterMetricFamily
75
from .registry import REGISTRY
86

97

10-
class GCCollector(object):
8+
class GCCollector:
119
"""Collector for Garbage collection statistics."""
1210

1311
def __init__(self, registry=REGISTRY):

prometheus_client/metrics.py

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,7 @@ def _validate_exemplar(exemplar):
5555
raise ValueError('Exemplar labels have %d UTF-8 characters, exceeding the limit of 128')
5656

5757

58-
class MetricWrapperBase(object):
58+
class MetricWrapperBase:
5959
_type = None
6060
_reserved_labelnames = ()
6161

@@ -88,11 +88,11 @@ def collect(self):
8888
return [metric]
8989

9090
def __str__(self):
91-
return "{0}:{1}".format(self._type, self._name)
91+
return f"{self._type}:{self._name}"
9292

9393
def __repr__(self):
9494
metric_type = type(self)
95-
return "{0}.{1}({2})".format(metric_type.__module__, metric_type.__name__, self._name)
95+
return f"{metric_type.__module__}.{metric_type.__name__}({self._name})"
9696

9797
def __init__(self,
9898
name,
@@ -154,7 +154,7 @@ def labels(self, *labelvalues, **labelkwargs):
154154
raise ValueError('No label names were set when constructing %s' % self)
155155

156156
if self._labelvalues:
157-
raise ValueError('%s already has labels set (%s); can not chain calls to .labels()' % (
157+
raise ValueError('{} already has labels set ({}); can not chain calls to .labels()'.format(
158158
self,
159159
dict(zip(self._labelnames, self._labelvalues))
160160
))
@@ -344,7 +344,7 @@ def __init__(self,
344344
self._multiprocess_mode = multiprocess_mode
345345
if multiprocess_mode not in self._MULTIPROC_MODES:
346346
raise ValueError('Invalid multiprocess mode: ' + multiprocess_mode)
347-
super(Gauge, self).__init__(
347+
super().__init__(
348348
name=name,
349349
documentation=documentation,
350350
labelnames=labelnames,
@@ -537,7 +537,7 @@ def __init__(self,
537537
buckets=DEFAULT_BUCKETS,
538538
):
539539
self._prepare_buckets(buckets)
540-
super(Histogram, self).__init__(
540+
super().__init__(
541541
name=name,
542542
documentation=documentation,
543543
labelnames=labelnames,
@@ -641,7 +641,7 @@ def _metric_init(self):
641641
def info(self, val):
642642
"""Set info metric."""
643643
if self._labelname_set.intersection(val.keys()):
644-
raise ValueError('Overlapping labels for Info metric, metric: %s child: %s' % (
644+
raise ValueError('Overlapping labels for Info metric, metric: {} child: {}'.format(
645645
self._labelnames, val))
646646
with self._lock:
647647
self._value = dict(val)
@@ -677,7 +677,7 @@ def __init__(self,
677677
_labelvalues=None,
678678
states=None,
679679
):
680-
super(Enum, self).__init__(
680+
super().__init__(
681681
name=name,
682682
documentation=documentation,
683683
labelnames=labelnames,
@@ -688,9 +688,9 @@ def __init__(self,
688688
_labelvalues=_labelvalues,
689689
)
690690
if name in labelnames:
691-
raise ValueError('Overlapping labels for Enum metric: %s' % (name,))
691+
raise ValueError(f'Overlapping labels for Enum metric: {name}')
692692
if not states:
693-
raise ValueError('No states provided for Enum metric: %s' % (name,))
693+
raise ValueError(f'No states provided for Enum metric: {name}')
694694
self._kwargs['states'] = self._states = states
695695

696696
def _metric_init(self):

prometheus_client/metrics_core.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111
RESERVED_METRIC_LABEL_NAME_RE = re.compile(r'^__.*$')
1212

1313

14-
class Metric(object):
14+
class Metric:
1515
"""A single metric family and its samples.
1616
1717
This is intended only for internal use by the instrumentation client.
@@ -50,7 +50,7 @@ def __eq__(self, other):
5050
and self.samples == other.samples)
5151

5252
def __repr__(self):
53-
return "Metric(%s, %s, %s, %s, %s)" % (
53+
return "Metric({}, {}, {}, {}, {})".format(
5454
self.name,
5555
self.documentation,
5656
self.type,

prometheus_client/mmap_dict.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,7 @@ def _read_all_values(data, used=0):
4545
pos += 8
4646

4747

48-
class MmapedDict(object):
48+
class MmapedDict:
4949
"""A dict of doubles, backed by an mmapped file.
5050
5151
The file starts with a 4 byte int, indicating how much of it is used.
@@ -94,7 +94,7 @@ def _init_value(self, key):
9494
encoded = key.encode('utf-8')
9595
# Pad to be 8-byte aligned.
9696
padded = encoded + (b' ' * (8 - (len(encoded) + 4) % 8))
97-
value = struct.pack('i{0}sd'.format(len(padded)).encode(), len(encoded), padded, 0.0)
97+
value = struct.pack(f'i{len(padded)}sd'.encode(), len(encoded), padded, 0.0)
9898
while self._used + len(value) > self._capacity:
9999
self._capacity *= 2
100100
self._f.truncate(self._capacity)

0 commit comments

Comments
 (0)
0