Handle an unknown text encoding name without a Python traceback

Direct answer

Validate a requested text encoding before attempting to decode input. codecs.lookup resolves a registered encoding name and raises LookupError when that name is unknown. Catching that specific exception lets a CLI return a short, stable diagnostic instead of exposing a Python traceback for an invalid option.

The fixture deliberately requests not-a-codec, so the demonstrated branch prints kind=invalid-encoding. It does not exercise a successful lookup or read any data. A production function needs an explicit success path as well as this failure path; otherwise a result variable assigned only inside except would be undefined for a valid codec.

An unknown name is different from invalid bytes. A supported encoding can still reject a particular payload with UnicodeDecodeError during decoding. Keep those results separate so a caller can distinguish an option typo from an input-format problem. Avoid treating every exception as an encoding-name error, because unrelated file or program failures need their own handling.

Complete example

from pathlib import Path
from tempfile import TemporaryDirectory
with TemporaryDirectory() as d:
    import codecs
    try:
        codecs.lookup('not-a-codec')
    except LookupError:
        result = 'kind=invalid-encoding'
    print(result)

Expected stdout (for a platform supporting the demonstrated operation):

kind=invalid-encoding

Sources

- codecs.lookup

Prepared with AI assistance. The example uses synthetic data; its stated limits apply.

Comments

Popular posts from this blog

Compare Two Text Files in Python Without Modifying Them

Seven CSV Quality Checks to Run Before Importing Data

Explain why SQLite transactions cannot make an HTTP call atomic