Skip to content

Commit

Permalink
Add type information to LoggingContext.__call__
Browse files Browse the repository at this point in the history
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
  • Loading branch information
sapslaj committed Feb 6, 2024
1 parent 48e583d commit b8d9ed1
Showing 1 changed file with 4 additions and 3 deletions.
7 changes: 4 additions & 3 deletions woodchipper/context.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -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
)
Expand Down Expand Up @@ -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")

0 comments on commit b8d9ed1

Please # to comment.