title: Pythonic way to ensure unicode in python 2 and 3
body: <p>I'm working on porting a library so that it is compatible with both python 2 and 3.  The library receives strings or string-like objects from the calling application and I need to ensure those objects get converted to unicode strings.</p>
  
  <p>In python 2 I can do:</p>
  
  <pre><code>unicode_x = unicode(x)
  </code></pre>
  
  <p>In python 3 I can do:</p>
  
  <pre><code>unicode_x = str(x)
  </code></pre>
  
  <p>However, the best cross-version solution I have is:</p>
  
  <pre><code>def ensure_unicode(x):
    if sys.version_info &lt; (3, 0):
      return unicode(x)
    return str(x)
  </code></pre>
  
  <p>which certainly doesn't seem great (although it works).  Is there a better solution?</p>
  
  <p>I am aware of <code>unicode_literals</code> and the <code>u</code> prefix but both of those solutions do not work as the inputs come from clients and are not literals in my library.</p>