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
x
1
from contextlib import contextmanager
2
3
4
def my_context_manager():
5
# Setup code
6
try:
7
yield
8
finally:
9
# Teardown code
Managing Festival Resources with enumerate
1
30
1
# Use a context manager to allocate festival resources and track them with enumeration.
2
3
from contextlib import contextmanager
4
5
6
def manage_festival_resources(resources):
7
print("Allocating festival resources:")
8
for idx, resource in enumerate(resources, start=1):
9
print(f"{idx}. {resource}")
10
try:
11
yield
12
finally:
13
print("Releasing festival resources.")
14
15
resources = ["Stage Setup", "Lighting", "Sound System", "Decorations"]
16
17
with manage_festival_resources(resources):
18
print("Festival resources are now in use.")
19
20
"""
21
Expected Output:
22
23
Allocating festival resources:
24
1. Stage Setup
25
2. Lighting
26
3. Sound System
27
4. Decorations
28
Festival resources are now in use.
29
Releasing festival resources.
30
"""
Managing Festival Budgets with zip
1
39
1
# Pair budget items with their amounts using a context manager.
2
3
from contextlib import contextmanager
4
5
6
def manage_festival_budget(items, amounts):
7
budget = {}
8
print("Allocating festival budget:")
9
for item, amount in zip(items, amounts):
10
budget[item] = amount
11
print(f"- {item}: PHP {amount}")
12
try:
13
yield budget
14
finally:
15
print("Finalizing festival budget:")
16
for item, amount in budget.items():
17
print(f"- {item}: PHP {amount}")
18
19
budget_items = ["Stage Setup", "Lighting", "Sound System", "Decorations"]
20
budget_amounts = [5000, 3000, 4000, 2000]
21
22
with manage_festival_budget(budget_items, budget_amounts) as budget:
23
print("Festival budget has been allocated successfully.")
24
25
"""
26
Expected Output:
27
28
Allocating festival budget:
29
- Stage Setup: PHP 5000
30
- Lighting: PHP 3000
31
- Sound System: PHP 4000
32
- Decorations: PHP 2000
33
Festival budget has been allocated successfully.
34
Finalizing festival budget:
35
- Stage Setup: PHP 5000
36
- Lighting: PHP 3000
37
- Sound System: PHP 4000
38
- Decorations: PHP 2000
39
"""