Editor

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 lesson

Create 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 self
  • Add a method add(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

    All Python exercises · 50 practice problems · Error Handling quiz