Context Manager Classes
A Python context manager class is a class with two methods, __enter__ and __exit__. The with statement calls __enter__ before its block and __exit__ after it.
You need Python Context Managers and Python try finally. You do not need to know classes yet: this lesson explains each part it uses, and Python Classes and Objects has more. The goal of this lesson: write a context manager as a class, without @contextmanager. Every example is complete and runs on its own, with no imports and no files.
A class with __enter__ and __exit__
A class is a named group of functions, called methods. The class below has two. __enter__ adds "front" to the list open_doors, and __exit__ takes it out again.
open_doors = []class FrontDoor: def __enter__(self): open_doors.append("front") def __exit__(self, exc_type, exc_value, traceback): open_doors.remove("front")with FrontDoor(): print("Inside:", open_doors)print("After:", open_doors)This prints Inside: ['front'], then After: [].
Here is what the with line does:
FrontDoor(), with brackets, makes an object from the class.withcalls that object's__enter__method, then runs the block.- After the block,
withcalls the object's__exit__method.
You never call the two methods yourself. A name with two underscores on each side is a special method name: Python calls it for you at a set moment. with finds the two methods by these names, so spell them exactly.
self is the object the method was called on. Python passes it in for you, so every method lists self first.
__exit__ takes three more parameters. They describe an error raised in the block: its type, the error itself and where it happened. When the block finishes with no error, all three are None. This class does not use them, but they must be there, because with always passes them.
Class versus @contextmanager: both make a context manager. With @contextmanager the code above yield is the set-up and the code below it is the clean-up. In a class, the set-up goes in __enter__ and the clean-up goes in __exit__, and there is no yield.
When to use a class: for one short set-up and clean-up, @contextmanager is less to write. Use a class when the object has to remember values between the two methods, or needs other methods as well. You also need to read classes like this: the file that open() gives you is an object with __enter__ and __exit__, which is why it works in with.
The brackets matter. with FrontDoor: passes the class, not an object made from it, and Python stops.
open_doors = []class FrontDoor: def __enter__(self): open_doors.append("front") def __exit__(self, exc_type, exc_value, traceback): open_doors.remove("front")with FrontDoor: # this line raises TypeError: the brackets are missing print("Inside:", open_doors)Nothing is printed before the TypeError: the block never runs, and neither does __enter__.
__exit__ runs after an error too
This is the same class. Its with block raises an error, which is caught outside.
open_doors = []class FrontDoor: def __enter__(self): open_doors.append("front") def __exit__(self, exc_type, exc_value, traceback): open_doors.remove("front")try: with FrontDoor(): print("Inside:", open_doors) raise ValueError("alarm went off")except ValueError as error: print("Caught:", error)print("After:", open_doors)The last line prints After: [], so __exit__ ran. Then the error carried on, and the except outside printed Caught: alarm went off.
The class has no try and no finally. It does not need them: when the block raises, with itself calls __exit__, and this time the three extra parameters hold the error. A function written with @contextmanager needs try and finally around its yield to do the same.
The raise ValueError(...) line stands in for any error in a real block. The open_doors list stands in for real set-up you must undo, such as an open file or a network connection, which these examples leave out.
Store values with __init__ and self
FrontDoor always opens the same door. To choose the door on the with line, the class needs a third method, __init__. Python calls it when the object is made, and passes it the values in the brackets.
open_doors = []class Door: def __init__(self, name): self.name = name def __enter__(self): self.count_before = len(open_doors) open_doors.append(self.name) def __exit__(self, exc_type, exc_value, traceback): open_doors.remove(self.name) print(f"Closed {self.name}, {self.count_before} still open")with Door("front"): with Door("garage"): print("Inside:", open_doors)print("After:", open_doors)This prints Inside: ['front', 'garage'], then Closed garage, 1 still open, Closed front, 0 still open and After: [].
The second with is inside the first, so both doors are open in the inner block. The inner with ends first, so the garage closes first.
Door("garage") makes an object and calls __init__ with name set to "garage". A parameter such as name is gone when its method ends. self.name = name stores the value on the object, as an attribute: a variable that belongs to one object and lasts as long as the object does. The dot means "belonging to", so self.name is this object's name. Every other method of the object reads it as self.name.
Any method can store an attribute. __enter__ stores self.count_before, and __exit__ reads it later. This is how the two methods share a value: a plain variable set in __enter__ does not exist in __exit__.
Each object has its own attributes. The two Door objects above keep different names and different counts.
self.name versus name: inside __enter__ and __exit__ there is no variable name. Writing open_doors.append(name) there raises NameError. Write self.name.
Return a value from __enter__ for as
with ... as variable: gives the block a value to work with. In a class, that value is whatever __enter__ returns.
class Laps: def __enter__(self): self.times = [] return self.times def __exit__(self, exc_type, exc_value, traceback): print(f"Ran {len(self.times)} laps")with Laps() as times: times.append(62) times.append(58) print("Running:", times)This prints Running: [62, 58], then Ran 2 laps.
__enter__ makes a list, stores it as self.times and returns it. with takes the returned value and assigns it to the name after as. as times receives that same list, so the block fills it and __exit__ reads it afterwards. return here does the job of yield value in a function written with @contextmanager.
What as receives: it is the value __enter__ returns, not the object Laps(). An __enter__ with no return gives None, as the classes in the first two sections do, and times.append(62) would then raise AttributeError.
The list of lap times stands in for a real resource that __enter__ sets up and hands to the block, such as an open file.
Note: This lesson leaves one thing out. An __exit__ that returns True hides the error from the code outside. The __exit__ methods here return nothing, so the error always carries on.
See also: Python Classes and Objects, Python try finally, Python with Statement.
Your turn
Write the class Kettle. Its __enter__ adds "kettle" to the end of switched_on, and its __exit__ removes it. The second block raises an error, and the kettle must still be switched off.
Making tea: ['fridge', 'kettle'] After tea: ['fridge'] Making soup: ['fridge', 'kettle'] Caught: no soup left After soup: ['fridge']
switched_on = ["fridge"]# write the class Kettle: __enter__ appends "kettle" to switched_on, __exit__ removes itwith Kettle(): print("Making tea:", switched_on)print("After tea:", switched_on)try: with Kettle(): print("Making soup:", switched_on) raise ValueError("no soup left")except ValueError as error: print("Caught:", error)print("After soup:", switched_on)