From 620f5fee6e9b56494b5ee088e77c111a160c3faf Mon Sep 17 00:00:00 2001 From: Tyler Goodlet Date: Sat, 9 Jan 2021 10:53:40 -0500 Subject: [PATCH] Wishful thinking with conditional mngrs --- piker/_async_utils.py | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/piker/_async_utils.py b/piker/_async_utils.py index b358e2f0..fb221215 100644 --- a/piker/_async_utils.py +++ b/piker/_async_utils.py @@ -17,7 +17,9 @@ """ Async utils no one seems to have built into a core lib (yet). """ +from typing import AsyncContextManager from collections import OrderedDict +from contextlib import asynccontextmanager def async_lifo_cache(maxsize=128): @@ -47,3 +49,18 @@ def async_lifo_cache(maxsize=128): return wrapper return decorator + + +@asynccontextmanager +async def _just_none(): + # noop -> skip entering context + yield None + + +@asynccontextmanager +async def maybe_with_if( + predicate: bool, + context: AsyncContextManager, +) -> AsyncContextManager: + async with context if predicate else _just_none() as output: + yield output