Editor

Write a Logging Context Manager

Intermediate · 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 LogBlock that works as a context manager. It takes a label string in __init__.

  • __enter__ should print START: <label> and return self.
  • __exit__ should print END: <label> and return False.
  • Then use it: with LogBlock('test') as lb: and inside print Running....

    class LogBlock:
    def __init__(self, label):
    pass # Store the label
    def __enter__(self):
    pass # Print START and return self
    def __exit__(self, exc_type, exc_val, exc_tb):
    pass # Print END and return False
    # Use it here

    More Context Manager exercises

    All Python exercises · 50 practice problems · Error Handling quiz