On this page
codecs
Prev: code | Up: stdlib_module | Next: codeop
Rel: struct
Ref: docs.python.org — codecs
Tags: #public #python3 #stdlib
Import
import codecs
Overview
Registry and base classes for Python's encoding/decoding subsystem (encode(), decode(), lookup(), register(), register_error(), and IncrementalDecoder/IncrementalEncoder). While everyday file I/O should use built-in open(..., encoding=...), reach for codecs when streaming partial byte chunks across sockets, handling BOMs, or registering custom codecs and error handlers.
Quick Start
import codecs
# Incremental decoding safely handles multi-byte UTF-8 characters split across chunks
decoder = codecs.getincrementaldecoder("utf-8")()
raw = "café".encode("utf-8") # b'caf\xc3\xa9'
part1 = decoder.decode(raw[:4], final=False) # splits the 2-byte 'é'
part2 = decoder.decode(raw[4:], final=True)
assert part1 + part2 == "café"
Implementation Walkthrough
1. Registering a Custom Error Handler
Error handlers decide what happens when encode() or decode() hits an unrepresentable byte or character:
import codecs
def hex_bracket_replace(err: UnicodeError) -> tuple[str, int]:
bad = err.object[err.start:err.end]
return (f"<{bad.hex()}>", err.end)
codecs.register_error("hexbracket", hex_bracket_replace)
text = b"ok\xffdone".decode("ascii", errors="hexbracket")
assert text == "ok<ff>done"
2. Inspecting Codec Metadata
Use codecs.lookup("utf-8") to normalize encoding aliases (e.g., "latin1" → "iso8859-1") and access the underlying encoder/decoder factories.
Gotchas & Boundaries
- Prefer built-in
open()overcodecs.open():codecs.open()is legacy and has subtle universal-newline quirks;open(path, encoding="utf-8", newline=...)is faster and cleaner in Python 3. - UTF-8 with BOM: Use
"utf-8-sig"(not"utf-8") when reading files that may start withcodecs.BOM_UTF8(\xef\xbb\xbf) so the BOM is stripped automatically. - Non-text codecs:
codecs.encode(b"abc", "hex")or"rot_13"work on bytes/str respectively, whereasstr.encode()only accepts text encodings.
Common Functions
- codecs.backslashreplace_errors() —
backslashreplace_errors(self, object, /)— Implements the 'backslashreplace' error handling, which replaces malformed data with a backslashed escape sequence. - codecs.decode() —
decode(obj, encoding='utf-8', errors='strict')— Decodes obj using the codec registered for encoding. - codecs.encode() —
encode(obj, encoding='utf-8', errors='strict')— Encodes obj using the codec registered for encoding. - codecs.EncodedFile() —
EncodedFile(file, data_encoding, file_encoding=None, errors='strict')— Return a wrapped version of file which provides transparent encoding translation. - codecs.getdecoder() —
getdecoder(encoding)— Lookup up the codec for the given encoding and return its decoder function. - codecs.getencoder() —
getencoder(encoding)— Lookup up the codec for the given encoding and return its encoder function. - codecs.getincrementaldecoder() —
getincrementaldecoder(encoding)— Lookup up the codec for the given encoding and return its IncrementalDecoder class or factory function. - codecs.getincrementalencoder() —
getincrementalencoder(encoding)— Lookup up the codec for the given encoding and return its IncrementalEncoder class or factory function. - codecs.getreader() —
getreader(encoding)— Lookup up the codec for the given encoding and return its StreamReader class or factory function. - codecs.getwriter() —
getwriter(encoding)— Lookup up the codec for the given encoding and return its StreamWriter class or factory function. - codecs.ignore_errors() —
ignore_errors(self, object, /)— Implements the 'ignore' error handling, which ignores malformed data and continues. - codecs.iterdecode() —
iterdecode(iterator, encoding, errors='strict', **kwargs)— Decoding iterator. - codecs.iterencode() —
iterencode(iterator, encoding, errors='strict', **kwargs)— Encoding iterator. - codecs.lookup() —
lookup(encoding, /)— Looks up a codec tuple in the Python codec registry and returns a CodecInfo object. - codecs.lookup_error() —
lookup_error(name, /)— Return the error handler for the specified error handling name or raise a LookupError, if no handler exists under this name. - codecs.namereplace_errors() —
namereplace_errors(self, object, /)— Implements the 'namereplace' error handling, which replaces an unencodable character with a \N{...} escape sequence. - codecs.open() —
open(filename, mode='r', encoding=None, errors='strict', buffering=-1)— Open an encoded file using the given mode and return a wrapped version providing transparent encoding/decoding. - codecs.register() —
register(search_function, /)— Register a codec search function. - codecs.register_error() —
register_error(errors, handler, /)— Register the specified error handler under the name errors. - codecs.replace_errors() —
replace_errors(self, object, /)— Implements the 'replace' error handling, which replaces malformed data with a replacement marker. - codecs.strict_errors() —
strict_errors(self, object, /)— Implements the 'strict' error handling, which raises a UnicodeError on coding errors. - codecs.xmlcharrefreplace_errors() —
xmlcharrefreplace_errors(self, object, /)— Implements the 'xmlcharrefreplace' error handling, which replaces an unencodable character with the appropriate XML character reference.
Classes & Objects
- codecs.Codec — Defines the interface for stateless encoders/decoders. (Methods:
.decode(),.encode()) - codecs.CodecInfo — Codec details when looking up the codec registry (Methods:
.count(),.index()) - codecs.IncrementalDecoder — An IncrementalDecoder decodes an input in multiple steps. The input can be passed piece by piece to the decode() method. The IncrementalDecoder remembers the state of the decoding process between calls to decode(). (Methods:
.decode(),.getstate(),.reset(),.setstate()) - codecs.IncrementalEncoder — An IncrementalEncoder encodes an input in multiple steps. The input can be passed piece by piece to the encode() method. The IncrementalEncoder remembers the state of the encoding process between calls to encode(). (Methods:
.encode(),.getstate(),.reset(),.setstate()) - codecs.StreamReader —
codecs.StreamReaderclass. (Methods:.charbuffertype(),.decode(),.encode(),.read(),.readline(),.readlines()) - codecs.StreamReaderWriter — StreamReaderWriter instances allow wrapping streams which work in both read and write modes. (Methods:
.read(),.readline(),.readlines(),.reset(),.seek(),.write()) - codecs.StreamRecoder — StreamRecoder instances translate data from one encoding to another. (Methods:
.read(),.readline(),.readlines(),.reset(),.seek(),.write()) - codecs.StreamWriter —
codecs.StreamWriterclass. (Methods:.decode(),.encode(),.reset(),.seek(),.write(),.writelines())
Constants & Attributes
codecs.BOM(bytes) =b'\xff\xfe'codecs.BOM32_BE(bytes) =b'\xfe\xff'codecs.BOM32_LE(bytes) =b'\xff\xfe'codecs.BOM64_BE(bytes) =b'\x00\x00\xfe\xff'codecs.BOM64_LE(bytes) =b'\xff\xfe\x00\x00'codecs.BOM_BE(bytes) =b'\xfe\xff'codecs.BOM_LE(bytes) =b'\xff\xfe'codecs.BOM_UTF16(bytes) =b'\xff\xfe'codecs.BOM_UTF16_BE(bytes) =b'\xfe\xff'codecs.BOM_UTF16_LE(bytes) =b'\xff\xfe'codecs.BOM_UTF32(bytes) =b'\xff\xfe\x00\x00'codecs.BOM_UTF32_BE(bytes) =b'\x00\x00\xfe\xff'codecs.BOM_UTF32_LE(bytes) =b'\xff\xfe\x00\x00'codecs.BOM_UTF8(bytes) =b'\xef\xbb\xbf'
Linked from
- tuts/python3/stdlib_module
- tuts/python3/stdlib_module/code
- tuts/python3/stdlib_module/codecs/backslashreplace_errors
- tuts/python3/stdlib_module/codecs/Codec
- tuts/python3/stdlib_module/codecs/CodecInfo
- tuts/python3/stdlib_module/codecs/decode
- tuts/python3/stdlib_module/codecs/encode
- tuts/python3/stdlib_module/codecs/EncodedFile
- tuts/python3/stdlib_module/codecs/getdecoder
- tuts/python3/stdlib_module/codecs/getencoder
- tuts/python3/stdlib_module/codecs/getincrementaldecoder
- tuts/python3/stdlib_module/codecs/getincrementalencoder
- tuts/python3/stdlib_module/codecs/getreader
- tuts/python3/stdlib_module/codecs/getwriter
- tuts/python3/stdlib_module/codecs/ignore_errors
- tuts/python3/stdlib_module/codecs/IncrementalDecoder
- tuts/python3/stdlib_module/codecs/IncrementalEncoder
- tuts/python3/stdlib_module/codecs/iterdecode
- tuts/python3/stdlib_module/codecs/iterencode
- tuts/python3/stdlib_module/codecs/lookup
- tuts/python3/stdlib_module/codecs/lookup_error
- tuts/python3/stdlib_module/codecs/namereplace_errors
- tuts/python3/stdlib_module/codecs/open
- tuts/python3/stdlib_module/codecs/register
- tuts/python3/stdlib_module/codecs/register_error
- tuts/python3/stdlib_module/codecs/replace_errors
- tuts/python3/stdlib_module/codecs/StreamReader
- tuts/python3/stdlib_module/codecs/StreamReaderWriter
- tuts/python3/stdlib_module/codecs/StreamRecoder
- tuts/python3/stdlib_module/codecs/StreamWriter
- tuts/python3/stdlib_module/codecs/strict_errors
- tuts/python3/stdlib_module/codecs/xmlcharrefreplace_errors
- tuts/python3/stdlib_module/codeop
- tuts/python3/stdlib_module/encodings
- tuts/python3/stdlib_module/stdlib_module
- tuts/python3/stdlib_module/struct
Related notes
- tuts/python3/stdlib_module/code Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/codecs/backslashreplace_errors Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/codecs/Codec Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/codecs/CodecInfo Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/codecs/decode Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/codecs/encode Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/codecs/EncodedFile Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/codecs/getdecoder Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/codecs/getencoder Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/codecs/getincrementaldecoder Linked here; links to this page; shared tags: #stdlib