Is this the right way to write a codec error handler?
Steven D'Aprano
steve+comp.lang.python at pearwood.info
Sat Jan 20 03:32:43 EST 2018
I want an error handler that falls back on Latin-1 for anything which
cannot be decoded. Is this the right way to write it?
def latin1_fallback(exception):
assert isinstance(exception, UnicodeError)
start, end = exception.start, exception.end
obj = exception.object
if isinstance(exception, UnicodeDecodeError):
return (obj[start:end].decode('latin1'), end+1)
elif isinstance(exception, UnicodeEncodeError):
return (obj[start:end].encode('latin1'), end+1)
else:
raise
Comments, corrections and criticisms welcome.
Thanks.
--
Steve
More information about the Python-list
mailing list