From 6c7d1900408101239567ba2baba1fbb3cfff8f6e Mon Sep 17 00:00:00 2001 From: themylogin Date: Thu, 5 May 2022 21:42:18 +0200 Subject: [PATCH] `middlewared.utils.functools.cache` --- .../middlewared/utils/functools.py | 29 +++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 src/middlewared/middlewared/utils/functools.py diff --git a/src/middlewared/middlewared/utils/functools.py b/src/middlewared/middlewared/utils/functools.py new file mode 100644 index 0000000000000..b61781245e505 --- /dev/null +++ b/src/middlewared/middlewared/utils/functools.py @@ -0,0 +1,29 @@ +import asyncio +import functools + +from middlewared.utils.lang import undefined + + +def cache(func): + value = undefined + + if asyncio.iscoroutinefunction(func): + @functools.wraps(func) + async def wrapped(self): + nonlocal value + + if value == undefined: + value = await func(self) + + return value + else: + @functools.wraps(func) + def wrapped(self): + nonlocal value + + if value == undefined: + value = func(self) + + return value + + return wrapped