Python Glossary Русский

all Python 3codecsfunction

codecs.getincrementaldecoder()

incremental codecs

Returns an incremental decoder class: it accepts bytes in chunks and keeps the undecoded tail itself. The main tool for text arriving from a socket or in blocks.

Syntax

dec = codecs.getincrementaldecoder(encoding)(errors='strict')

This is where codecs earns its keep: bytes.decode on a chunk that splits a letter either fails or, with errors='replace', silently corrupts the text. An incremental decoder holds the partial character until the next chunk. It returns a class you must call: getincrementaldecoder('utf-8')(). Pass final=True with the last chunk, or a truncated tail at the end of the stream vanishes without an error.

Examples

import codecs
data = 'Привет'.encode('utf-8')
print(data[:3].decode('utf-8', 'replace'))  # → П�
dec = codecs.getincrementaldecoder('utf-8')()
print(dec.decode(data[:3]), dec.decode(data[3:], final=True))  # → П ривет
import codecs
dec = codecs.getincrementaldecoder('utf-8')()
dec.decode(b'ok\xd0')
try:
    dec.decode(b'', final=True)
except UnicodeDecodeError as e:
    print(e.reason)  # → unexpected end of data

See also

Common errors

Open in the full glossarydocs.python.orgReport an inaccuracy