title: Best output type and encoding practices for __repr__() functions?
body: <p>Lately, I've had lots of trouble with <code>__repr__()</code>, <code>format()</code>, and encodings.  <strong>Should the output of <code>__repr__()</code> be encoded or be a unicode string?</strong>  Is there a best encoding for the result of <code>__repr__()</code> in Python?  What I want to output does have non-ASCII characters.</p>
  
  <p>I use Python 2.x, and want to write code that can easily be adapted to Python 3.  The program thus uses</p>
  
  <pre><code># -*- coding: utf-8 -*-
  from __future__ import unicode_literals, print_function  # The 'Hello' literal represents a Unicode object
  </code></pre>
  
  <p>Here are some additional problems that have been bothering me, and I'm looking for a solution that solves them:</p>
  
  <ol>
  <li>Printing to an UTF-8 terminal should work (I have <code>sys.stdout.encoding</code> set to <code>UTF-8</code>, but it would be best if other cases worked too).</li>
  <li>Piping the output to a file (encoded in UTF-8) should work (in this case, <code>sys.stdout.encoding</code> is <code>None</code>).</li>
  <li>My code for many <code>__repr__()</code> functions currently has many <code>return ….encode('utf-8')</code>, and that's heavy.  Is there anything robust and lighter?</li>
  <li>In some cases, I even have ugly beasts like <code>return ('&lt;{}&gt;'.format(repr(x).decode('utf-8'))).encode('utf-8')</code>, i.e., the representation of objects is decoded, put into a formatting string, and then re-encoded.  I would like to avoid such convoluted transformations.</li>
  </ol>
  
  <p>What would you recommend to do in order to write simple <code>__repr__()</code> functions that behave nicely with respect to these encoding questions?</p>