Created
April 9, 2024 16:11
-
-
Save steinerkelvin/2ce2f05783bf9eade62c3d44b43f1190 to your computer and use it in GitHub Desktop.
Typed Python getter-setter hook closure function
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, Generic, Protocol | |
| T = TypeVar("T") | |
| class SetterGetterFn(Generic[T], Protocol): | |
| def __call__(self, x: T = ..., /) -> T: | |
| ... | |
| def create_state_fn(default: Callable[..., T]) -> SetterGetterFn[T]: | |
| """ | |
| Creates a state function that can be used to get or set a value. | |
| """ | |
| value = default() | |
| def state_function(input: T | None = None): | |
| nonlocal value | |
| if input is not None: | |
| value = input | |
| return value | |
| return state_function | |
| a_bool_hook = create_state_fn(bool) | |
| print(a_bool_hook()) | |
| print(a_bool_hook(True)) | |
| print(a_bool_hook(False)) | |
| print(a_bool_hook()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment