On this page
  1. codecs
  2. Import
  3. Overview
  4. Quick Start
  5. Implementation Walkthrough
  6. 1. Registering a Custom Error Handler
  7. 2. Inspecting Codec Metadata
  8. Gotchas & Boundaries
  9. Common Functions
  10. Classes & Objects
  11. Constants & Attributes

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

Common Functions

Classes & Objects

Constants & Attributes

Linked from

Related notes