Created
October 20, 2022 19:26
-
-
Save benji-york/e278fa13beaca87b57ccae9233f972b1 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| from typing import Callable, TypeVar, ParamSpec, Iterable, Any | |
| import functools | |
| P = ParamSpec('P') | |
| Q = TypeVar('Q') | |
| R = TypeVar('R') | |
| def postprocess(post_func: Callable[[Q], R]) -> Callable[[Callable[P, Q]], Callable[P, R]]: | |
| """A decorator that filters a function's return value through a callable. | |
| >>> @postprocess(int) | |
| ... def number() -> str: | |
| ... return '42' | |
| >>> assert number() == 42 | |
| """ | |
| def decorator(decorated_func: Callable[P, Q]) -> Callable[P, R]: | |
| @functools.wraps(decorated_func) | |
| def wrapper(*args: P.args, **kwargs: P.kwargs) -> R: | |
| return post_func(decorated_func(*args, **kwargs)) | |
| return wrapper | |
| return decorator |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment