contextlib.suppress in Python

Level 4151 keystrokes

This uses suppress() to silently ignore specific exceptions.

Python code

# suppress is a context manager that ignores the given exceptions
1from contextlib import suppress
# os provides file operations such as remove
2import os
3
# Same as try/except FileNotFoundError: pass, in one line
4with suppress(FileNotFoundError):
# The file does not exist, so this raises FileNotFoundError
5 os.remove("nonexistent_file.txt")
# Skipped: the rest of the block is abandoned after the exception
6 print("Removed")
7
# The exception was swallowed, so execution continues here
8print("Continuing...")

Output

Continuing...
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this Python code and how often they appear.

  • "× 6
  • .× 5
  • (× 4
  • )× 4
  • _× 1
  • :× 1

More Python examples at level 4

← Python typing practice