Skip to content

Instantly share code, notes, and snippets.

@fakuivan
Created April 28, 2021 00:18
Show Gist options
  • Save fakuivan/217c1f47bcdf8155b34c7ff32b1e255e to your computer and use it in GitHub Desktop.
Save fakuivan/217c1f47bcdf8155b34c7ff32b1e255e to your computer and use it in GitHub Desktop.
Free variable function pairs in python
from typing import overload, Any, Tuple, Callable, TypeVar
T=TypeVar('T')
@overload
def free_var(initial: T) -> Tuple[Callable[[T], T], Callable[[], T]]: ...
@overload
def free_var(*, like: T) -> Tuple[Callable[[T], T], Callable[[], T]]: ...
def free_var(*args, **kwargs):
var: Any
def getter():
nonlocal var
return var
def setter(value):
nonlocal var
return (var := value)
if len(args) > 0:
setter(*args)
return setter, getter
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment