Skip to content

Instantly share code, notes, and snippets.

@steinerkelvin
Created April 9, 2024 16:11
Show Gist options
  • Select an option

  • Save steinerkelvin/2ce2f05783bf9eade62c3d44b43f1190 to your computer and use it in GitHub Desktop.

Select an option

Save steinerkelvin/2ce2f05783bf9eade62c3d44b43f1190 to your computer and use it in GitHub Desktop.
Typed Python getter-setter hook closure function
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