← All lessons

Context managers

Sign in · Sign up

Lesson 11.5

Your own with is made with two methods:

class Step:
    def __enter__(self):
        print("Entering the block")
        return self

    def __exit__(self, exc_type, exc_value, traceback):
        print("Leaving the block")

with Step():
    print("Working")

# The class for the task is called Counter — with a value field and its own text.
  • __enter__ is called on entering the block;
  • __exit__ on leaving, and it runs even if there was an error inside;
  • return self in __enter__ is needed for as to work.

open is built the same way: it closes the file when leaving with.

The check sets the starting value reset and the increase base. Write the manager Counter(reset): __enter__ prints Start: <value> and returns itself, in the block base is added to counter.value, and __exit__ prints Total: <value>.

Hint

A manager is a class with two methods with two underscores each.

__enter__ is called on entering with, prints the start and returns the object itself — that's what gets bound to the name after as. __exit__(self, exc_type, exc, tb) runs on leaving, even if there was an error inside.