Python Glossary Русский

all Python 3codecsfunction

codecs.lookup()

codec registry

Finds a codec by name and returns a CodecInfo with its functions and classes. It also maps an alias to the canonical name: 'UTF8' → 'utf-8', 'latin-1' → 'iso8859-1'.

Syntax

info = codecs.lookup(encoding)

Its most useful job is validating an encoding name from a config or a header up front: an unknown name raises LookupError at once instead of halfway through a file. Comparing encodings as strings is fragile ('utf8', 'UTF-8', 'u8' are one codec), while lookup(x).name gives the canonical name. Name normalisation has changed: since 3.15 spaces become hyphens and other characters are no longer replaced with underscores.

Examples

import codecs
print(codecs.lookup('UTF8').name)  # → utf-8
print(codecs.lookup('latin-1').name)  # → iso8859-1
print(codecs.lookup('u8').name == codecs.lookup('utf-8').name)  # → True
import codecs
try:
    codecs.lookup('utf-9')
except LookupError as e:
    print(e)  # → unknown encoding: utf-9

See also

Common errors

Open in the full glossarydocs.python.orgReport an inaccuracy