Closed thorwhalen closed 2 years ago
I feel bad not re-using ContextFanout
for this.
I'm just not sure it's worth it for the sake of reuse.
As a matter of note, one way to use (by delegation, not subclassing) ContextFanout
is to do this:
@dataclass
class ContextualFunction:
func: Callable
contexts: Iterable[ContextManager] = ()
def __post_init__(self):
self.__signature__ = Sig(self.func)
self.multi_context = ContextFanout(*self.contexts)
def __call__(self, *args, **kwargs):
return self.func(*args, **kwargs)
def __enter__(self):
self.multi_context.__enter__()
return self
def __exit__(self, exc_type, exc_val, exc_tb) -> None:
return self.multi_context.__exit__(exc_type, exc_val, exc_tb)
An aggregate of a function and context managers.
This is useful when a function needs specific resources run, which are managed by some context managers. What
ContextualFunc
does is bring both in one place so that the callable is it's own context manager instance which you can enter, call, and exit.┆Issue is synchronized with this Asana task by Unito