The python codecs module provides StreamWriter classes for transparently encoding output streams. For instance:
outstream = codecs.getwriter('utf8')(sys.__stdout__)
outstream.write(u'\u2713')
outstream.write(' A-OK!\n') # I want this to fail!
outstream.close()
However the problem I have with the default StreamWriter is that it will except str objects as well as unicode objects. If my program is writing a str to this stream, it is a bug and I want it to fail! Is there a way to make this happen without writing my own StreamWriter that enforces the type of objects written?
Also, I don’t want my solution to be sensitive to sys.stdout.encoding, sys.stdout.isatty(), locale.getpreferredencoding(), sys.getfilesystemencoding(), os.environ["PYTHONIOENCODING"] or whatever other ways python has of trying to be clever.
If possible, do what you’re trying to do in Python 3, which has a much stronger distinction between unicode and bytes. Failing that, you’ll need to subclass
StreamWriter, for example: