Python Glossary Русский

all Python 3codecsfunction

codecs.strict_errors()

error handlers

The 'strict' error handler, the default for encode and decode: it simply raises the UnicodeEncodeError or UnicodeDecodeError it receives.

Syntax

codecs.strict_errors(exception)

Strict is the right default: failing beats silently corrupting data. An error while reading a file almost always means the wrong encoding (cp1251 instead of utf-8), not a reason to set errors='ignore'. You call the function directly inside your own handler to behave like strict for cases it does not handle.

Examples

import codecs
def only_e(err):
    if err.object[err.start:err.end] == 'é':
        return ('e', err.end)
    return codecs.strict_errors(err)
codecs.register_error('only_e', only_e)
print('café'.encode('ascii', 'only_e'))  # → b'cafe'
try:
    'naïve'.encode('ascii', 'only_e')
except UnicodeEncodeError as e:
    print(e.reason)  # → ordinal not in range(128)

See also

Common errors

Open in the full glossarydocs.python.orgReport an inaccuracy