conditional 2.0 – Conditional Context¶
The conditional
context manager comes handy when you
always want to execute a with-block but only conditionally want to apply its
context manager.
If you find yourself writing code like this:
if CONDITION:
with CONTEXTMANAGER():
BODY()
else:
BODY()
Consider replacing it with:
with conditional(CONDITION, CONTEXTMANAGER()):
BODY()
Asynchronous context managers are supported since version 2.0:
async with conditional(CONDITION, ASYNCCONTEXTMANAGER()):
BODY()
The conditional
context manager ships with type
annotations. Type checkers and IDEs can use this information to implement
type safety and auto completion.
API Documentation¶
- conditional.conditional(condition, contextmanager)¶
Wrap a context manager and enter it only if condition is true.