/
usr
/
share
/
doc
/
python-kitchen-1.1.1
/
html
/
Upload File
HOME
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Designing Unicode Aware APIs — kitchen 1.1.1 documentation</title> <link rel="stylesheet" href="_static/default.css" type="text/css" /> <link rel="stylesheet" href="_static/pygments.css" type="text/css" /> <script type="text/javascript"> var DOCUMENTATION_OPTIONS = { URL_ROOT: '', VERSION: '1.1.1', COLLAPSE_INDEX: false, FILE_SUFFIX: '.html', HAS_SOURCE: true }; </script> <script type="text/javascript" src="_static/jquery.js"></script> <script type="text/javascript" src="_static/underscore.js"></script> <script type="text/javascript" src="_static/doctools.js"></script> <link rel="search" type="application/opensearchdescription+xml" title="Search within kitchen 1.1.1 documentation" href="_static/opensearch.xml"/> <link rel="top" title="kitchen 1.1.1 documentation" href="index.html" /> <link rel="up" title="Using kitchen to write good code" href="tutorial.html" /> <link rel="next" title="Kitchen API" href="api-overview.html" /> <link rel="prev" title="Overcoming frustration: Correctly using unicode in python2" href="unicode-frustrations.html" /> </head> <body> <div class="related"> <h3>Navigation</h3> <ul> <li class="right" style="margin-right: 10px"> <a href="genindex.html" title="General Index" accesskey="I">index</a></li> <li class="right" > <a href="py-modindex.html" title="Python Module Index" >modules</a> |</li> <li class="right" > <a href="api-overview.html" title="Kitchen API" accesskey="N">next</a> |</li> <li class="right" > <a href="unicode-frustrations.html" title="Overcoming frustration: Correctly using unicode in python2" accesskey="P">previous</a> |</li> <li><a href="index.html">kitchen 1.1.1 documentation</a> »</li> <li><a href="tutorial.html" accesskey="U">Using kitchen to write good code</a> »</li> </ul> </div> <div class="document"> <div class="documentwrapper"> <div class="bodywrapper"> <div class="body"> <div class="section" id="designing-unicode-aware-apis"> <span id="designingunicodeawareapis"></span><h1><a class="toc-backref" href="#id1">Designing Unicode Aware APIs</a><a class="headerlink" href="#designing-unicode-aware-apis" title="Permalink to this headline">¶</a></h1> <p>APIs that deal with byte <tt class="xref py py-class docutils literal"><span class="pre">str</span></tt> and <tt class="xref py py-class docutils literal"><span class="pre">unicode</span></tt> strings are difficult to get right. Here are a few strategies with pros and cons of each.</p> <div class="contents topic" id="contents"> <p class="topic-title first">Contents</p> <ul class="simple"> <li><a class="reference internal" href="#designing-unicode-aware-apis" id="id1">Designing Unicode Aware APIs</a><ul> <li><a class="reference internal" href="#take-either-bytes-or-unicode-output-only-unicode" id="id2">Take either bytes or unicode, output only unicode</a></li> <li><a class="reference internal" href="#take-either-bytes-or-unicode-output-the-same-type" id="id3">Take either bytes or unicode, output the same type</a></li> <li><a class="reference internal" href="#separate-functions" id="id4">Separate functions</a></li> <li><a class="reference internal" href="#deciding-whether-to-take-str-or-unicode-when-no-value-is-returned" id="id5">Deciding whether to take str or unicode when no value is returned</a><ul> <li><a class="reference internal" href="#writing-to-external-data" id="id6">Writing to external data</a></li> <li><a class="reference internal" href="#updating-data-structures" id="id7">Updating data structures</a></li> </ul> </li> <li><a class="reference internal" href="#apis-to-avoid" id="id8">APIs to Avoid</a><ul> <li><a class="reference internal" href="#returning-unicode-unless-a-conversion-fails" id="id9">Returning unicode unless a conversion fails</a></li> <li><a class="reference internal" href="#ignoring-values-with-no-chance-of-recovery" id="id10">Ignoring values with no chance of recovery</a></li> <li><a class="reference internal" href="#raising-a-unicodeexception-with-no-chance-of-recovery" id="id11">Raising a UnicodeException with no chance of recovery</a></li> </ul> </li> <li><a class="reference internal" href="#knowing-your-data" id="id12">Knowing your data</a><ul> <li><a class="reference internal" href="#do-you-need-to-operate-on-both-bytes-and-unicode" id="id13">Do you need to operate on both bytes and unicode?</a></li> <li><a class="reference internal" href="#can-you-restrict-the-encodings" id="id14">Can you restrict the encodings?</a><ul> <li><a class="reference internal" href="#single-byte-encodings" id="id15">Single byte encodings</a></li> <li><a class="reference internal" href="#multibyte-encodings" id="id16">Multibyte encodings</a><ul> <li><a class="reference internal" href="#fixed-width" id="id17">Fixed width</a></li> <li><a class="reference internal" href="#variable-width" id="id18">Variable Width</a><ul> <li><a class="reference internal" href="#ascii-compatible" id="id19">ASCII compatible</a></li> <li><a class="reference internal" href="#escaped" id="id20">Escaped</a></li> <li><a class="reference internal" href="#other" id="id21">Other</a></li> </ul> </li> </ul> </li> </ul> </li> </ul> </li> </ul> </li> </ul> </div> <div class="section" id="take-either-bytes-or-unicode-output-only-unicode"> <h2><a class="toc-backref" href="#id2">Take either bytes or unicode, output only unicode</a><a class="headerlink" href="#take-either-bytes-or-unicode-output-only-unicode" title="Permalink to this headline">¶</a></h2> <p>In this strategy, you allow the user to enter either <tt class="xref py py-class docutils literal"><span class="pre">unicode</span></tt> strings or byte <tt class="xref py py-class docutils literal"><span class="pre">str</span></tt> but what you give back is always <tt class="xref py py-class docutils literal"><span class="pre">unicode</span></tt>. This strategy is easy for novice endusers to start using immediately as they will be able to feed either type of string into the function and get back a string that they can use in other places.</p> <p>However, it does lead to the novice writing code that functions correctly when testing it with <a class="reference internal" href="glossary.html#term-ascii"><em class="xref std std-term">ASCII</em></a>-only data but fails when given data that contains non-<a class="reference internal" href="glossary.html#term-ascii"><em class="xref std std-term">ASCII</em></a> characters. Worse, if your API is not designed to be flexible, the consumer of your code won’t be able to easily correct those problems once they find them.</p> <p>Here’s a good API that uses this strategy:</p> <div class="highlight-python"><div class="highlight"><pre><span class="kn">from</span> <span class="nn">kitchen.text.converters</span> <span class="kn">import</span> <span class="n">to_unicode</span> <span class="k">def</span> <span class="nf">truncate</span><span class="p">(</span><span class="n">msg</span><span class="p">,</span> <span class="n">max_length</span><span class="p">,</span> <span class="n">encoding</span><span class="o">=</span><span class="s">'utf8'</span><span class="p">,</span> <span class="n">errors</span><span class="o">=</span><span class="s">'replace'</span><span class="p">):</span> <span class="n">msg</span> <span class="o">=</span> <span class="n">to_unicode</span><span class="p">(</span><span class="n">msg</span><span class="p">,</span> <span class="n">encoding</span><span class="p">,</span> <span class="n">errors</span><span class="p">)</span> <span class="k">return</span> <span class="n">msg</span><span class="p">[:</span><span class="n">max_length</span><span class="p">]</span> </pre></div> </div> <p>The call to <tt class="xref py py-func docutils literal"><span class="pre">truncate()</span></tt> starts with the essential parameters for performing the task. It ends with two optional keyword arguments that define the encoding to use to transform from a byte <tt class="xref py py-class docutils literal"><span class="pre">str</span></tt> to <tt class="xref py py-class docutils literal"><span class="pre">unicode</span></tt> and the strategy to use if undecodable bytes are encountered. The defaults may vary depending on the use cases you have in mind. When the output is generally going to be printed for the user to see, <tt class="docutils literal"><span class="pre">errors='replace'</span></tt> is a good default. If you are constructing keys to a database, raisng an exception (with <tt class="docutils literal"><span class="pre">errors='strict'</span></tt>) may be a better default. In either case, having both parameters allows the person using your API to choose how they want to handle any problems. Having the values is also a clue to them that a conversion from byte <tt class="xref py py-class docutils literal"><span class="pre">str</span></tt> to <tt class="xref py py-class docutils literal"><span class="pre">unicode</span></tt> string is going to occur.</p> <div class="admonition note"> <p class="first admonition-title">Note</p> <p>If you’re targeting python-3.1 and above, <tt class="docutils literal"><span class="pre">errors='surrogateescape'</span></tt> may be a better default than <tt class="docutils literal"><span class="pre">errors='strict'</span></tt>. You need to be mindful of a few things when using <tt class="docutils literal"><span class="pre">surrogateescape</span></tt> though:</p> <ul class="simple"> <li><tt class="docutils literal"><span class="pre">surrogateescape</span></tt> will cause issues if a non-<a class="reference internal" href="glossary.html#term-ascii"><em class="xref std std-term">ASCII</em></a> compatible encoding is used (for instance, UTF-16 and UTF-32.) That makes it unhelpful in situations where a true general purpose method of encoding must be found. <span class="target" id="index-0"></span><a class="pep reference external" href="http://www.python.org/dev/peps/pep-0383"><strong>PEP 383</strong></a> mentions that <tt class="docutils literal"><span class="pre">surrogateescape</span></tt> was specifically designed with the limitations of translating using system locales (where <a class="reference internal" href="glossary.html#term-ascii"><em class="xref std std-term">ASCII</em></a> compatibility is generally seen as inescapable) so you should keep that in mind.</li> <li>If you use <tt class="docutils literal"><span class="pre">surrogateescape</span></tt> to decode from <tt class="xref py py-class docutils literal"><span class="pre">bytes</span></tt> to <tt class="xref py py-class docutils literal"><span class="pre">unicode</span></tt> you will need to use an error handler other than <tt class="docutils literal"><span class="pre">strict</span></tt> to encode as the lone surrogate that this error handler creates makes for invalid unicode that must be handled when encoding. In Python-3.1.2 or less, a bug in the encoder error handlers mean that you can only use <tt class="docutils literal"><span class="pre">surrogateescape</span></tt> to encode; anything else will throw an error.</li> </ul> <p class="last">Evaluate your usages of the variables in question to see what makes sense.</p> </div> <p>Here’s a bad example of using this strategy:</p> <div class="highlight-python"><div class="highlight"><pre><span class="kn">from</span> <span class="nn">kitchen.text.converters</span> <span class="kn">import</span> <span class="n">to_unicode</span> <span class="k">def</span> <span class="nf">truncate</span><span class="p">(</span><span class="n">msg</span><span class="p">,</span> <span class="n">max_length</span><span class="p">):</span> <span class="n">msg</span> <span class="o">=</span> <span class="n">to_unicode</span><span class="p">(</span><span class="n">msg</span><span class="p">)</span> <span class="k">return</span> <span class="n">msg</span><span class="p">[:</span><span class="n">max_length</span><span class="p">]</span> </pre></div> </div> <p>In this example, we don’t have the optional keyword arguments for <tt class="xref py py-attr docutils literal"><span class="pre">encoding</span></tt> and <tt class="xref py py-attr docutils literal"><span class="pre">errors</span></tt>. A user who uses this function is more likely to miss the fact that a conversion from byte <tt class="xref py py-class docutils literal"><span class="pre">str</span></tt> to <tt class="xref py py-class docutils literal"><span class="pre">unicode</span></tt> is going to occur. And once an error is reported, they will have to look through their backtrace and think harder about where they want to transform their data into <tt class="xref py py-class docutils literal"><span class="pre">unicode</span></tt> strings instead of having the opportunity to control how the conversion takes place in the function itself. Note that the user does have the ability to make this work by making the transformation to unicode themselves:</p> <div class="highlight-python"><div class="highlight"><pre><span class="kn">from</span> <span class="nn">kitchen.text.converters</span> <span class="kn">import</span> <span class="n">to_unicode</span> <span class="n">msg</span> <span class="o">=</span> <span class="n">to_unicode</span><span class="p">(</span><span class="n">msg</span><span class="p">,</span> <span class="n">encoding</span><span class="o">=</span><span class="s">'euc_jp'</span><span class="p">,</span> <span class="n">errors</span><span class="o">=</span><span class="s">'ignore'</span><span class="p">)</span> <span class="n">new_msg</span> <span class="o">=</span> <span class="n">truncate</span><span class="p">(</span><span class="n">msg</span><span class="p">,</span> <span class="mi">5</span><span class="p">)</span> </pre></div> </div> </div> <div class="section" id="take-either-bytes-or-unicode-output-the-same-type"> <h2><a class="toc-backref" href="#id3">Take either bytes or unicode, output the same type</a><a class="headerlink" href="#take-either-bytes-or-unicode-output-the-same-type" title="Permalink to this headline">¶</a></h2> <p>This strategy is sometimes called polymorphic because the type of data that is returned is dependent on the type of data that is received. The concept is that when you are given a byte <tt class="xref py py-class docutils literal"><span class="pre">str</span></tt> to process, you return a byte <tt class="xref py py-class docutils literal"><span class="pre">str</span></tt> in your output. When you are given <tt class="xref py py-class docutils literal"><span class="pre">unicode</span></tt> strings to process, you return <tt class="xref py py-class docutils literal"><span class="pre">unicode</span></tt> strings in your output.</p> <p>This can work well for end users as the ones that know about the difference between the two string types will already have transformed the strings to their desired type before giving it to this function. The ones that don’t can remain blissfully ignorant (at least, as far as your function is concerned) as the function does not change the type.</p> <p>In cases where the encoding of the byte <tt class="xref py py-class docutils literal"><span class="pre">str</span></tt> is known or can be discovered based on the input data this works well. If you can’t figure out the input encoding, however, this strategy can fail in any of the following cases:</p> <ol class="arabic simple"> <li>It needs to do an internal conversion between byte <tt class="xref py py-class docutils literal"><span class="pre">str</span></tt> and <tt class="xref py py-class docutils literal"><span class="pre">unicode</span></tt> string.</li> <li>It cannot return the same data as either a <tt class="xref py py-class docutils literal"><span class="pre">unicode</span></tt> string or byte <tt class="xref py py-class docutils literal"><span class="pre">str</span></tt>.</li> <li>You may need to deal with byte strings that are not byte-compatible with <a class="reference internal" href="glossary.html#term-ascii"><em class="xref std std-term">ASCII</em></a></li> </ol> <p>First, a couple examples of using this strategy in a good way:</p> <div class="highlight-python"><div class="highlight"><pre><span class="k">def</span> <span class="nf">translate</span><span class="p">(</span><span class="n">msg</span><span class="p">,</span> <span class="n">table</span><span class="p">):</span> <span class="n">replacements</span> <span class="o">=</span> <span class="n">table</span><span class="o">.</span><span class="n">keys</span><span class="p">()</span> <span class="n">new_msg</span> <span class="o">=</span> <span class="p">[]</span> <span class="k">for</span> <span class="n">index</span><span class="p">,</span> <span class="n">char</span> <span class="ow">in</span> <span class="nb">enumerate</span><span class="p">(</span><span class="n">msg</span><span class="p">):</span> <span class="k">if</span> <span class="n">char</span> <span class="ow">in</span> <span class="n">replacements</span><span class="p">:</span> <span class="n">new_msg</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">table</span><span class="p">[</span><span class="n">char</span><span class="p">])</span> <span class="k">else</span><span class="p">:</span> <span class="n">new_msg</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">char</span><span class="p">)</span> <span class="k">return</span> <span class="s">''</span><span class="o">.</span><span class="n">join</span><span class="p">(</span><span class="n">new_msg</span><span class="p">)</span> </pre></div> </div> <p>In this example, all of the strings that we use (except the empty string which is okay because it doesn’t have any characters to encode) come from outside of the function. Due to that, the user is responsible for making sure that the <tt class="xref py py-attr docutils literal"><span class="pre">msg</span></tt>, and the keys and values in <tt class="xref py py-attr docutils literal"><span class="pre">table</span></tt> all match in terms of type (<tt class="xref py py-class docutils literal"><span class="pre">unicode</span></tt> vs <tt class="xref py py-class docutils literal"><span class="pre">str</span></tt>) and encoding (You can do some error checking to make sure the user gave all the same type but you can’t do the same for the user giving different encodings). You do not need to make changes to the string that require you to know the encoding or type of the string; everything is a simple replacement of one element in the array of characters in message with the character in table.</p> <div class="highlight-python"><pre>import json from kitchen.text.converters import to_unicode, to_bytes def first_field_from_json_data(json_string): '''Return the first field in a json data structure. The format of the json data is a simple list of strings. '["one", "two", "three"]' ''' if isinstance(json_string, unicode): # On all python versions, json.loads() returns unicode if given # a unicode string return json.loads(json_string)[0] # Byte str: figure out which encoding we're dealing with if '\x00' not in json_data[:2] encoding = 'utf8' elif '\x00\x00\x00' == json_data[:3]: encoding = 'utf-32-be' elif '\x00\x00\x00' == json_data[1:4]: encoding = 'utf-32-le' elif '\x00' == json_data[0] and '\x00' == json_data[2]: encoding = 'utf-16-be' else: encoding = 'utf-16-le' data = json.loads(unicode(json_string, encoding)) return data[0].encode(encoding)</pre> </div> <p>In this example the function takes either a byte <tt class="xref py py-class docutils literal"><span class="pre">str</span></tt> type or a <tt class="xref py py-class docutils literal"><span class="pre">unicode</span></tt> string that has a list in json format and returns the first field from it as the type of the input string. The first section of code is very straightforward; we receive a <tt class="xref py py-class docutils literal"><span class="pre">unicode</span></tt> string, parse it with a function, and then return the first field from our parsed data (which our function returned to us as json data).</p> <p>The second portion that deals with byte <tt class="xref py py-class docutils literal"><span class="pre">str</span></tt> is not so straightforward. Before we can parse the string we have to determine what characters the bytes in the string map to. If we didn’t do that, we wouldn’t be able to properly find which characters are present in the string. In order to do that we have to figure out the encoding of the byte <tt class="xref py py-class docutils literal"><span class="pre">str</span></tt>. Luckily, the json specification states that all strings are unicode and encoded with one of UTF32be, UTF32le, UTF16be, UTF16le, or <a class="reference internal" href="glossary.html#term-utf-8"><em class="xref std std-term">UTF-8</em></a>. It further defines the format such that the first two characters are always <a class="reference internal" href="glossary.html#term-ascii"><em class="xref std std-term">ASCII</em></a>. Each of these has a different sequence of NULLs when they encode an <a class="reference internal" href="glossary.html#term-ascii"><em class="xref std std-term">ASCII</em></a> character. We can use that to detect which encoding was used to create the byte <tt class="xref py py-class docutils literal"><span class="pre">str</span></tt>.</p> <p>Finally, we return the byte <tt class="xref py py-class docutils literal"><span class="pre">str</span></tt> by encoding the <tt class="xref py py-class docutils literal"><span class="pre">unicode</span></tt> back to a byte <tt class="xref py py-class docutils literal"><span class="pre">str</span></tt>.</p> <p>As you can see, in this example we have to convert from byte <tt class="xref py py-class docutils literal"><span class="pre">str</span></tt> to <tt class="xref py py-class docutils literal"><span class="pre">unicode</span></tt> and back. But we know from the json specification that byte <tt class="xref py py-class docutils literal"><span class="pre">str</span></tt> has to be one of a limited number of encodings that we are able to detect. That ability makes this strategy work.</p> <p>Now for some examples of using this strategy in ways that fail:</p> <div class="highlight-python"><div class="highlight"><pre><span class="kn">import</span> <span class="nn">unicodedata</span> <span class="k">def</span> <span class="nf">first_char</span><span class="p">(</span><span class="n">msg</span><span class="p">):</span> <span class="sd">'''Return the first character in a string'''</span> <span class="k">if</span> <span class="ow">not</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">msg</span><span class="p">,</span> <span class="nb">unicode</span><span class="p">):</span> <span class="k">try</span><span class="p">:</span> <span class="n">msg</span> <span class="o">=</span> <span class="nb">unicode</span><span class="p">(</span><span class="n">msg</span><span class="p">,</span> <span class="s">'utf8'</span><span class="p">)</span> <span class="k">except</span> <span class="ne">UnicodeError</span><span class="p">:</span> <span class="n">msg</span> <span class="o">=</span> <span class="nb">unicode</span><span class="p">(</span><span class="n">msg</span><span class="p">,</span> <span class="s">'latin1'</span><span class="p">)</span> <span class="n">msg</span> <span class="o">=</span> <span class="n">unicodedata</span><span class="o">.</span><span class="n">normalize</span><span class="p">(</span><span class="s">'NFC'</span><span class="p">,</span> <span class="n">msg</span><span class="p">)</span> <span class="k">return</span> <span class="n">msg</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span> </pre></div> </div> <p>If you look at that code and think that there’s something fragile and prone to breaking in the <tt class="docutils literal"><span class="pre">try:</span> <span class="pre">except:</span></tt> block you are correct in being suspicious. This code will fail on multi-byte character sets that aren’t <a class="reference internal" href="glossary.html#term-utf-8"><em class="xref std std-term">UTF-8</em></a>. It can also fail on data where the sequence of bytes is valid <a class="reference internal" href="glossary.html#term-utf-8"><em class="xref std std-term">UTF-8</em></a> but the bytes are actually of a different encoding. The reasons this code fails is that we don’t know what encoding the bytes are in and the code must convert from a byte <tt class="xref py py-class docutils literal"><span class="pre">str</span></tt> to a <tt class="xref py py-class docutils literal"><span class="pre">unicode</span></tt> string in order to function.</p> <p>In order to make this code robust we must know the encoding of <tt class="xref py py-attr docutils literal"><span class="pre">msg</span></tt>. The only way to know that is to ask the user so the API must do that:</p> <div class="highlight-python"><div class="highlight"><pre><span class="kn">import</span> <span class="nn">unicodedata</span> <span class="k">def</span> <span class="nf">number_of_chars</span><span class="p">(</span><span class="n">msg</span><span class="p">,</span> <span class="n">encoding</span><span class="o">=</span><span class="s">'utf8'</span><span class="p">,</span> <span class="n">errors</span><span class="o">=</span><span class="s">'strict'</span><span class="p">):</span> <span class="k">if</span> <span class="ow">not</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">msg</span><span class="p">,</span> <span class="nb">unicode</span><span class="p">):</span> <span class="n">msg</span> <span class="o">=</span> <span class="nb">unicode</span><span class="p">(</span><span class="n">msg</span><span class="p">,</span> <span class="n">encoding</span><span class="p">,</span> <span class="n">errors</span><span class="p">)</span> <span class="n">msg</span> <span class="o">=</span> <span class="n">unicodedata</span><span class="o">.</span><span class="n">normalize</span><span class="p">(</span><span class="s">'NFC'</span><span class="p">,</span> <span class="n">msg</span><span class="p">)</span> <span class="k">return</span> <span class="nb">len</span><span class="p">(</span><span class="n">msg</span><span class="p">)</span> </pre></div> </div> <p>Another example of failure:</p> <div class="highlight-python"><div class="highlight"><pre><span class="kn">import</span> <span class="nn">os</span> <span class="k">def</span> <span class="nf">listdir</span><span class="p">(</span><span class="n">directory</span><span class="p">):</span> <span class="n">files</span> <span class="o">=</span> <span class="n">os</span><span class="o">.</span><span class="n">listdir</span><span class="p">(</span><span class="n">directory</span><span class="p">)</span> <span class="k">if</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">directory</span><span class="p">,</span> <span class="nb">str</span><span class="p">):</span> <span class="k">return</span> <span class="n">files</span> <span class="c"># files could contain both bytes and unicode</span> <span class="n">new_files</span> <span class="o">=</span> <span class="p">[]</span> <span class="k">for</span> <span class="n">filename</span> <span class="ow">in</span> <span class="n">files</span><span class="p">:</span> <span class="k">if</span> <span class="ow">not</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">filename</span><span class="p">,</span> <span class="nb">unicode</span><span class="p">):</span> <span class="c"># What to do here?</span> <span class="k">continue</span> <span class="n">new_files</span><span class="o">.</span><span class="n">appen</span><span class="p">(</span><span class="n">filename</span><span class="p">)</span> <span class="k">return</span> <span class="n">new_files</span> </pre></div> </div> <p>This function illustrates the second failure mode. Here, not all of the possible values can be represented as <tt class="xref py py-class docutils literal"><span class="pre">unicode</span></tt> without knowing more about the encoding of each of the filenames involved. Since each filename could have a different encoding there’s a few different options to pursue. We could make this function always return byte <tt class="xref py py-class docutils literal"><span class="pre">str</span></tt> since that can accurately represent anything that could be returned. If we want to return <tt class="xref py py-class docutils literal"><span class="pre">unicode</span></tt> we need to at least allow the user to specify what to do in case of an error decoding the bytes to <tt class="xref py py-class docutils literal"><span class="pre">unicode</span></tt>. We can also let the user specify the encoding to use for doing the decoding but that won’t help in all cases since not all files will be in the same encoding (or even necessarily in any encoding):</p> <div class="highlight-python"><div class="highlight"><pre><span class="kn">import</span> <span class="nn">locale</span> <span class="kn">import</span> <span class="nn">os</span> <span class="k">def</span> <span class="nf">listdir</span><span class="p">(</span><span class="n">directory</span><span class="p">,</span> <span class="n">encoding</span><span class="o">=</span><span class="n">locale</span><span class="o">.</span><span class="n">getpreferredencoding</span><span class="p">(),</span> <span class="n">errors</span><span class="o">=</span><span class="s">'strict'</span><span class="p">):</span> <span class="c"># Note: In python-3.1+, surrogateescape may be a better default</span> <span class="n">files</span> <span class="o">=</span> <span class="n">os</span><span class="o">.</span><span class="n">listdir</span><span class="p">(</span><span class="n">directory</span><span class="p">)</span> <span class="k">if</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">directory</span><span class="p">,</span> <span class="nb">str</span><span class="p">):</span> <span class="k">return</span> <span class="n">files</span> <span class="n">new_files</span> <span class="o">=</span> <span class="p">[]</span> <span class="k">for</span> <span class="n">filename</span> <span class="ow">in</span> <span class="n">files</span><span class="p">:</span> <span class="k">if</span> <span class="ow">not</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">filename</span><span class="p">,</span> <span class="nb">unicode</span><span class="p">):</span> <span class="n">filename</span> <span class="o">=</span> <span class="nb">unicode</span><span class="p">(</span><span class="n">filename</span><span class="p">,</span> <span class="n">encoding</span><span class="o">=</span><span class="n">encoding</span><span class="p">,</span> <span class="n">errors</span><span class="o">=</span><span class="n">errors</span><span class="p">)</span> <span class="n">new_files</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">filename</span><span class="p">)</span> <span class="k">return</span> <span class="n">new_files</span> </pre></div> </div> <p>Note that although we use <tt class="xref py py-attr docutils literal"><span class="pre">errors</span></tt> in this example as what to pass to the codec that decodes to <tt class="xref py py-class docutils literal"><span class="pre">unicode</span></tt> we could also have an <tt class="xref py py-attr docutils literal"><span class="pre">errors</span></tt> argument that decides other things to do like skip a filename entirely, return a placeholder (<tt class="docutils literal"><span class="pre">Nondisplayable</span> <span class="pre">filename</span></tt>), or raise an exception.</p> <p>This leaves us with one last failure to describe:</p> <div class="highlight-python"><div class="highlight"><pre><span class="k">def</span> <span class="nf">first_field</span><span class="p">(</span><span class="n">csv_string</span><span class="p">):</span> <span class="sd">'''Return the first field in a comma separated values string.'''</span> <span class="k">try</span><span class="p">:</span> <span class="k">return</span> <span class="n">csv_string</span><span class="p">[:</span><span class="n">csv_string</span><span class="o">.</span><span class="n">index</span><span class="p">(</span><span class="s">','</span><span class="p">)]</span> <span class="k">except</span> <span class="ne">ValueError</span><span class="p">:</span> <span class="k">return</span> <span class="n">csv_string</span> </pre></div> </div> <p>This code looks simple enough. The hidden error here is that we are searching for a comma character in a byte <tt class="xref py py-class docutils literal"><span class="pre">str</span></tt> but not all encodings will use the same sequence of bytes to represent the comma. If you use an encoding that’s not <a class="reference internal" href="glossary.html#term-ascii"><em class="xref std std-term">ASCII</em></a> compatible on the byte level, then the literal comma <tt class="docutils literal"><span class="pre">','</span></tt> in the above code will match inappropriate bytes. Some examples of how it can fail:</p> <ul class="simple"> <li>Will find the byte representing an <a class="reference internal" href="glossary.html#term-ascii"><em class="xref std std-term">ASCII</em></a> comma in another character</li> <li>Will find the comma but leave trailing garbage bytes on the end of the string</li> <li>Will not match the character that represents the comma in this encoding</li> </ul> <p>There are two ways to solve this. You can either take the encoding value from the user or you can take the separator value from the user. Of the two, taking the encoding is the better option for two reasons:</p> <ol class="arabic"> <li><p class="first">Taking a separator argument doesn’t clearly document for the API user that the reason they must give it is to properly match the encoding of the <tt class="xref py py-attr docutils literal"><span class="pre">csv_string</span></tt>. They’re just as likely to think that it’s simply a way to specify an alternate character (like ”:” or “|”) for the separator.</p> </li> <li><p class="first">It’s possible for a variable width encoding to reuse the same byte sequence for different characters in multiple sequences.</p> <div class="admonition note"> <p class="first admonition-title">Note</p> <p class="last"><a class="reference internal" href="glossary.html#term-utf-8"><em class="xref std std-term">UTF-8</em></a> is resistant to this as any character’s sequence of bytes will never be a subset of another character’s sequence of bytes.</p> </div> </li> </ol> <p>With that in mind, here’s how to improve the API:</p> <div class="highlight-python"><div class="highlight"><pre><span class="k">def</span> <span class="nf">first_field</span><span class="p">(</span><span class="n">csv_string</span><span class="p">,</span> <span class="n">encoding</span><span class="o">=</span><span class="s">'utf-8'</span><span class="p">,</span> <span class="n">errors</span><span class="o">=</span><span class="s">'replace'</span><span class="p">):</span> <span class="k">if</span> <span class="ow">not</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">csv_string</span><span class="p">,</span> <span class="nb">unicode</span><span class="p">):</span> <span class="n">u_string</span> <span class="o">=</span> <span class="nb">unicode</span><span class="p">(</span><span class="n">csv_string</span><span class="p">,</span> <span class="n">encoding</span><span class="p">,</span> <span class="n">errors</span><span class="p">)</span> <span class="n">is_unicode</span> <span class="o">=</span> <span class="bp">False</span> <span class="k">else</span><span class="p">:</span> <span class="n">u_string</span> <span class="o">=</span> <span class="n">csv_string</span> <span class="k">try</span><span class="p">:</span> <span class="n">field</span> <span class="o">=</span> <span class="n">u_string</span><span class="p">[:</span><span class="n">U_string</span><span class="o">.</span><span class="n">index</span><span class="p">(</span><span class="s">u','</span><span class="p">)]</span> <span class="k">except</span> <span class="ne">ValueError</span><span class="p">:</span> <span class="k">return</span> <span class="n">csv_string</span> <span class="k">if</span> <span class="ow">not</span> <span class="n">is_unicode</span><span class="p">:</span> <span class="n">field</span> <span class="o">=</span> <span class="n">field</span><span class="o">.</span><span class="n">encode</span><span class="p">(</span><span class="n">encoding</span><span class="p">,</span> <span class="n">errors</span><span class="p">)</span> <span class="k">return</span> <span class="n">field</span> </pre></div> </div> <div class="admonition note"> <p class="first admonition-title">Note</p> <p>If you decide you’ll never encounter a variable width encoding that reuses byte sequences you can use this code instead:</p> <div class="last highlight-python"><div class="highlight"><pre><span class="k">def</span> <span class="nf">first_field</span><span class="p">(</span><span class="n">csv_string</span><span class="p">,</span> <span class="n">encoding</span><span class="o">=</span><span class="s">'utf-8'</span><span class="p">):</span> <span class="k">try</span><span class="p">:</span> <span class="k">return</span> <span class="n">csv_string</span><span class="p">[:</span><span class="n">csv_string</span><span class="o">.</span><span class="n">index</span><span class="p">(</span><span class="s">','</span><span class="o">.</span><span class="n">encode</span><span class="p">(</span><span class="n">encoding</span><span class="p">))]</span> <span class="k">except</span> <span class="ne">ValueError</span><span class="p">:</span> <span class="k">return</span> <span class="n">csv_string</span> </pre></div> </div> </div> </div> <div class="section" id="separate-functions"> <h2><a class="toc-backref" href="#id4">Separate functions</a><a class="headerlink" href="#separate-functions" title="Permalink to this headline">¶</a></h2> <p>Sometimes you want to be able to take either byte <tt class="xref py py-class docutils literal"><span class="pre">str</span></tt> or <tt class="xref py py-class docutils literal"><span class="pre">unicode</span></tt> strings, perform similar operations on either one and then return data in the same format as was given. Probably the easiest way to do that is to have separate functions for each and adopt a naming convention to show that one is for working with byte <tt class="xref py py-class docutils literal"><span class="pre">str</span></tt> and the other is for working with <tt class="xref py py-class docutils literal"><span class="pre">unicode</span></tt> strings:</p> <div class="highlight-python"><div class="highlight"><pre><span class="k">def</span> <span class="nf">translate_b</span><span class="p">(</span><span class="n">msg</span><span class="p">,</span> <span class="n">table</span><span class="p">):</span> <span class="sd">'''Replace values in str with other byte values like unicode.translate'''</span> <span class="k">if</span> <span class="ow">not</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">msg</span><span class="p">,</span> <span class="nb">str</span><span class="p">):</span> <span class="k">raise</span> <span class="ne">TypeError</span><span class="p">(</span><span class="s">'msg must be of type str'</span><span class="p">)</span> <span class="n">str_table</span> <span class="o">=</span> <span class="p">[</span><span class="nb">chr</span><span class="p">(</span><span class="n">s</span><span class="p">)</span> <span class="k">for</span> <span class="n">s</span> <span class="ow">in</span> <span class="nb">xrange</span><span class="p">(</span><span class="mi">0</span><span class="p">,</span><span class="mi">256</span><span class="p">)]</span> <span class="n">delete_chars</span> <span class="o">=</span> <span class="p">[]</span> <span class="k">for</span> <span class="n">chr_val</span> <span class="ow">in</span> <span class="p">(</span><span class="n">k</span> <span class="k">for</span> <span class="n">k</span> <span class="ow">in</span> <span class="n">table</span><span class="o">.</span><span class="n">keys</span><span class="p">()</span> <span class="k">if</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">k</span><span class="p">,</span> <span class="nb">int</span><span class="p">)):</span> <span class="k">if</span> <span class="n">chr_val</span> <span class="o">></span> <span class="mi">255</span><span class="p">:</span> <span class="k">raise</span> <span class="ne">ValueError</span><span class="p">(</span><span class="s">'Keys in table must not exceed 255)'</span><span class="p">)</span> <span class="k">if</span> <span class="n">table</span><span class="p">[</span><span class="n">chr_val</span><span class="p">]</span> <span class="o">==</span> <span class="bp">None</span><span class="p">:</span> <span class="n">delete_chars</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="nb">chr</span><span class="p">(</span><span class="n">chr_val</span><span class="p">))</span> <span class="k">elif</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">table</span><span class="p">[</span><span class="n">chr_val</span><span class="p">],</span> <span class="nb">int</span><span class="p">):</span> <span class="k">if</span> <span class="n">table</span><span class="p">[</span><span class="n">chr_val</span><span class="p">]</span> <span class="o">></span> <span class="mi">255</span><span class="p">:</span> <span class="k">raise</span> <span class="ne">TypeError</span><span class="p">(</span><span class="s">'table values cannot be more than 255 or less than 0'</span><span class="p">)</span> <span class="n">str_table</span><span class="p">[</span><span class="n">chr_val</span><span class="p">]</span> <span class="o">=</span> <span class="nb">chr</span><span class="p">(</span><span class="n">table</span><span class="p">[</span><span class="n">chr_val</span><span class="p">])</span> <span class="k">else</span><span class="p">:</span> <span class="k">if</span> <span class="ow">not</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">table</span><span class="p">[</span><span class="n">chr_val</span><span class="p">],</span> <span class="nb">str</span><span class="p">):</span> <span class="k">raise</span> <span class="ne">TypeError</span><span class="p">(</span><span class="s">'character mapping must return integer, None or str'</span><span class="p">)</span> <span class="n">str_table</span><span class="p">[</span><span class="n">chr_val</span><span class="p">]</span> <span class="o">=</span> <span class="n">table</span><span class="p">[</span><span class="n">chr_val</span><span class="p">]</span> <span class="n">str_table</span> <span class="o">=</span> <span class="s">''</span><span class="o">.</span><span class="n">join</span><span class="p">(</span><span class="n">str_table</span><span class="p">)</span> <span class="n">delete_chars</span> <span class="o">=</span> <span class="s">''</span><span class="o">.</span><span class="n">join</span><span class="p">(</span><span class="n">delete_chars</span><span class="p">)</span> <span class="k">return</span> <span class="n">msg</span><span class="o">.</span><span class="n">translate</span><span class="p">(</span><span class="n">str_table</span><span class="p">,</span> <span class="n">delete_chars</span><span class="p">)</span> <span class="k">def</span> <span class="nf">translate</span><span class="p">(</span><span class="n">msg</span><span class="p">,</span> <span class="n">table</span><span class="p">):</span> <span class="sd">'''Replace values in a unicode string with other values'''</span> <span class="k">if</span> <span class="ow">not</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">msg</span><span class="p">,</span> <span class="nb">unicode</span><span class="p">):</span> <span class="k">raise</span> <span class="ne">TypeError</span><span class="p">(</span><span class="s">'msg must be of type unicode'</span><span class="p">)</span> <span class="k">return</span> <span class="n">msg</span><span class="o">.</span><span class="n">translate</span><span class="p">(</span><span class="n">table</span><span class="p">)</span> </pre></div> </div> <p>There’s several things that we have to do in this API:</p> <ul class="simple"> <li>Because the function names might not be enough of a clue to the user of the functions of the value types that are expected, we have to check that the types are correct.</li> <li>We keep the behaviour of the two functions as close to the same as possible, just with byte <tt class="xref py py-class docutils literal"><span class="pre">str</span></tt> and <tt class="xref py py-class docutils literal"><span class="pre">unicode</span></tt> strings substituted for each other.</li> </ul> </div> <div class="section" id="deciding-whether-to-take-str-or-unicode-when-no-value-is-returned"> <h2><a class="toc-backref" href="#id5">Deciding whether to take str or unicode when no value is returned</a><a class="headerlink" href="#deciding-whether-to-take-str-or-unicode-when-no-value-is-returned" title="Permalink to this headline">¶</a></h2> <p>Not all functions have a return value. Sometimes a function is there to interact with something external to python, for instance, writing a file out to disk or a method exists to update the internal state of a data structure. One of the main questions with these APIs is whether to take byte <tt class="xref py py-class docutils literal"><span class="pre">str</span></tt>, <tt class="xref py py-class docutils literal"><span class="pre">unicode</span></tt> string, or both. The answer depends on your use case but I’ll give some examples here.</p> <div class="section" id="writing-to-external-data"> <h3><a class="toc-backref" href="#id6">Writing to external data</a><a class="headerlink" href="#writing-to-external-data" title="Permalink to this headline">¶</a></h3> <p>When your information is going to an external data source like writing to a file you need to decide whether to take in <tt class="xref py py-class docutils literal"><span class="pre">unicode</span></tt> strings or byte <tt class="xref py py-class docutils literal"><span class="pre">str</span></tt>. Remember that most external data sources are not going to be dealing with unicode directly. Instead, they’re going to be dealing with a sequence of bytes that may be interpreted as unicode. With that in mind, you either need to have the user give you a byte <tt class="xref py py-class docutils literal"><span class="pre">str</span></tt> or convert to a byte <tt class="xref py py-class docutils literal"><span class="pre">str</span></tt> inside the function.</p> <p>Next you need to think about the type of data that you’re receiving. If it’s textual data, (for instance, this is a chat client and the user is typing messages that they expect to be read by another person) it probably makes sense to take in <tt class="xref py py-class docutils literal"><span class="pre">unicode</span></tt> strings and do the conversion inside your function. On the other hand, if this is a lower level function that’s passing data into a network socket, it probably should be taking byte <tt class="xref py py-class docutils literal"><span class="pre">str</span></tt> instead.</p> <p>Just as noted in the API notes above, you should specify an <tt class="xref py py-attr docutils literal"><span class="pre">encoding</span></tt> and <tt class="xref py py-attr docutils literal"><span class="pre">errors</span></tt> argument if you need to transform from <tt class="xref py py-class docutils literal"><span class="pre">unicode</span></tt> string to byte <tt class="xref py py-class docutils literal"><span class="pre">str</span></tt> and you are unable to guess the encoding from the data itself.</p> </div> <div class="section" id="updating-data-structures"> <h3><a class="toc-backref" href="#id7">Updating data structures</a><a class="headerlink" href="#updating-data-structures" title="Permalink to this headline">¶</a></h3> <p>Sometimes your API is just going to update a data structure and not immediately output that data anywhere. Just as when writing external data, you should think about both what your function is going to do with the data eventually and what the caller of your function is thinking that they’re giving you. Most of the time, you’ll want to take <tt class="xref py py-class docutils literal"><span class="pre">unicode</span></tt> strings and enter them into the data structure as <tt class="xref py py-class docutils literal"><span class="pre">unicode</span></tt> when the data is textual in nature. You’ll want to take byte <tt class="xref py py-class docutils literal"><span class="pre">str</span></tt> and enter them into the data structure as byte <tt class="xref py py-class docutils literal"><span class="pre">str</span></tt> when the data is not text. Use a naming convention so the user knows what’s expected.</p> </div> </div> <div class="section" id="apis-to-avoid"> <h2><a class="toc-backref" href="#id8">APIs to Avoid</a><a class="headerlink" href="#apis-to-avoid" title="Permalink to this headline">¶</a></h2> <p>There are a few APIs that are just wrong. If you catch yourself making an API that does one of these things, change it before anyone sees your code.</p> <div class="section" id="returning-unicode-unless-a-conversion-fails"> <h3><a class="toc-backref" href="#id9">Returning unicode unless a conversion fails</a><a class="headerlink" href="#returning-unicode-unless-a-conversion-fails" title="Permalink to this headline">¶</a></h3> <p>This type of API usually deals with byte <tt class="xref py py-class docutils literal"><span class="pre">str</span></tt> at some point and converts it to <tt class="xref py py-class docutils literal"><span class="pre">unicode</span></tt> because it’s usually thought to be text. However, there are times when the bytes fail to convert to a <tt class="xref py py-class docutils literal"><span class="pre">unicode</span></tt> string. When that happens, this API returns the raw byte <tt class="xref py py-class docutils literal"><span class="pre">str</span></tt> instead of a <tt class="xref py py-class docutils literal"><span class="pre">unicode</span></tt> string. One example of this is present in the <a class="reference external" href="http://docs.python.org/library">python standard library</a>: python2’s <a class="reference external" href="http://docs.python.org/library/os.html#os.listdir" title="(in Python v2.7)"><tt class="xref py py-func docutils literal"><span class="pre">os.listdir()</span></tt></a>:</p> <div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="kn">import</span> <span class="nn">os</span> <span class="gp">>>> </span><span class="kn">import</span> <span class="nn">locale</span> <span class="gp">>>> </span><span class="n">locale</span><span class="o">.</span><span class="n">getpreferredencoding</span><span class="p">()</span> <span class="go">'UTF-8'</span> <span class="gp">>>> </span><span class="n">os</span><span class="o">.</span><span class="n">mkdir</span><span class="p">(</span><span class="s">'/tmp/mine'</span><span class="p">)</span> <span class="gp">>>> </span><span class="n">os</span><span class="o">.</span><span class="n">chdir</span><span class="p">(</span><span class="s">'/tmp/mine'</span><span class="p">)</span> <span class="gp">>>> </span><span class="nb">open</span><span class="p">(</span><span class="s">'nonsense_char_</span><span class="se">\xff</span><span class="s">'</span><span class="p">,</span> <span class="s">'w'</span><span class="p">)</span><span class="o">.</span><span class="n">close</span><span class="p">()</span> <span class="gp">>>> </span><span class="nb">open</span><span class="p">(</span><span class="s">'all_ascii'</span><span class="p">,</span> <span class="s">'w'</span><span class="p">)</span><span class="o">.</span><span class="n">close</span><span class="p">()</span> <span class="gp">>>> </span><span class="n">os</span><span class="o">.</span><span class="n">listdir</span><span class="p">(</span><span class="s">u'.'</span><span class="p">)</span> <span class="go">[u'all_ascii', 'nonsense_char_\xff']</span> </pre></div> </div> <p>The problem with APIs like this is that they cause failures that are hard to debug because they don’t happen where the variables are set. For instance, let’s say you take the filenames from <a class="reference external" href="http://docs.python.org/library/os.html#os.listdir" title="(in Python v2.7)"><tt class="xref py py-func docutils literal"><span class="pre">os.listdir()</span></tt></a> and give it to this function:</p> <div class="highlight-python"><div class="highlight"><pre><span class="k">def</span> <span class="nf">normalize_filename</span><span class="p">(</span><span class="n">filename</span><span class="p">):</span> <span class="sd">'''Change spaces and dashes into underscores'''</span> <span class="k">return</span> <span class="n">filename</span><span class="o">.</span><span class="n">translate</span><span class="p">({</span><span class="nb">ord</span><span class="p">(</span><span class="s">u' '</span><span class="p">):</span><span class="s">u'_'</span><span class="p">,</span> <span class="nb">ord</span><span class="p">(</span><span class="s">u' '</span><span class="p">):</span><span class="s">u'_'</span><span class="p">})</span> </pre></div> </div> <p>When you test this, you use filenames that all are decodable in your preferred encoding and everything seems to work. But when this code is run on a machine that has filenames in multiple encodings the filenames returned by <a class="reference external" href="http://docs.python.org/library/os.html#os.listdir" title="(in Python v2.7)"><tt class="xref py py-func docutils literal"><span class="pre">os.listdir()</span></tt></a> suddenly include byte <tt class="xref py py-class docutils literal"><span class="pre">str</span></tt>. And byte <tt class="xref py py-class docutils literal"><span class="pre">str</span></tt> has a different <a class="reference external" href="http://docs.python.org/library/string.html#string.translate" title="(in Python v2.7)"><tt class="xref py py-func docutils literal"><span class="pre">string.translate()</span></tt></a> function that takes different values. So the code raises an exception where it’s not immediately obvious that <a class="reference external" href="http://docs.python.org/library/os.html#os.listdir" title="(in Python v2.7)"><tt class="xref py py-func docutils literal"><span class="pre">os.listdir()</span></tt></a> is at fault.</p> </div> <div class="section" id="ignoring-values-with-no-chance-of-recovery"> <h3><a class="toc-backref" href="#id10">Ignoring values with no chance of recovery</a><a class="headerlink" href="#ignoring-values-with-no-chance-of-recovery" title="Permalink to this headline">¶</a></h3> <p>An early version of python3 attempted to fix the <a class="reference external" href="http://docs.python.org/library/os.html#os.listdir" title="(in Python v2.7)"><tt class="xref py py-func docutils literal"><span class="pre">os.listdir()</span></tt></a> problem pointed out in the last section by returning all values that were decodable to <tt class="xref py py-class docutils literal"><span class="pre">unicode</span></tt> and omitting the filenames that were not. This lead to the following output:</p> <div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="kn">import</span> <span class="nn">os</span> <span class="gp">>>> </span><span class="kn">import</span> <span class="nn">locale</span> <span class="gp">>>> </span><span class="n">locale</span><span class="o">.</span><span class="n">getpreferredencoding</span><span class="p">()</span> <span class="go">'UTF-8'</span> <span class="gp">>>> </span><span class="n">os</span><span class="o">.</span><span class="n">mkdir</span><span class="p">(</span><span class="s">'/tmp/mine'</span><span class="p">)</span> <span class="gp">>>> </span><span class="n">os</span><span class="o">.</span><span class="n">chdir</span><span class="p">(</span><span class="s">'/tmp/mine'</span><span class="p">)</span> <span class="gp">>>> </span><span class="nb">open</span><span class="p">(</span><span class="n">b</span><span class="s">'nonsense_char_</span><span class="se">\xff</span><span class="s">'</span><span class="p">,</span> <span class="s">'w'</span><span class="p">)</span><span class="o">.</span><span class="n">close</span><span class="p">()</span> <span class="gp">>>> </span><span class="nb">open</span><span class="p">(</span><span class="s">'all_ascii'</span><span class="p">,</span> <span class="s">'w'</span><span class="p">)</span><span class="o">.</span><span class="n">close</span><span class="p">()</span> <span class="gp">>>> </span><span class="n">os</span><span class="o">.</span><span class="n">listdir</span><span class="p">(</span><span class="s">'.'</span><span class="p">)</span> <span class="go">['all_ascii']</span> </pre></div> </div> <p>The issue with this type of code is that it is silently doing something surprising. The caller expects to get a full list of files back from <a class="reference external" href="http://docs.python.org/library/os.html#os.listdir" title="(in Python v2.7)"><tt class="xref py py-func docutils literal"><span class="pre">os.listdir()</span></tt></a>. Instead, it silently ignores some of the files, returning only a subset. This leads to code that doesn’t do what is expected that may go unnoticed until the code is in production and someone notices that something important is being missed.</p> </div> <div class="section" id="raising-a-unicodeexception-with-no-chance-of-recovery"> <h3><a class="toc-backref" href="#id11">Raising a UnicodeException with no chance of recovery</a><a class="headerlink" href="#raising-a-unicodeexception-with-no-chance-of-recovery" title="Permalink to this headline">¶</a></h3> <p>Believe it or not, a few libraries exist that make it impossible to deal with unicode text without raising a <tt class="xref py py-exc docutils literal"><span class="pre">UnicodeError</span></tt>. What seems to occur in these libraries is that the library has functions that expect to receive a <tt class="xref py py-class docutils literal"><span class="pre">unicode</span></tt> string. However, internally, those functions call other functions that expect to receive a byte <tt class="xref py py-class docutils literal"><span class="pre">str</span></tt>. The programmer of the API was smart enough to convert from a <tt class="xref py py-class docutils literal"><span class="pre">unicode</span></tt> string to a byte <tt class="xref py py-class docutils literal"><span class="pre">str</span></tt> but they did not give the user the chance to specify the encodings to use or how to deal with errors. This results in exceptions when the user passes in a byte <tt class="xref py py-class docutils literal"><span class="pre">str</span></tt> because the initial function wants a <tt class="xref py py-class docutils literal"><span class="pre">unicode</span></tt> string and exceptions when the user passes in a <tt class="xref py py-class docutils literal"><span class="pre">unicode</span></tt> string because the function can’t convert the string to bytes in the encoding that it’s selected.</p> <p>Do not put the user in the position of not being able to use your API without raising a <tt class="xref py py-exc docutils literal"><span class="pre">UnicodeError</span></tt> with certain values. If you can only safely take <tt class="xref py py-class docutils literal"><span class="pre">unicode</span></tt> strings, document that byte <tt class="xref py py-class docutils literal"><span class="pre">str</span></tt> is not allowed and vice versa. If you have to convert internally, make sure to give the caller of your function parameters to control the encoding and how to treat errors that may occur during the encoding/decoding process. If your code will raise a <tt class="xref py py-exc docutils literal"><span class="pre">UnicodeError</span></tt> with non-<a class="reference internal" href="glossary.html#term-ascii"><em class="xref std std-term">ASCII</em></a> values no matter what, you should probably rethink your API.</p> </div> </div> <div class="section" id="knowing-your-data"> <h2><a class="toc-backref" href="#id12">Knowing your data</a><a class="headerlink" href="#knowing-your-data" title="Permalink to this headline">¶</a></h2> <p>If you’ve read all the way down to this section without skipping you’ve seen several admonitions about the type of data you are processing affecting the viability of the various API choices.</p> <p>Here’s a few things to consider in your data:</p> <div class="section" id="do-you-need-to-operate-on-both-bytes-and-unicode"> <h3><a class="toc-backref" href="#id13">Do you need to operate on both bytes and unicode?</a><a class="headerlink" href="#do-you-need-to-operate-on-both-bytes-and-unicode" title="Permalink to this headline">¶</a></h3> <p>Much of the data in libraries, programs, and the general environment outside of python is written where strings are sequences of bytes. So when we interact with data that comes from outside of python or data that is about to leave python it may make sense to only operate on the data as a byte <tt class="xref py py-class docutils literal"><span class="pre">str</span></tt>. There’s two times when this may make sense:</p> <ol class="arabic simple"> <li>The user is intended to hand the data to the function and then the function takes care of sending the data outside of python (to the filesystem, over the network, etc).</li> <li>The data is not representable as text. For instance, writing a binary file format.</li> </ol> <p>Even when your code is operating in this area you still need to think a little more about your data. For instance, it might make sense for the person using your API to pass in <tt class="xref py py-class docutils literal"><span class="pre">unicode</span></tt> strings and let the function convert that into the byte <tt class="xref py py-class docutils literal"><span class="pre">str</span></tt> that it then sends over the wire.</p> <p>There are also times when it might make sense to operate only on <tt class="xref py py-class docutils literal"><span class="pre">unicode</span></tt> strings. <tt class="xref py py-class docutils literal"><span class="pre">unicode</span></tt> represents text so anytime that you are working on textual data that isn’t going to leave python it has the potential to be a <tt class="xref py py-class docutils literal"><span class="pre">unicode</span></tt>-only API. However, there’s two things that you should consider when designing a <tt class="xref py py-class docutils literal"><span class="pre">unicode</span></tt>-only API:</p> <ol class="arabic simple"> <li>As your API gains popularity, people are going to use your API in places that you may not have thought of. Corner cases in these other places may mean that processing bytes is desirable.</li> <li>In python2, byte <tt class="xref py py-class docutils literal"><span class="pre">str</span></tt> and <tt class="xref py py-class docutils literal"><span class="pre">unicode</span></tt> are often used interchangably with each other. That means that people programming against your API may have received <tt class="xref py py-class docutils literal"><span class="pre">str</span></tt> from some other API and it would be most convenient for their code if your API accepted it.</li> </ol> <div class="admonition note"> <p class="first admonition-title">Note</p> <p class="last">In python3, the separation between the text type and the byte type are more clear. So in python3, there’s less need to have all APIs take both unicode and bytes.</p> </div> </div> <div class="section" id="can-you-restrict-the-encodings"> <h3><a class="toc-backref" href="#id14">Can you restrict the encodings?</a><a class="headerlink" href="#can-you-restrict-the-encodings" title="Permalink to this headline">¶</a></h3> <p>If you determine that you have to deal with byte <tt class="xref py py-class docutils literal"><span class="pre">str</span></tt> you should realize that not all encodings are created equal. Each has different properties that may make it possible to provide a simpler API provided that you can reasonably tell the users of your API that they cannot use certain classes of encodings.</p> <p>As one example, if you are required to find a comma (<tt class="docutils literal"><span class="pre">,</span></tt>) in a byte <tt class="xref py py-class docutils literal"><span class="pre">str</span></tt> you have different choices based on what encodings are allowed. If you can reasonably restrict your API users to only giving <a class="reference internal" href="glossary.html#term-ascii-compatible"><em class="xref std std-term">ASCII compatible</em></a> encodings you can do this simply by searching for the literal comma character because that character will be represented by the same byte sequence in all <a class="reference internal" href="glossary.html#term-ascii-compatible"><em class="xref std std-term">ASCII compatible</em></a> encodings.</p> <p>The following are some classes of encodings to be aware of as you decide how generic your code needs to be.</p> <div class="section" id="single-byte-encodings"> <h4><a class="toc-backref" href="#id15">Single byte encodings</a><a class="headerlink" href="#single-byte-encodings" title="Permalink to this headline">¶</a></h4> <p>Single byte encodings can only represent 256 total characters. They encode the <a class="reference internal" href="glossary.html#term-code-points"><em class="xref std std-term">code points</em></a> for a character to the equivalent number in a single byte.</p> <p>Most single byte encodings are <a class="reference internal" href="glossary.html#term-ascii-compatible"><em class="xref std std-term">ASCII compatible</em></a>. <a class="reference internal" href="glossary.html#term-ascii-compatible"><em class="xref std std-term">ASCII compatible</em></a> encodings are the most likely to be usable without changes to code so this is good news. A notable exception to this is the <a class="reference external" href="http://en.wikipedia.org/wiki/Extended_Binary_Coded_Decimal_Interchange_Code">EBDIC</a> family of encodings.</p> </div> <div class="section" id="multibyte-encodings"> <h4><a class="toc-backref" href="#id16">Multibyte encodings</a><a class="headerlink" href="#multibyte-encodings" title="Permalink to this headline">¶</a></h4> <p>Multibyte encodings use more than one byte to encode some characters.</p> <div class="section" id="fixed-width"> <h5><a class="toc-backref" href="#id17">Fixed width</a><a class="headerlink" href="#fixed-width" title="Permalink to this headline">¶</a></h5> <p>Fixed width encodings have a set number of bytes to represent all of the characters in the character set. <tt class="docutils literal"><span class="pre">UTF-32</span></tt> is an example of a fixed width encoding that uses four bytes per character and can express every unicode characters. There are a number of problems with writing APIs that need to operate on fixed width, multibyte characters. To go back to our earlier example of finding a comma in a string, we have to realize that even in <tt class="docutils literal"><span class="pre">UTF-32</span></tt> where the <a class="reference internal" href="glossary.html#term-code-point"><em class="xref std std-term">code point</em></a> for <a class="reference internal" href="glossary.html#term-ascii"><em class="xref std std-term">ASCII</em></a> characters is the same as in <a class="reference internal" href="glossary.html#term-ascii"><em class="xref std std-term">ASCII</em></a>, the byte sequence for them is different. So you cannot search for the literal byte character as it may pick up false positives and may break a byte sequence in an odd place.</p> </div> <div class="section" id="variable-width"> <h5><a class="toc-backref" href="#id18">Variable Width</a><a class="headerlink" href="#variable-width" title="Permalink to this headline">¶</a></h5> <div class="section" id="ascii-compatible"> <h6><a class="toc-backref" href="#id19">ASCII compatible</a><a class="headerlink" href="#ascii-compatible" title="Permalink to this headline">¶</a></h6> <p><a class="reference internal" href="glossary.html#term-utf-8"><em class="xref std std-term">UTF-8</em></a> and the <a class="reference external" href="http://en.wikipedia.org/wiki/Extended_Unix_Code">EUC</a> family of encodings are examples of <a class="reference internal" href="glossary.html#term-ascii-compatible"><em class="xref std std-term">ASCII compatible</em></a> multi-byte encodings. They achieve this by adhering to two principles:</p> <ul class="simple"> <li>All of the <a class="reference internal" href="glossary.html#term-ascii"><em class="xref std std-term">ASCII</em></a> characters are represented by the byte that they are in the <a class="reference internal" href="glossary.html#term-ascii"><em class="xref std std-term">ASCII</em></a> encoding.</li> <li>None of the <a class="reference internal" href="glossary.html#term-ascii"><em class="xref std std-term">ASCII</em></a> byte sequences are reused in any other byte sequence for a different character.</li> </ul> </div> <div class="section" id="escaped"> <h6><a class="toc-backref" href="#id20">Escaped</a><a class="headerlink" href="#escaped" title="Permalink to this headline">¶</a></h6> <p>Some multibyte encodings work by using only bytes from the <a class="reference internal" href="glossary.html#term-ascii"><em class="xref std std-term">ASCII</em></a> encoding but when a particular sequence of those byes is found, they are interpreted as meaning something other than their <a class="reference internal" href="glossary.html#term-ascii"><em class="xref std std-term">ASCII</em></a> values. <tt class="docutils literal"><span class="pre">UTF-7</span></tt> is one such encoding that can encode all of the unicode <a class="reference internal" href="glossary.html#term-code-points"><em class="xref std std-term">code points</em></a>. For instance, here’s a some Japanese characters encoded as <tt class="docutils literal"><span class="pre">UTF-7</span></tt>:</p> <div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="n">a</span> <span class="o">=</span> <span class="s">u'</span><span class="se">\u304f\u3089\u3068\u307f</span><span class="s">'</span> <span class="gp">>>> </span><span class="k">print</span> <span class="n">a</span> <span class="go">くらとみ</span> <span class="gp">>>> </span><span class="k">print</span> <span class="n">a</span><span class="o">.</span><span class="n">encode</span><span class="p">(</span><span class="s">'utf-7'</span><span class="p">)</span> <span class="go">+ME8wiTBoMH8-</span> </pre></div> </div> <p>These encodings can be used when you need to encode unicode data that may contain non-<a class="reference internal" href="glossary.html#term-ascii"><em class="xref std std-term">ASCII</em></a> characters for inclusion in an <a class="reference internal" href="glossary.html#term-ascii"><em class="xref std std-term">ASCII</em></a> only transport medium or file.</p> <p>However, they are not <a class="reference internal" href="glossary.html#term-ascii-compatible"><em class="xref std std-term">ASCII compatible</em></a> in the sense that we used earlier as the bytes that represent a <a class="reference internal" href="glossary.html#term-ascii"><em class="xref std std-term">ASCII</em></a> character are being reused as part of other characters. If you were to search for a literal plus sign in this encoded string, you would run across many false positives, for instance.</p> </div> <div class="section" id="other"> <h6><a class="toc-backref" href="#id21">Other</a><a class="headerlink" href="#other" title="Permalink to this headline">¶</a></h6> <p>There are many other popular variable width encodings, for instance <tt class="docutils literal"><span class="pre">UTF-16</span></tt> and <tt class="docutils literal"><span class="pre">shift-JIS</span></tt>. Many of these are not <a class="reference internal" href="glossary.html#term-ascii-compatible"><em class="xref std std-term">ASCII compatible</em></a> so you cannot search for a literal <a class="reference internal" href="glossary.html#term-ascii"><em class="xref std std-term">ASCII</em></a> character without danger of false positives or false negatives.</p> </div> </div> </div> </div> </div> </div> </div> </div> </div> <div class="sphinxsidebar"> <div class="sphinxsidebarwrapper"> <h3><a href="index.html">Table Of Contents</a></h3> <ul> <li><a class="reference internal" href="#">Designing Unicode Aware APIs</a><ul> <li><a class="reference internal" href="#take-either-bytes-or-unicode-output-only-unicode">Take either bytes or unicode, output only unicode</a></li> <li><a class="reference internal" href="#take-either-bytes-or-unicode-output-the-same-type">Take either bytes or unicode, output the same type</a></li> <li><a class="reference internal" href="#separate-functions">Separate functions</a></li> <li><a class="reference internal" href="#deciding-whether-to-take-str-or-unicode-when-no-value-is-returned">Deciding whether to take str or unicode when no value is returned</a><ul> <li><a class="reference internal" href="#writing-to-external-data">Writing to external data</a></li> <li><a class="reference internal" href="#updating-data-structures">Updating data structures</a></li> </ul> </li> <li><a class="reference internal" href="#apis-to-avoid">APIs to Avoid</a><ul> <li><a class="reference internal" href="#returning-unicode-unless-a-conversion-fails">Returning unicode unless a conversion fails</a></li> <li><a class="reference internal" href="#ignoring-values-with-no-chance-of-recovery">Ignoring values with no chance of recovery</a></li> <li><a class="reference internal" href="#raising-a-unicodeexception-with-no-chance-of-recovery">Raising a UnicodeException with no chance of recovery</a></li> </ul> </li> <li><a class="reference internal" href="#knowing-your-data">Knowing your data</a><ul> <li><a class="reference internal" href="#do-you-need-to-operate-on-both-bytes-and-unicode">Do you need to operate on both bytes and unicode?</a></li> <li><a class="reference internal" href="#can-you-restrict-the-encodings">Can you restrict the encodings?</a><ul> <li><a class="reference internal" href="#single-byte-encodings">Single byte encodings</a></li> <li><a class="reference internal" href="#multibyte-encodings">Multibyte encodings</a><ul> <li><a class="reference internal" href="#fixed-width">Fixed width</a></li> <li><a class="reference internal" href="#variable-width">Variable Width</a><ul> <li><a class="reference internal" href="#ascii-compatible">ASCII compatible</a></li> <li><a class="reference internal" href="#escaped">Escaped</a></li> <li><a class="reference internal" href="#other">Other</a></li> </ul> </li> </ul> </li> </ul> </li> </ul> </li> </ul> </li> </ul> <h4>Previous topic</h4> <p class="topless"><a href="unicode-frustrations.html" title="previous chapter">Overcoming frustration: Correctly using unicode in python2</a></p> <h4>Next topic</h4> <p class="topless"><a href="api-overview.html" title="next chapter">Kitchen API</a></p> <h3>This Page</h3> <ul class="this-page-menu"> <li><a href="_sources/designing-unicode-apis.txt" rel="nofollow">Show Source</a></li> </ul> <div id="searchbox" style="display: none"> <h3>Quick search</h3> <form class="search" action="search.html" method="get"> <input type="text" name="q" /> <input type="submit" value="Go" /> <input type="hidden" name="check_keywords" value="yes" /> <input type="hidden" name="area" value="default" /> </form> <p class="searchtip" style="font-size: 90%"> Enter search terms or a module, class or function name. </p> </div> <script type="text/javascript">$('#searchbox').show(0);</script> </div> </div> <div class="clearer"></div> </div> <div class="related"> <h3>Navigation</h3> <ul> <li class="right" style="margin-right: 10px"> <a href="genindex.html" title="General Index" >index</a></li> <li class="right" > <a href="py-modindex.html" title="Python Module Index" >modules</a> |</li> <li class="right" > <a href="api-overview.html" title="Kitchen API" >next</a> |</li> <li class="right" > <a href="unicode-frustrations.html" title="Overcoming frustration: Correctly using unicode in python2" >previous</a> |</li> <li><a href="index.html">kitchen 1.1.1 documentation</a> »</li> <li><a href="tutorial.html" >Using kitchen to write good code</a> »</li> </ul> </div> <div class="footer"> © Copyright 2011 Red Hat, Inc. and others. Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.1.3. </div> </body> </html>