Skip to main content

codecs

The codecs module exposes the codec registry, error handlers, incremental codecs, and stream wrappers. Full per-codec catalogue lives in Reference -> Codec registry.

Source-of-record: Lib/codecs.py, Python/codecs.c, codecs docs.

Top-level functions

FunctionReturns
encode(obj, encoding='utf-8', errors='strict')bytes.
decode(obj, encoding='utf-8', errors='strict')str.
lookup(encoding)CodecInfo.
lookup_error(name)Error handler.
register(search_function)Add a search function.
register_error(name, fn)Register handler.
open(filename, mode='r', encoding=None, errors='strict', buffering=-1)Opens a file with codec.
iterencode(iterator, encoding, errors='strict')Stream encode.
iterdecode(iterator, encoding, errors='strict')Stream decode.
EncodedFile(file, data_encoding, file_encoding=None, errors='strict')Transparent transcoder.
getencoder(encoding) / getdecoder(encoding)Codec function.
getreader(encoding) / getwriter(encoding)Stream class.
getincrementalencoder(encoding) / getincrementaldecoder(encoding)Class.

BOM constants

ConstantBytes
BOMPlatform-default BOM.
BOM_UTF8b'\\xef\\xbb\\xbf'.
BOM_UTF16_BEb'\\xfe\\xff'.
BOM_UTF16_LEb'\\xff\\xfe'.
BOM_UTF32_BEb'\\x00\\x00\\xfe\\xff'.
BOM_UTF32_LEb'\\xff\\xfe\\x00\\x00'.

Error handlers

'strict', 'ignore', 'replace', 'xmlcharrefreplace', 'backslashreplace', 'surrogateescape', 'surrogatepass', 'namereplace'. Custom handlers are fn(exc) -> (replacement, new_index).

Classes

ClassRole
CodecStateless encode/decode pair.
IncrementalEncoder / IncrementalDecoderStreaming with encode(s, final=False).
BufferedIncrementalEncoder / BufferedIncrementalDecoderHelpers with internal buffer.
StreamReader / StreamWriterWrap a binary stream as decoded text.
StreamRecoderMix encoder + decoder for transcoding.
StreamReaderWriterBidirectional wrapper.

Gopy status

AreaState
Module surfaceComplete.
Built-in codecsUTF-8/16/32, ASCII, Latin-1 complete; codepage codecs complete for common set.
Error handlersComplete.
Incremental codecsComplete.
Stream classesComplete.

Reference