_thunk.py 625 B

12345678910111213141516171819202122232425262728
  1. from typing import Callable, Generic, Optional, TypeVar
  2. R = TypeVar("R")
  3. class Thunk(Generic[R]):
  4. """
  5. A simple lazy evaluation implementation that lets you delay
  6. execution of a function. It properly handles releasing the
  7. function once it is forced.
  8. """
  9. f: Optional[Callable[[], R]]
  10. r: Optional[R]
  11. __slots__ = ["f", "r"]
  12. def __init__(self, f: Callable[[], R]):
  13. self.f = f
  14. self.r = None
  15. def force(self) -> R:
  16. if self.f is None:
  17. return self.r # type: ignore[return-value]
  18. self.r = self.f()
  19. self.f = None
  20. return self.r