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.
Install & Compatibility
Where this runs
tested against v2.0 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
muslpy 3.10–3.910 runs
installs and imports cleanly · install 0.0s · import 0.000s · 17.8MB
glibcpy 3.10–3.910 runs
installs and imports cleanly · install 1.5s · import 0.000s · 18MB
16MB installed
● package 16MB
Code
Verified usage
Verified import paths — ran on the pinned version, not inferred.
from conditional import Conditional
This example demonstrates how to use `Conditional` to wrap a block of code, including other context managers, based on a boolean condition.
from conditional import Conditional
# Example 1: Condition is True, block executes
print("Before true conditional block")
with Conditional(True):
print("Inside true conditional block")
with open("temp_file.txt", "w") as f:
f.write("This was written conditionally.\n")
print("After true conditional block")
# Example 2: Condition is False, block does not execute
print("\nBefore false conditional block")
with Conditional(False):
print("Inside false conditional block (should not see this)")
# The file will not be opened or written to
with open("another_temp_file.txt", "w") as f:
f.write("This was NOT written conditionally.\n")
print("After false conditional block")
# Cleanup (optional)
import os
if os.path.exists("temp_file.txt"):
os.remove("temp_file.txt")
if os.path.exists("another_temp_file.txt"):
os.remove("another_temp_file.txt")
Upgrade
Version history
Breaking-change detection hasn't run for this library yet.
Audit
Security & dependencies
CVE tracking and dependency tree are planned for a later release.