decorator.py 568 B

12345678910111213141516171819202122232425
  1. """Decorator utilities."""
  2. from typing import Callable, TypeVar
  3. T = TypeVar("T")
  4. def once(f: Callable[[], T]) -> Callable[[], T]:
  5. """A decorator that calls the function once and caches the result.
  6. Args:
  7. f: The function to call.
  8. Returns:
  9. A function that calls the function once and caches the result.
  10. """
  11. unset = object()
  12. value: object | T = unset
  13. def wrapper() -> T:
  14. nonlocal value
  15. value = f() if value is unset else value
  16. return value # pyright: ignore[reportReturnType]
  17. return wrapper