all Python 3codecsfunction
codecs.register()
codec registry
Registers a codec search function: given a normalised name it returns a CodecInfo or None. This is how you add your own encoding to Python.
Syntax
codecs.register(search_function)
You register a search function, not a codec, and it must return None for names it does not own, or it hijacks every lookup. The name arrives lower-cased, so compare against 'shout', not 'Shout'. Results are cached: after the first successful lookup, changing your search function no longer affects that name; codecs.unregister (3.10+) removes it. For a coursework task a custom codec is almost never needed: str.translate or a plain function does the job.
Examples
import codecs
def search(name):
if name == 'shout':
enc = lambda s, errors='strict': (s.upper().encode(), len(s))
dec = lambda b, errors='strict': (bytes(b).decode().lower(), len(b))
return codecs.CodecInfo(enc, dec, name='shout')
return None
codecs.register(search)
print('hi'.encode('Shout')) # → b'HI'
print(b'HI'.decode('shout')) # → hi
See also
Open in the full glossarydocs.python.orgReport an inaccuracy