Python 3D Academyবাংলা

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")
The second time, os.remove raises FileNotFoundError, suppress swallows it, and "removed" is skipped.

Several managers in one with, step by step. Copying a recipe from one card to another needs both cards open at once:

  1. list them with commas: with open("a.txt") as src, open("b.txt", "w") as dst:
  2. they are entered left to right
  3. 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 @contextmanager generator
  • 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 bare except 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 with continues.
  • A missing comma. Several managers in one with are separated by commas; brackets around them also work in modern Python.

Quiz

  1. What does this print?

    from contextlib import suppress
    
    with suppress(ValueError):
        print("a")
        int("x")
        print("b")
    print("c")
  2. 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
  3. 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")
  4. 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
  5. 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

  1. Write safe_int(text) that returns int(text), or None if the text isn't a whole number. Use suppress.

  2. Write copy_upper(src, dst) that copies the file src into the file dst with every letter in capitals. Open both files in one with.

  3. Write remove_quietly(name) that deletes the file if it exists and does nothing if it doesn't, then returns "done". Use os.remove and suppress.