Should I include this boilerplate code in every Python script I write?
<p>My boss asked me to put the following lines (from <a href="https://stackoverflow.com/questions/4374455/how-to-set-sys-stdout-encoding-in-python-3">this answer</a>) into a Python 3 script I wrote:</p>

<pre><code>import sys
import codecs
sys.stdout = codecs.getwriter("utf-8")(sys.stdout.detach()) 
</code></pre>

<p>He says it's to prevent <code>UnicodeEncodeErrors</code> when printing Unicode characters in non-UTF8 locales. I am wondering whether this is really necessary, and why Python wouldn't handle encoding/decoding correctly without boilerplate code.</p>

<p>What is the most Pythonic way to make Python scripts compatible with different operating system locales? And what does this boilerplate code do exactly?</p>

<p>The answer provided <a href="http://stackoverflow.com/questions/11741574/how-to-print-utf-8-encoded-text-to-the-console-in-python-3">here</a> has a good excerpt from the Python mailing list regarding your question. I guess it is not necessary to do this.</p>

<blockquote>
  <p>The only supported default encodings in Python are:</p>
  
  <p>Python 2.x: ASCII<br>
  Python 3.x: UTF-8</p>
  
  <p>If you change these, you are on your own and strange things will start
  to happen. The default encoding does not only affect the translation
  between Python and the outside world, but also all internal
  conversions between 8-bit strings and Unicode.</p>
  
  <p>Hacks like what's happening in the pango module (setting the default
  encoding to 'utf-8' by reloading the site module in order to get the
  sys.setdefaultencoding() API back) are just downright wrong and will
  cause serious problems since Unicode objects cache their default
  encoded representation.</p>
  
  <p>Please don't enable the use of a locale based default encoding.</p>
  
  <p>If all you want to achieve is getting the encodings of stdout and
  stdin correctly setup for pipes, you should instead change the
  .encoding attribute of those (only).</p>
  
  <p>--<br>
  Marc-Andre Lemburg<br>
  eGenix.com</p>
</blockquote>

python python-3.x unicode