From 8a27f80b2353fa664ece9a97dedae120a16c1d48 Mon Sep 17 00:00:00 2001 From: Jakob van Santen Date: Thu, 19 Jan 2023 13:05:33 +0100 Subject: [PATCH] Allow tuples of exceptions in ExceptionCounter `ExceptionCounter.__exit__` kicks down to `isinstance`, which accepts either a single type or a tuple of types (or in Python 3.10, a UnionType). Update type annotations to reflect this. Signed-off-by: Jakob van Santen --- prometheus_client/context_managers.py | 6 ++++-- prometheus_client/metrics.py | 6 +++--- 2 files changed, 7 insertions(+), 5 deletions(-) diff --git a/prometheus_client/context_managers.py b/prometheus_client/context_managers.py index b229b17d..ef4db178 100644 --- a/prometheus_client/context_managers.py +++ b/prometheus_client/context_managers.py @@ -1,7 +1,9 @@ import sys from timeit import default_timer from types import TracebackType -from typing import Any, Callable, Optional, Type, TYPE_CHECKING, TypeVar +from typing import ( + Any, Callable, Optional, Tuple, Type, TYPE_CHECKING, TypeVar, Union, +) if sys.version_info >= (3, 8, 0): from typing import Literal @@ -14,7 +16,7 @@ class ExceptionCounter: - def __init__(self, counter: "Counter", exception: Type[BaseException]) -> None: + def __init__(self, counter: "Counter", exception: Union[Type[BaseException], Tuple[Type[BaseException], ...]]) -> None: self._counter = counter self._exception = exception diff --git a/prometheus_client/metrics.py b/prometheus_client/metrics.py index 45125b42..392e1e4d 100644 --- a/prometheus_client/metrics.py +++ b/prometheus_client/metrics.py @@ -3,8 +3,8 @@ import time import types from typing import ( - Any, Callable, Dict, Iterable, List, Optional, Sequence, Type, TypeVar, - Union, + Any, Callable, Dict, Iterable, List, Optional, Sequence, Tuple, Type, + TypeVar, Union, ) from . import values # retain this import style for testability @@ -288,7 +288,7 @@ def inc(self, amount: float = 1, exemplar: Optional[Dict[str, str]] = None) -> N _validate_exemplar(exemplar) self._value.set_exemplar(Exemplar(exemplar, amount, time.time())) - def count_exceptions(self, exception: Type[BaseException] = Exception) -> ExceptionCounter: + def count_exceptions(self, exception: Union[Type[BaseException], Tuple[Type[BaseException], ...]] = Exception) -> ExceptionCounter: """Count exceptions in a block of code or function. Can be used as a function decorator or context manager.