Python 3D Academyবাংলা

Writing a context manager: __enter__ and __exit__

🌍 In real life. At a hotel, check-in gives you a room key, and check-out takes it back and tidies the room, whether your stay went well or the shower broke.

Any class can work with with if it has two dunder methods:

  • __enter__(self) is check-in: it runs on the way in, and whatever it returns is what as names
  • __exit__(self, exc_type, exc, tb) is check-out: it runs on the way out, always

Such an object is called a context manager. Watch the flow come in through the __enter__ door and leave through the __exit__ door:

The idea in one sentence: any class becomes a context manager by having __enter__ (runs on the way in; its return value goes after as) and __exit__ (runs on the way out, always).

Its words:

  • __enter__(self): setup; return the thing the block will use
  • __exit__(self, exc_type, exc, tb): clean-up, told about any error
  • swallowing an error: __exit__ returning True stops the error from going any further
class Hotel:
    def __enter__(self):
        print("checked in")
        return "key 101"

    def __exit__(self, exc_type, exc, tb):
        print("checked out")

with Hotel() as key:
    print("using", key)
print("taxi home")

What __exit__ is told, step by step. Its three extra parameters describe any error that happened in the block:

  1. no error: all three are None
  2. an error: exc_type is its class (like ValueError) and exc is the error itself
  3. if __exit__ returns True, the error is swallowed and the program carries on after the block; otherwise (returning nothing) the error keeps going

Swallowing errors hides problems, so only do it for an error you truly expect, like a hotel that shrugs off a lost towel but not a fire.

class ShrugOff:
    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc, tb):
        if exc_type is ValueError:
            print("ignored:", exc)
            return True        # swallow only ValueError
        return False

with ShrugOff():
    int("not a number")
print("still running")

Why a class? When the setup and clean-up need to remember things (a start time, a counter, a connection), a class keeps that state in its attributes between __enter__ and __exit__.

Mistakes and edge cases.

  • Forgetting to return self from enter. Then as name gets None.
  • Returning True from exit by accident. It hides every error in the block; return nothing (None) unless you really mean to swallow it.
  • Too few parameters on exit. Python always passes three error details; def __exit__(self): fails when the block ends.

Quiz

  1. What does this print?

    class Door:
        def __enter__(self):
            print("open")
            return "inside"
    
        def __exit__(self, exc_type, exc, tb):
            print("shut")
    
    with Door() as where:
        print(where)
  2. What does this print?

    class Guard:
        def __enter__(self):
            return self
    
        def __exit__(self, exc_type, exc, tb):
            print("exit sees", exc_type)
    
    with Guard():
        print("fine")
  3. What happens if __exit__ returns True after an error in the block?

    • The error is swallowed and the program carries on after the block
    • The block runs again
    • The error is printed twice
  4. What does this print?

    class Hotel:
        def __enter__(self):
            print("in")
    
        def __exit__(self, exc_type, exc, tb):
            print("out")
    
    try:
        with Hotel():
            raise ValueError("broken shower")
    except ValueError as e:
        print("complaint:", e)
  5. Which line has a mistake?

    class Hotel:
        def __enter__(self):
            return "key"
    
        def __exit__(self):
            print("checked out")
    
    with Hotel() as key:
        print(key)

Coding tasks

  1. Write a class Announce that works with with: on the way in it prints "begin", on the way out it prints "end".

  2. Write a class Hotel whose __enter__ returns "room 101", and whose __exit__ sets self.checked_out = True. (stay() is written for you; don't change it.)

  3. Write a class Quiet whose __exit__ swallows a ValueError (returns True) but lets every other error carry on. (attempt() and divide() are written for you.)