From b8d9ed14c263eb256ee0ec4b7ae1497a12b9818d Mon Sep 17 00:00:00 2001 From: Justin Roberson Date: Thu, 16 Nov 2023 12:48:32 -0500 Subject: [PATCH] Add type information to LoggingContext.__call__ Adds a `DecoratedCallable` TypeVar and uses that in the type hints for the `__call__` method in `LoggingContext`. This allows type information to pass through correctly when used as a decorator. It seems like the `@wraps` decorator on the wrapper mangles the type info so I had to disable type checking on the return because Pyright was convinced it was wasn't the correct type, but the tests proved otherwise. I'm not sure there's a good way to test since at runtime the function signature is getting passed through correctly. It's only on the type checking pass that things break down. It's probably fine as-is since no tests broke as a result, but figured it was worth mentioning. Fixes #60 --- woodchipper/context.py | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/woodchipper/context.py b/woodchipper/context.py index 5707d2a..a3b4c00 100644 --- a/woodchipper/context.py +++ b/woodchipper/context.py @@ -5,12 +5,13 @@ from collections.abc import MutableMapping from decimal import Decimal from functools import wraps -from typing import Any, Mapping, NamedTuple, Optional, Tuple, Union, cast +from typing import Any, Callable, Mapping, NamedTuple, Optional, Tuple, TypeVar, Union, cast import woodchipper LoggableValue = Optional[Union[str, int, bool, Decimal, float]] LoggingContextType = Mapping[str, LoggableValue] +DecoratedCallable = TypeVar("DecoratedCallable", bound=Callable[..., Any]) class Missing: @@ -208,7 +209,7 @@ def __exit__(self, exc_type, exc_val, exc_tb): self._token = None return False - def __call__(self, f): + def __call__(self, f: DecoratedCallable) -> DecoratedCallable: self.decorator_mapping = _build_path_head_to_param_config_map( self.injected_context, delimiter=self.path_delimiter ) @@ -250,7 +251,7 @@ def wrapper(*func_args, **func_kwargs): with self: return f(*func_args, **func_kwargs) - return wrapper + return wrapper # type: ignore logging_ctx = LoggingContextVar("logging_ctx")