Skip to content

Instantly share code, notes, and snippets.

@benji-york
Created October 20, 2022 19:26
Show Gist options
  • Select an option

  • Save benji-york/e278fa13beaca87b57ccae9233f972b1 to your computer and use it in GitHub Desktop.

Select an option

Save benji-york/e278fa13beaca87b57ccae9233f972b1 to your computer and use it in GitHub Desktop.
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