Build a Batch Processor Context Manager
Advanced · Write the code · from Python Context Managers: The with Statement and Building Your Own
From the lesson: Python Context Managers: The with Statement and Building Your Own
Imagine walking through an automatic door at a grocery store. You don't have to push it open or remember to close it behind you. The door opens when you approach and closes when you walk through. It just handles itself.
Read the lessonCreate a class called BatchProcessor that collects items and processes them when the block ends.
__init__: set self.items to an empty list__enter__: print 'Batch started' and return selfadd(self, item) that appends the item to self.items__exit__: print 'Processing N items...' where N is the count, then print each item as ' - <item>', then print 'Batch complete'. Return False.Use it to add 'email', 'report', and 'backup'.
# Build your BatchProcessor class here
More Context Manager exercises
- Predict the Output: Basic withIntermediate
- Write a Logging Context ManagerIntermediate
- Fix the Bug: Missing CleanupIntermediate
- Write an Indentation Context ManagerAdvanced
- Refactor: Replace try/finally with a Context ManagerAdvanced
All Python exercises · 50 practice problems · Error Handling quiz