From e632a4ced2240acba6201218c3700cd6dfe724b2 Mon Sep 17 00:00:00 2001 From: Zixuan James Li <359101898@qq.com> Date: Wed, 13 Apr 2022 10:43:23 -0400 Subject: [PATCH] decorator: Strengthen decorator types using ParamSpec. Signed-off-by: Zixuan James Li <359101898@qq.com> --- zerver/decorator.py | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/zerver/decorator.py b/zerver/decorator.py index 934cb45bcb..be4710b235 100644 --- a/zerver/decorator.py +++ b/zerver/decorator.py @@ -24,6 +24,7 @@ from django.utils.translation import gettext as _ from django.views.decorators.csrf import csrf_exempt from django_otp import user_has_device from two_factor.utils import default_device +from typing_extensions import ParamSpec from zerver.lib.cache import cache_with_key from zerver.lib.exceptions import ( @@ -67,7 +68,8 @@ webhook_logger = logging.getLogger("zulip.zerver.webhooks") webhook_unsupported_events_logger = logging.getLogger("zulip.zerver.webhooks.unsupported") webhook_anomalous_payloads_logger = logging.getLogger("zulip.zerver.webhooks.anomalous") -FuncT = TypeVar("FuncT", bound=Callable[..., object]) +ParamT = ParamSpec("ParamT") +ReturnT = TypeVar("ReturnT") def update_user_activity( @@ -847,20 +849,22 @@ def to_utc_datetime(var_name: str, timestamp: str) -> datetime.datetime: return timestamp_to_datetime(float(timestamp)) -def statsd_increment(counter: str, val: int = 1) -> Callable[[FuncT], FuncT]: +def statsd_increment( + counter: str, val: int = 1 +) -> Callable[[Callable[ParamT, ReturnT]], Callable[ParamT, ReturnT]]: """Increments a statsd counter on completion of the decorated function. Pass the name of the counter to this decorator-returning function.""" - def wrapper(func: FuncT) -> FuncT: + def wrapper(func: Callable[ParamT, ReturnT]) -> Callable[ParamT, ReturnT]: @wraps(func) - def wrapped_func(*args: object, **kwargs: object) -> object: + def wrapped_func(*args: ParamT.args, **kwargs: ParamT.kwargs) -> ReturnT: ret = func(*args, **kwargs) statsd.incr(counter, val) return ret - return cast(FuncT, wrapped_func) # https://github.com/python/mypy/issues/1927 + return wrapped_func return wrapper