Conditional Context Manager

2.0 · active · verified Fri Apr 17

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.

Common errors

Warnings

Install

Imports

Quickstart

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")

view raw JSON →