python / python-orientation
18 mins
Python Level 6: Context Managers & Exception Blocks
Why This Matters: `with open()` context managers automatically cleanup resources even if errors occur.
## Safe Resource Management with Context Managers
Python uses `with open()` context managers to safely handle file streams.
```python
with open("data.txt", "w") as f:
f.write("GrowCode Python Data Stream
")
# File closed automatically here!
try:
val = int("abc")
except ValueError as e:
print(f"Handled error: {e}")
```
MENTAL MODEL & MEMORY LAYOUT
CONTEXT MANAGER LIFECYCLE: [ __enter__ Open File ] ──► [ Execute Block ] ──► [ __exit__ Auto Close File ]
COMMON PITFALLS TO AVOID
- Forgetting context manager `with open(...)` and leaving unclosed file streams open.
Safe Integer Parsing Pattern
def safe_parse(s):
try:
return int(s)
except ValueError:
return 0
print(safe_parse("123")) # 123
print(safe_parse("invalid")) # 0Handles parsing exceptions gracefully with try/except fallback.
CONCEPT MASTERY CHECKPOINT
Why is `with open(...)` preferred over raw `open()` and `close()` in Python?
NEXT RECOMMENDED LESSON
Python Level 7: OOP & Classes
Challenge: Write function `safe_int(s)` returning int(s) if valid else 0.