summaryrefslogtreecommitdiff
path: root/mesonbuild/utils
diff options
context:
space:
mode:
authorDylan Baker <dylan@pnwbakers.com>2025-01-08 08:55:19 -0800
committerEli Schwartz <eschwartz93@gmail.com>2025-01-08 13:45:26 -0500
commit7fd138dad98d698c9305c466f500a1df4fb0d74d (patch)
tree6557b09037d27b5537ca9deac4695b4e511d8a39 /mesonbuild/utils
parent95d0c40da5de2b85f11b9ccda93ed21969327464 (diff)
downloadmeson-7fd138dad98d698c9305c466f500a1df4fb0d74d.tar.gz
utils: Add a lazy property decorator
Diffstat (limited to 'mesonbuild/utils')
-rw-r--r--mesonbuild/utils/universal.py20
1 files changed, 20 insertions, 0 deletions
diff --git a/mesonbuild/utils/universal.py b/mesonbuild/utils/universal.py
index e2634b925..3ec23e105 100644
--- a/mesonbuild/utils/universal.py
+++ b/mesonbuild/utils/universal.py
@@ -130,6 +130,7 @@ __all__ = [
'is_wsl',
'iter_regexin_iter',
'join_args',
+ 'lazy_property',
'listify',
'listify_array_value',
'partition',
@@ -2379,3 +2380,22 @@ def first(iter: T.Iterable[_T], predicate: T.Callable[[_T], bool]) -> T.Optional
if predicate(i):
return i
return None
+
+
+class lazy_property(T.Generic[_T]):
+ """Descriptor that replaces the function it wraps with the value generated.
+
+ This property will only be calculated the first time it's queried, and will
+ be cached and the cached value used for subsequent calls.
+
+ This works by shadowing itself with the calculated value, in the instance.
+ Due to Python's MRO that means that the calculated value will be found
+ before this property, speeding up subsequent lookups.
+ """
+ def __init__(self, func: T.Callable[[T.Any], _T]):
+ self.__func = func
+
+ def __get__(self, instance: object, cls: T.Type) -> _T:
+ value = self.__func(instance)
+ setattr(instance, self.__func.__name__, value)
+ return value