|
| 1 | +"""A wrapper for functions that require the current state of the store.""" |
| 2 | + |
| 3 | +from __future__ import annotations |
| 4 | + |
| 5 | +import inspect |
| 6 | +from typing import TYPE_CHECKING, Concatenate, Generic |
| 7 | + |
| 8 | +from redux.basic_types import Action, Args, Event, ReturnType, SelectorOutput, State |
| 9 | + |
| 10 | +if TYPE_CHECKING: |
| 11 | + from collections.abc import Callable |
| 12 | + |
| 13 | + from redux.main import Store |
| 14 | + |
| 15 | + |
| 16 | +class WithState(Generic[State, Action, Event, SelectorOutput, ReturnType, Args]): |
| 17 | + """A wrapper for functions that require the current state of the store.""" |
| 18 | + |
| 19 | + def __init__( |
| 20 | + self: WithState, |
| 21 | + *, |
| 22 | + store: Store[State, Action, Event], |
| 23 | + selector: Callable[[State], SelectorOutput], |
| 24 | + func: Callable[ |
| 25 | + Concatenate[SelectorOutput, Args], |
| 26 | + ReturnType, |
| 27 | + ], |
| 28 | + ) -> None: |
| 29 | + """Initialize the WithState instance.""" |
| 30 | + self._store = store |
| 31 | + self._selector = selector |
| 32 | + self._func = func |
| 33 | + signature = inspect.signature(func) |
| 34 | + parameters = list(signature.parameters.values()) |
| 35 | + if parameters and parameters[0].kind in [ |
| 36 | + inspect.Parameter.POSITIONAL_ONLY, |
| 37 | + inspect.Parameter.POSITIONAL_OR_KEYWORD, |
| 38 | + ]: |
| 39 | + parameters = parameters[1:] |
| 40 | + self._signature = signature.replace(parameters=parameters) |
| 41 | + |
| 42 | + def __call__( |
| 43 | + self: WithState[ |
| 44 | + State, |
| 45 | + Action, |
| 46 | + Event, |
| 47 | + SelectorOutput, |
| 48 | + ReturnType, |
| 49 | + Args, |
| 50 | + ], |
| 51 | + *args: Args.args, |
| 52 | + **kwargs: Args.kwargs, |
| 53 | + ) -> ReturnType: |
| 54 | + """Call the wrapped function with the current state of the store.""" |
| 55 | + if self._store._state is None: # noqa: SLF001 |
| 56 | + msg = 'Store has not been initialized yet.' |
| 57 | + raise RuntimeError(msg) |
| 58 | + return self._func(self._selector(self._store._state), *args, **kwargs) # noqa: SLF001 |
| 59 | + |
| 60 | + def __repr__( |
| 61 | + self: WithState[ |
| 62 | + State, |
| 63 | + Action, |
| 64 | + Event, |
| 65 | + SelectorOutput, |
| 66 | + ReturnType, |
| 67 | + Args, |
| 68 | + ], |
| 69 | + ) -> str: |
| 70 | + """Return the string representation of the WithState instance.""" |
| 71 | + return super().__repr__() + f'(func: {self._func})' |
| 72 | + |
| 73 | + @property |
| 74 | + def __signature__( |
| 75 | + self: WithState[ |
| 76 | + State, |
| 77 | + Action, |
| 78 | + Event, |
| 79 | + SelectorOutput, |
| 80 | + ReturnType, |
| 81 | + Args, |
| 82 | + ], |
| 83 | + ) -> inspect.Signature: |
| 84 | + """Get the signature of the wrapped function.""" |
| 85 | + return self._signature |
0 commit comments