Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Gauge typing improvement #935

Merged
merged 3 commits into from
Jul 18, 2023
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
9 changes: 3 additions & 6 deletions prometheus_client/context_managers.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,10 @@
import sys
from timeit import default_timer
from types import TracebackType
from typing import (
Any, Callable, Optional, Tuple, Type, TYPE_CHECKING, TypeVar, Union,
Any, Callable, Literal, Optional, Tuple, Type, TYPE_CHECKING, TypeVar,
Union,
)

if sys.version_info >= (3, 8, 0):
from typing import Literal

from .decorator import decorate

if TYPE_CHECKING:
Expand All @@ -23,7 +20,7 @@ def __init__(self, counter: "Counter", exception: Union[Type[BaseException], Tup
def __enter__(self) -> None:
pass

def __exit__(self, typ: Optional[Type[BaseException]], value: Optional[BaseException], traceback: Optional[TracebackType]) -> "Literal[False]":
def __exit__(self, typ: Optional[Type[BaseException]], value: Optional[BaseException], traceback: Optional[TracebackType]) -> Literal[False]:
if isinstance(value, self._exception):
self._counter.inc()
return False
Expand Down
63 changes: 18 additions & 45 deletions prometheus_client/decorator.py
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This file is actually copied from https://github.com/micheles/decorator to avoid any dependencies and we do not want to modify it locally. At some point i need to update the version, but for now can we just keep it the same?

Original file line number Diff line number Diff line change
Expand Up @@ -35,40 +35,18 @@

import collections
import inspect
from inspect import getfullargspec
import itertools
import operator
import re
import sys

__version__ = '4.0.10'

if sys.version_info >= (3,):
from inspect import getfullargspec

def get_init(cls):
return cls.__init__

def get_init(cls):
return cls.__init__
else:
class getfullargspec(object):
"A quick and dirty replacement for getfullargspec for Python 2.X"

def __init__(self, f):
self.args, self.varargs, self.varkw, self.defaults = \
inspect.getargspec(f)
self.kwonlyargs = []
self.kwonlydefaults = None

def __iter__(self):
yield self.args
yield self.varargs
yield self.varkw
yield self.defaults

getargspec = inspect.getargspec


def get_init(cls):
return cls.__init__.__func__

# getargspec has been deprecated in Python 3.5
ArgSpec = collections.namedtuple(
Expand Down Expand Up @@ -113,26 +91,21 @@ def __init__(self, func=None, name=None, signature=None,
setattr(self, a, getattr(argspec, a))
for i, arg in enumerate(self.args):
setattr(self, 'arg%d' % i, arg)
if sys.version_info < (3,): # easy way
self.shortsignature = self.signature = (
inspect.formatargspec(
formatvalue=lambda val: "", *argspec)[1:-1])
else: # Python 3 way
allargs = list(self.args)
allshortargs = list(self.args)
if self.varargs:
allargs.append('*' + self.varargs)
allshortargs.append('*' + self.varargs)
elif self.kwonlyargs:
allargs.append('*') # single star syntax
for a in self.kwonlyargs:
allargs.append('%s=None' % a)
allshortargs.append('%s=%s' % (a, a))
if self.varkw:
allargs.append('**' + self.varkw)
allshortargs.append('**' + self.varkw)
self.signature = ', '.join(allargs)
self.shortsignature = ', '.join(allshortargs)
allargs = list(self.args)
allshortargs = list(self.args)
if self.varargs:
allargs.append('*' + self.varargs)
allshortargs.append('*' + self.varargs)
elif self.kwonlyargs:
allargs.append('*') # single star syntax
for a in self.kwonlyargs:
allargs.append('%s=None' % a)
allshortargs.append('%s=%s' % (a, a))
if self.varkw:
allargs.append('**' + self.varkw)
allshortargs.append('**' + self.varkw)
self.signature = ', '.join(allargs)
self.shortsignature = ', '.join(allshortargs)
self.dict = func.__dict__.copy()
# func=None happens when decorating a caller
if name:
Expand Down
6 changes: 1 addition & 5 deletions prometheus_client/exposition.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,6 @@

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


class _PrometheusRedirectHandler(HTTPRedirectHandler):
Expand Down Expand Up @@ -545,10 +544,7 @@ def _use_gateway(
) -> None:
gateway_url = urlparse(gateway)
# See https://bugs.python.org/issue27657 for details on urlparse in py>=3.7.6.
if not gateway_url.scheme or (
PYTHON376_OR_NEWER
and gateway_url.scheme not in ['http', 'https']
):
if not gateway_url.scheme or gateway_url.scheme not in ['http', 'https']:
gateway = f'http://{gateway}'

gateway = gateway.rstrip('/')
Expand Down
6 changes: 3 additions & 3 deletions prometheus_client/metrics.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@
import time
import types
from typing import (
Any, Callable, Dict, Iterable, List, Optional, Sequence, Tuple, Type,
TypeVar, Union,
Any, Callable, Dict, Iterable, List, Literal, Optional, Sequence, Tuple,
Type, TypeVar, Union,
)

from . import values # retain this import style for testability
Expand Down Expand Up @@ -357,7 +357,7 @@ def __init__(self,
unit: str = '',
registry: Optional[CollectorRegistry] = REGISTRY,
_labelvalues: Optional[Sequence[str]] = None,
multiprocess_mode: str = 'all',
multiprocess_mode: Literal['all', 'liveall', 'min', 'livemin', 'max', 'livemax', 'sum', 'livesum'] = 'all',
):
self._multiprocess_mode = multiprocess_mode
if multiprocess_mode not in self._MULTIPROC_MODES:
Expand Down