|
| 1 | +from functools import wraps |
| 2 | +from typing import Callable, Generic, TypeVar, Union |
| 3 | + |
| 4 | +from typing_extensions import ParamSpec, final |
| 5 | + |
| 6 | +_ReturnType = TypeVar('_ReturnType') |
| 7 | +_FuncParams = ParamSpec('_FuncParams') |
| 8 | + |
| 9 | + |
| 10 | +@final |
| 11 | +class Trampoline(Generic[_ReturnType]): |
| 12 | + """ |
| 13 | + Represents a wrapped function call. |
| 14 | +
|
| 15 | + Primitive to convert recursion into an actual object. |
| 16 | + """ |
| 17 | + |
| 18 | + __slots__ = ('func', 'args', 'kwargs') |
| 19 | + |
| 20 | + def __init__( # noqa: WPS451 |
| 21 | + self, |
| 22 | + func: Callable[_FuncParams, _ReturnType], |
| 23 | + /, # We use pos-only here to be able to store `kwargs` correctly. |
| 24 | + *args: _FuncParams.args, |
| 25 | + **kwargs: _FuncParams.kwargs, |
| 26 | + ) -> None: |
| 27 | + """Save function and given arguments.""" |
| 28 | + self.func = getattr(func, '_orig_func', func) |
| 29 | + self.args = args |
| 30 | + self.kwargs = kwargs |
| 31 | + |
| 32 | + def __call__(self) -> _ReturnType: |
| 33 | + """Call wrapped function with given arguments.""" |
| 34 | + return self.func(*self.args, **self.kwargs) |
| 35 | + |
| 36 | + |
| 37 | +def trampoline( |
| 38 | + func: Callable[_FuncParams, Union[_ReturnType, Trampoline[_ReturnType]]], |
| 39 | +) -> Callable[_FuncParams, _ReturnType]: |
| 40 | + """ |
| 41 | + Convert functions using recursion to regular functions. |
| 42 | +
|
| 43 | + Trampolines allow to unwrap recursion into a regular ``while`` loop, |
| 44 | + which does not raise any ``RecursionError`` ever. |
| 45 | +
|
| 46 | + Since python does not have TCO (tail call optimization), |
| 47 | + we have to provide this helper. |
| 48 | +
|
| 49 | + This is done by wrapping real function calls into |
| 50 | + :class:`returns.trampolines.Trampoline` objects: |
| 51 | +
|
| 52 | + .. code:: python |
| 53 | +
|
| 54 | + >>> from typing import Union |
| 55 | + >>> from returns.trampolines import Trampoline, trampoline |
| 56 | +
|
| 57 | + >>> @trampoline |
| 58 | + ... def get_factorial( |
| 59 | + ... for_number: int, |
| 60 | + ... current_number: int = 0, |
| 61 | + ... acc: int = 1, |
| 62 | + ... ) -> Union[int, Trampoline[int]]: |
| 63 | + ... assert for_number >= 0 |
| 64 | + ... if for_number <= current_number: |
| 65 | + ... return acc |
| 66 | + ... return Trampoline( |
| 67 | + ... get_factorial, |
| 68 | + ... for_number, |
| 69 | + ... current_number=current_number + 1, |
| 70 | + ... acc=acc * (current_number + 1), |
| 71 | + ... ) |
| 72 | +
|
| 73 | + >>> assert get_factorial(0) == 1 |
| 74 | + >>> assert get_factorial(3) == 6 |
| 75 | + >>> assert get_factorial(4) == 24 |
| 76 | +
|
| 77 | + See also: |
| 78 | + - eli.thegreenplace.net/2017/on-recursion-continuations-and-trampolines |
| 79 | + - https://en.wikipedia.org/wiki/Tail_call |
| 80 | +
|
| 81 | + """ |
| 82 | + |
| 83 | + @wraps(func) |
| 84 | + def decorator( |
| 85 | + *args: _FuncParams.args, |
| 86 | + **kwargs: _FuncParams.kwargs, |
| 87 | + ) -> _ReturnType: |
| 88 | + trampoline_result = func(*args, **kwargs) |
| 89 | + while isinstance(trampoline_result, Trampoline): |
| 90 | + trampoline_result = trampoline_result() |
| 91 | + return trampoline_result |
| 92 | + |
| 93 | + decorator._orig_func = func # type: ignore[attr-defined] # noqa: WPS437 |
| 94 | + return decorator |
0 commit comments