Handy context managers, and several at once
🌍 In real life. Some problems are expected and harmless: you go to throw away an old note, and it's already gone. Fine, nothing to do. Other problems must never be hidden.
contextlib.suppress(SomeError) is a ready-made context manager for the harmless kind: if that one error happens inside the block, it is swallowed and the program carries on after the block. Its __exit__ returns True for that error only. The room below swallows its error the same way:
The idea in one sentence: contextlib.suppress(Error) quietly ignores one expected error inside its block, and one with can open several managers at once, cleaning them up in reverse order.
Its words:
suppress(FileNotFoundError): "if this exact error happens, skip the rest of the block and carry on"- several managers:
with a() as x, b() as y: - reverse clean-up: the last one opened is the first one closed
import os
from contextlib import suppress
with open("old.txt", "w") as f:
f.write("old note")
for _ in range(2):
with suppress(FileNotFoundError):
os.remove("old.txt")
print("removed")
print("done, no crash")Several managers in one with, step by step. Copying a recipe from one card to another needs both cards open at once:
- list them with commas:
with open("a.txt") as src, open("b.txt", "w") as dst: - they are entered left to right
- they are cleaned up in the opposite order, right to left, and every one is cleaned up even if something fails
Which kind of context manager should I write?
- one short setup and clean-up → a
@contextmanagergenerator - it needs to remember things, or has several methods → a class with
__enter__and__exit__ - an expected, harmless error →
suppress
with open("recipe.txt", "w") as f:
f.write("rice\nlentils\nsalt\n")
with open("recipe.txt") as src, open("copy.txt", "w") as dst:
for line in src:
dst.write(line.upper())
with open("copy.txt") as f:
print(f.read())Why reverse order? The later resource often depends on the earlier one (a writer inside an open file), so it must be closed first, like taking the ribbon off before opening the box.
Mistakes and edge cases.
- Suppressing too much.
suppress(Exception)hides real bugs, just like a bareexcept Exception:. Name the one harmless error. - Code after the error. Inside a suppressed block, the lines after the error don't run; only the code after the
withcontinues. - A missing comma. Several managers in one
withare separated by commas; brackets around them also work in modern Python.
Quiz
What does this print?
from contextlib import suppress with suppress(ValueError): print("a") int("x") print("b") print("c")What does
suppress(KeyError)do with a ZeroDivisionError raised in its block?- Nothing: it only swallows KeyError, so the error carries on
- Swallows it too
- Turns it into a KeyError
What does this print?
from contextlib import contextmanager @contextmanager def door(name): print("open", name) yield print("close", name) with door("A"), door("B"): print("inside")A context manager has to count how many times it was used. Which kind fits best?
- A class with __enter__ and __exit__, keeping the count on self
- suppress
- No context manager can do that
Which line has a mistake? (A missing key should just be skipped.)
from contextlib import suppress prices = {"tea": 10} with suppress(ValueError): print(prices["coffee"]) print("next customer")
Coding tasks
Write
safe_int(text)that returnsint(text), orNoneif the text isn't a whole number. Usesuppress.Write
copy_upper(src, dst)that copies the filesrcinto the filedstwith every letter in capitals. Open both files in onewith.Write
remove_quietly(name)that deletes the file if it exists and does nothing if it doesn't, then returns"done". Useos.removeandsuppress.