Python Glossary Русский

all Python 3codecsfunction

codecs.getencoder()

codec registry

Returns a codec's stateless encoder function: it takes a string and returns a pair (bytes, number of characters consumed). Same as lookup(name).encode.

Syntax

encode = codecs.getencoder(encoding)

The main trap is that the result is a tuple, not bytes: f('я') returns (b'\xd1\x8f', 1), and writing it to a file as is raises TypeError. The encoder keeps no state, so for UTF-16 every call writes a fresh BOM; for chunks use getincrementalencoder. If you just need bytes, str.encode is shorter and clearer.

Examples

import codecs
enc = codecs.getencoder('utf-8')
data, used = enc('яблоко')
print(data[:2], used)  # → b'\xd1\x8f' 6
enc16 = codecs.getencoder('utf-16')
print(enc16('a')[0], enc16('b')[0])  # → ? b'\xff\xfea\x00' b'\xff\xfeb\x00' — BOM в каждом вызове, порядок байтов зависит от машины

See also

Open in the full glossarydocs.python.orgReport an inaccuracy