The `conditional` library provides a `Conditional` context manager that executes code within a `with` block only when a specified boolean condition is true. It simplifies conditional execution of code sections, particularly useful when dealing with other context managers or resource allocation that should only happen under certain circumstances. As of version 2.0, it is actively maintained with a low release cadence.
pip install conditionalVerified import paths — ran on the pinned version, not inferred.
This example demonstrates how to use `Conditional` to wrap a block of code, including other context managers, based on a boolean condition.
Ensure the `condition` argument is explicitly a `bool`. If you previously passed a callable, evaluate it *before* passing the result to `Conditional`: `with Conditional(my_callable()):` instead of `with Conditional(my_callable):`.
Use it as `with Conditional(my_condition): with MyActualContextManager(): ...` if you want to conditionally enter `MyActualContextManager`. For simple conditional execution without another context manager, you might also consider a standard `if my_condition: ...` block.
If certain operations must always occur regardless of the condition, place them outside the `Conditional` block. For complex conditional logic, a standard `if/else` statement might offer more clarity and control over divergent paths.
No dependency data recorded yet.