codekingpro/portable-devtools
114k
1"""Various helper functions."""2 3from __future__ import annotations4 5import sys6from collections.abc import Callable, Mapping7from functools import cached_property8from typing import Any, Generic, Protocol, TypeVar, overload9 10__all__ = ("under_cached_property", "cached_property")11 12 13if sys.version_info >= (3, 11):14 from typing import Self15else:16 Self = Any17 18_T = TypeVar("_T")19# We use Mapping to make it possible to use TypedDict, but this isn't20# technically type safe as we need to assign into the dict.21_Cache = TypeVar("_Cache", bound=Mapping[str, Any])22 23 24class _CacheImpl(Protocol[_Cache]):25 _cache: _Cache26 27 28class under_cached_property(Generic[_T]):29 """Use as a class method decorator.30 31 It operates almost exactly like32 the Python `@property` decorator, but it puts the result of the33 method it decorates into the instance dict after the first call,34 effectively replacing the function it decorates with an instance35 variable. It is, in Python parlance, a data descriptor.36 """37 38 def __init__(self, wrapped: Callable[[Any], _T]) -> None:39 self.wrapped = wrapped40 self.__doc__ = wrapped.__doc__41 self.name = wrapped.__name__42 43 @overload44 def __get__(self, inst: None, owner: type[object] | None = None) -> Self: ...45 46 @overload47 def __get__(48 self, inst: _CacheImpl[Any], owner: type[object] | None = None49 ) -> _T: ...50 51 def __get__(52 self, inst: _CacheImpl[Any] | None, owner: type[object] | None = None53 ) -> _T | Self:54 if inst is None:55 return self56 try:57 return inst._cache[self.name] # type: ignore[no-any-return]58 except KeyError:59 val = self.wrapped(inst)60 inst._cache[self.name] = val61 return val62 63 def __set__(self, inst: _CacheImpl[Any], value: _T) -> None:64 raise AttributeError("cached property is read-only")65 