Context managers · 2 / 15 Theory

Creating context managers with classes

For your own class to work with with you only need to define __enter__ and __exit__. Let us see how they behave and what they receive.

A minimal manager

class Notice:
    def __enter__(self):
        print("enter")
        return "value"

    def __exit__(self, kind, value, trace):
        print("exit", kind)
        return False

with Notice() as x:
    print("inside", x)
# enter
# inside value
# exit None

What __enter__ returns is what the variable after as receives. Often it is self, so that you can use the object inside the block. Section with entry and exit practises it.

The three parameters of __exit__

If the block ends well, __exit__ receives None in all three. If there was an exception, it receives its class, its value and its traceback.

ParameterNo errorWith error
kindNonethe class of the error, for example KeyError
valueNonethe error object (its message)
traceNoneinformation about where it happened
class Notice:
    def __enter__(self):
        return self

    def __exit__(self, kind, value, trace):
        print("exit", kind.__name__ if kind else None)
        return False

try:
    with Notice():
        raise KeyError("k")
except KeyError:
    print("caught outside")
# exit KeyError
# caught outside

What __exit__ returns: swallowing or letting the error pass

  • If it returns False (or None, the usual case), the error continues and propagates.
  • If it returns True, the error is suppressed: the program goes on after the with block as if nothing happened.
class Swallower:
    def __enter__(self):
        return self

    def __exit__(self, kind, value, trace):
        print(f"ignored: {value}")
        return True

with Swallower():
    int("abc")
print("the program goes on")
# ignored: invalid literal for int() with base 10: 'abc'
# the program goes on

Suppressing errors is dangerous: it hides failures you may have needed to see. Do it only for specific errors and for a reason (for example, returning kind is ZeroDivisionError).

Keeping state: indentation with levels

A class attribute can keep count of how many blocks are open.

class Level:
    depth = 0

    def __init__(self, name):
        self.name = name

    def __enter__(self):
        print("  " * Level.depth + "Opens " + self.name)
        Level.depth += 1
        return self

    def __exit__(self, *args):
        Level.depth -= 1
        print("  " * Level.depth + "Closes " + self.name)

with Level("a"):
    with Level("b"):
        print("  " * Level.depth + "inside")
# Opens a
#   Opens b
#     inside
#   Closes b
# Closes a

It is the idea of Nested levels. Notice that the closing runs in reverse order: the last one opened is closed first.

Undoing if something fails: a transaction

Since __exit__ knows whether there was an error, it can restore the previous state. This is a transaction: either everything is applied or nothing is.

class Backup:
    def __init__(self, items):
        self.items = items

    def __enter__(self):
        self.original = list(self.items)
        return self.items

    def __exit__(self, kind, value, trace):
        if kind is not None:
            self.items[:] = self.original
            print("restored")
            return True
        return False

data = [1, 2, 3]
with Backup(data) as d:
    d.append(4)
    d.append("x" + 5)   # TypeError
print(data)
# restored
# [1, 2, 3]

You practise it with Transaction with rollback.

Several resources and a record of what happened

In a single with you can open several managers separated by commas. They are opened from left to right and closed from right to left, and all are closed even if there is an error. You will check it in Guaranteed cleanup.

And since __exit__ knows the type of the error, it can behave differently depending on its class, as Error-aware log does.