Python Context Managers

What Are Python Context Managers?

Context managers manage the setup and teardown of resources, ensuring they are properly handled even if errors occur. They are commonly used with the with statement.

Why Use Context Managers?

  • Automatic Resource Management: Ensure resources like lists or dictionaries are handled correctly.
  • Error Handling: Guarantee cleanup actions are performed even when exceptions arise.
  • Cleaner Code: Reduce boilerplate code for resource management.

How to Use Context Managers?

Syntax of a Custom Context Manager Using contextlib

from contextlib import contextmanager

@contextmanager
def my_context_manager():
    # Setup code
    try:
        yield
    finally:
        # Teardown code

Managing Festival Resources with enumerate

# Use a context manager to allocate festival resources and track them with enumeration.

from contextlib import contextmanager

@contextmanager
def manage_festival_resources(resources):
    print("Allocating festival resources:")
    for idx, resource in enumerate(resources, start=1):
        print(f"{idx}. {resource}")
    try:
        yield
    finally:
        print("Releasing festival resources.")

resources = ["Stage Setup", "Lighting", "Sound System", "Decorations"]

with manage_festival_resources(resources):
    print("Festival resources are now in use.")

""" 
Expected Output: 

Allocating festival resources:
1. Stage Setup
2. Lighting
3. Sound System
4. Decorations
Festival resources are now in use.
Releasing festival resources.
"""

Managing Festival Budgets with zip

# Pair budget items with their amounts using a context manager.

from contextlib import contextmanager

@contextmanager
def manage_festival_budget(items, amounts):
    budget = {}
    print("Allocating festival budget:")
    for item, amount in zip(items, amounts):
        budget[item] = amount
        print(f"- {item}: PHP {amount}")
    try:
        yield budget
    finally:
        print("Finalizing festival budget:")
        for item, amount in budget.items():
            print(f"- {item}: PHP {amount}")

budget_items = ["Stage Setup", "Lighting", "Sound System", "Decorations"]
budget_amounts = [5000, 3000, 4000, 2000]

with manage_festival_budget(budget_items, budget_amounts) as budget:
    print("Festival budget has been allocated successfully.")

"""
Expected Output: 

Allocating festival budget:
- Stage Setup: PHP 5000
- Lighting: PHP 3000
- Sound System: PHP 4000
- Decorations: PHP 2000
Festival budget has been allocated successfully.
Finalizing festival budget:
- Stage Setup: PHP 5000
- Lighting: PHP 3000
- Sound System: PHP 4000
- Decorations: PHP 2000
"""

Scroll to Top