brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: Python's contextlib.suppress ignores one expected error in a single line

Python
~/tips/tip-python-contextlib-suppress

from contextlib import suppress

Replaces a try/except/pass block for an error you expect and are fine with.

Deleting a temp file that may or may not exist usually turns into four lines of try, except and pass. Python has a shorter way that also says what you mean.

import os
from contextlib import suppress

with suppress(FileNotFoundError):
    os.remove('somefile.tmp')

If the file is not there, the FileNotFoundError is swallowed and the script continues after the with block. Any other error still goes up as normal. The docs describe it as the same as a try with except FileNotFoundError: pass.

You can list more than one exception: suppress(FileNotFoundError, PermissionError). It has been in the standard library since Python 3.4.

I find it reads better in cleanup code: the line tells you right away which error is expected, instead of hiding it at the bottom of a try block.

Caveat, and the docs say it as well: use it only for very specific errors, and only when carrying on silently is really the right thing. suppress(Exception) hides every bug in that block, and you will spend an afternoon wondering why nothing happens. Also note that the whole rest of the block is skipped after the error, so keep the block to the one statement that may fail.

Further reading: Python docs: contextlib.suppress

More Python tips import asyncio from enum import StrEnum, auto except* ValueError as eg: import pytest pytest --maxfail=2 All Python tips (107) All topics

Link