all Python 3codecsterm
codecs.Codec
base classes
The base class of a stateless codec: encode and decode return a pair (result, length consumed). You subclass it when writing your own codec.
Syntax
class MyCodec(codecs.Codec):
def encode(self, input, errors='strict'): ...
Application code does not need this class: encoding and decoding are str.encode and bytes.decode. The base methods raise NotImplementedError. The contract is strict: return a two-item tuple whose second item is the length of the INPUT consumed, not of the output. For the codec to be found by name it still has to be registered with codecs.register.
Examples
import codecs
class Upper(codecs.Codec):
def encode(self, text, errors='strict'):
return text.upper().encode('ascii', errors), len(text)
def decode(self, data, errors='strict'):
return bytes(data).decode('ascii', errors), len(data)
print(Upper().encode('abc')) # → (b'ABC', 3)
See also
Open in the full glossarydocs.python.orgReport an inaccuracy