_thunk.py 644 B

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