This file is indexed.

/usr/share/doc/python-kitchen-doc/html/designing-unicode-apis.html is in python-kitchen-doc 1.2.4-2.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
<!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" lang="en">
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    
    <title>Designing Unicode Aware APIs &#8212; kitchen 1.2.4 documentation</title>
    
    <link rel="stylesheet" href="_static/classic.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.2.4',
        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.2.4 documentation"
          href="_static/opensearch.xml"/>
    <link rel="top" title="kitchen 1.2.4 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 role="document">
    <div class="related" role="navigation" aria-label="related navigation">
      <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 class="nav-item nav-item-0"><a href="index.html">kitchen 1.2.4 documentation</a> &#187;</li>
          <li class="nav-item nav-item-1"><a href="tutorial.html" accesskey="U">Using kitchen to write good code</a> &#187;</li> 
      </ul>
    </div>  

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <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 <code class="xref py py-class docutils literal"><span class="pre">str</span></code> and <code class="xref py py-class docutils literal"><span class="pre">unicode</span></code> 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 <code class="xref py py-class docutils literal"><span class="pre">unicode</span></code> strings
or byte <code class="xref py py-class docutils literal"><span class="pre">str</span></code> but what you give back is always <code class="xref py py-class docutils literal"><span class="pre">unicode</span></code>.  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"><span class="xref std std-term">ASCII</span></a>-only data but fails when given data that contains
non-<a class="reference internal" href="glossary.html#term-ascii"><span class="xref std std-term">ASCII</span></a> characters.  Worse, if your API is not designed to be
flexible, the consumer of your code won&#8217;t be able to easily correct those
problems once they find them.</p>
<p>Here&#8217;s a good API that uses this strategy:</p>
<div class="highlight-python"><div class="highlight"><pre><span></span><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="s1">&#39;utf8&#39;</span><span class="p">,</span> <span class="n">errors</span><span class="o">=</span><span class="s1">&#39;replace&#39;</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 <code class="xref py py-func docutils literal"><span class="pre">truncate()</span></code> 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 <code class="xref py py-class docutils literal"><span class="pre">str</span></code> to <code class="xref py py-class docutils literal"><span class="pre">unicode</span></code>
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, <code class="docutils literal"><span class="pre">errors='replace'</span></code> is
a good default.  If you are constructing keys to a database, raisng an
exception (with <code class="docutils literal"><span class="pre">errors='strict'</span></code>) 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 <code class="xref py py-class docutils literal"><span class="pre">str</span></code> to <code class="xref py py-class docutils literal"><span class="pre">unicode</span></code> string is going to
occur.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p>If you&#8217;re targeting python-3.1 and above, <code class="docutils literal"><span class="pre">errors='surrogateescape'</span></code> may
be a better default than <code class="docutils literal"><span class="pre">errors='strict'</span></code>.  You need to be mindful of
a few things when using <code class="docutils literal"><span class="pre">surrogateescape</span></code> though:</p>
<ul class="simple">
<li><code class="docutils literal"><span class="pre">surrogateescape</span></code> will cause issues if a non-<a class="reference internal" href="glossary.html#term-ascii"><span class="xref std std-term">ASCII</span></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="https://www.python.org/dev/peps/pep-0383"><strong>PEP 383</strong></a> mentions that <code class="docutils literal"><span class="pre">surrogateescape</span></code> was
specifically designed with the limitations of translating using system
locales (where <a class="reference internal" href="glossary.html#term-ascii"><span class="xref std std-term">ASCII</span></a> compatibility is generally seen as
inescapable) so you should keep that in mind.</li>
<li>If you use <code class="docutils literal"><span class="pre">surrogateescape</span></code> to decode from <code class="xref py py-class docutils literal"><span class="pre">bytes</span></code>
to <code class="xref py py-class docutils literal"><span class="pre">unicode</span></code> you will need to use an error handler other than
<code class="docutils literal"><span class="pre">strict</span></code> 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 <code class="docutils literal"><span class="pre">surrogateescape</span></code> 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&#8217;s a bad example of using this strategy:</p>
<div class="highlight-python"><div class="highlight"><pre><span></span><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&#8217;t have the optional keyword arguments for
<code class="xref py py-attr docutils literal"><span class="pre">encoding</span></code> and <code class="xref py py-attr docutils literal"><span class="pre">errors</span></code>.  A user who uses this function is more
likely to miss the fact that a conversion from byte <code class="xref py py-class docutils literal"><span class="pre">str</span></code> to
<code class="xref py py-class docutils literal"><span class="pre">unicode</span></code> 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 <code class="xref py py-class docutils literal"><span class="pre">unicode</span></code> 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></span><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="s1">&#39;euc_jp&#39;</span><span class="p">,</span> <span class="n">errors</span><span class="o">=</span><span class="s1">&#39;ignore&#39;</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 <code class="xref py py-class docutils literal"><span class="pre">str</span></code> to process, you return a byte
<code class="xref py py-class docutils literal"><span class="pre">str</span></code> in your output.  When you are given <code class="xref py py-class docutils literal"><span class="pre">unicode</span></code> strings to
process, you return <code class="xref py py-class docutils literal"><span class="pre">unicode</span></code> 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&#8217;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 <code class="xref py py-class docutils literal"><span class="pre">str</span></code> is known or can be
discovered based on the input data this works well.  If you can&#8217;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 <code class="xref py py-class docutils literal"><span class="pre">str</span></code> and
<code class="xref py py-class docutils literal"><span class="pre">unicode</span></code> string.</li>
<li>It cannot return the same data as either a <code class="xref py py-class docutils literal"><span class="pre">unicode</span></code> string or byte
<code class="xref py py-class docutils literal"><span class="pre">str</span></code>.</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"><span class="xref std std-term">ASCII</span></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></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="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="s1">&#39;&#39;</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&#8217;t have any characters to encode) come from outside of
the function.  Due to that, the user is responsible for making sure that the
<code class="xref py py-attr docutils literal"><span class="pre">msg</span></code>, and the keys and values in <code class="xref py py-attr docutils literal"><span class="pre">table</span></code> all match in terms of
type (<code class="xref py py-class docutils literal"><span class="pre">unicode</span></code> vs <code class="xref py py-class docutils literal"><span class="pre">str</span></code>) and encoding (You can do some error
checking to make sure the user gave all the same type but you can&#8217;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"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">json</span>
<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="p">,</span> <span class="n">to_bytes</span>

<span class="k">def</span> <span class="nf">first_field_from_json_data</span><span class="p">(</span><span class="n">json_string</span><span class="p">):</span>
    <span class="sd">&#39;&#39;&#39;Return the first field in a json data structure.</span>

<span class="sd">    The format of the json data is a simple list of strings.</span>
<span class="sd">    &#39;[&quot;one&quot;, &quot;two&quot;, &quot;three&quot;]&#39;</span>
<span class="sd">    &#39;&#39;&#39;</span>
    <span class="k">if</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">json_string</span><span class="p">,</span> <span class="nb">unicode</span><span class="p">):</span>
        <span class="c1"># On all python versions, json.loads() returns unicode if given</span>
        <span class="c1"># a unicode string</span>
        <span class="k">return</span> <span class="n">json</span><span class="o">.</span><span class="n">loads</span><span class="p">(</span><span class="n">json_string</span><span class="p">)[</span><span class="mi">0</span><span class="p">]</span>

    <span class="c1"># Byte str: figure out which encoding we&#39;re dealing with</span>
    <span class="k">if</span> <span class="s1">&#39;</span><span class="se">\x00</span><span class="s1">&#39;</span> <span class="ow">not</span> <span class="ow">in</span> <span class="n">json_data</span><span class="p">[:</span><span class="mi">2</span><span class="p">]</span>
        <span class="n">encoding</span> <span class="o">=</span> <span class="s1">&#39;utf8&#39;</span>
    <span class="k">elif</span> <span class="s1">&#39;</span><span class="se">\x00\x00\x00</span><span class="s1">&#39;</span> <span class="o">==</span> <span class="n">json_data</span><span class="p">[:</span><span class="mi">3</span><span class="p">]:</span>
        <span class="n">encoding</span> <span class="o">=</span> <span class="s1">&#39;utf-32-be&#39;</span>
    <span class="k">elif</span> <span class="s1">&#39;</span><span class="se">\x00\x00\x00</span><span class="s1">&#39;</span> <span class="o">==</span> <span class="n">json_data</span><span class="p">[</span><span class="mi">1</span><span class="p">:</span><span class="mi">4</span><span class="p">]:</span>
        <span class="n">encoding</span> <span class="o">=</span> <span class="s1">&#39;utf-32-le&#39;</span>
    <span class="k">elif</span> <span class="s1">&#39;</span><span class="se">\x00</span><span class="s1">&#39;</span> <span class="o">==</span> <span class="n">json_data</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span> <span class="ow">and</span> <span class="s1">&#39;</span><span class="se">\x00</span><span class="s1">&#39;</span> <span class="o">==</span> <span class="n">json_data</span><span class="p">[</span><span class="mi">2</span><span class="p">]:</span>
        <span class="n">encoding</span> <span class="o">=</span> <span class="s1">&#39;utf-16-be&#39;</span>
    <span class="k">else</span><span class="p">:</span>
        <span class="n">encoding</span> <span class="o">=</span> <span class="s1">&#39;utf-16-le&#39;</span>

    <span class="n">data</span> <span class="o">=</span> <span class="n">json</span><span class="o">.</span><span class="n">loads</span><span class="p">(</span><span class="nb">unicode</span><span class="p">(</span><span class="n">json_string</span><span class="p">,</span> <span class="n">encoding</span><span class="p">))</span>
    <span class="k">return</span> <span class="n">data</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span><span class="o">.</span><span class="n">encode</span><span class="p">(</span><span class="n">encoding</span><span class="p">)</span>
</pre></div>
</div>
<p>In this example the function takes either a byte <code class="xref py py-class docutils literal"><span class="pre">str</span></code> type or
a <code class="xref py py-class docutils literal"><span class="pre">unicode</span></code> 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 <code class="xref py py-class docutils literal"><span class="pre">unicode</span></code> 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 <code class="xref py py-class docutils literal"><span class="pre">str</span></code> 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&#8217;t do that, we wouldn&#8217;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 <code class="xref py py-class docutils literal"><span class="pre">str</span></code>.
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"><span class="xref std std-term">UTF-8</span></a>.  It further
defines the format such that the first two characters are always
<a class="reference internal" href="glossary.html#term-ascii"><span class="xref std std-term">ASCII</span></a>.  Each of these has a different sequence of NULLs when they
encode an <a class="reference internal" href="glossary.html#term-ascii"><span class="xref std std-term">ASCII</span></a> character.  We can use that to detect which encoding
was used to create the byte <code class="xref py py-class docutils literal"><span class="pre">str</span></code>.</p>
<p>Finally, we return the byte <code class="xref py py-class docutils literal"><span class="pre">str</span></code> by encoding the <code class="xref py py-class docutils literal"><span class="pre">unicode</span></code> back
to a byte <code class="xref py py-class docutils literal"><span class="pre">str</span></code>.</p>
<p>As you can see, in this example we have to convert from byte <code class="xref py py-class docutils literal"><span class="pre">str</span></code> to
<code class="xref py py-class docutils literal"><span class="pre">unicode</span></code> and back.  But we know from the json specification that byte
<code class="xref py py-class docutils literal"><span class="pre">str</span></code> 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></span><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">&#39;&#39;&#39;Return the first character in a string&#39;&#39;&#39;</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="s1">&#39;utf8&#39;</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="s1">&#39;latin1&#39;</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="s1">&#39;NFC&#39;</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&#8217;s something fragile and prone to
breaking in the <code class="docutils literal"><span class="pre">try:</span> <span class="pre">except:</span></code> block you are correct in being suspicious.
This code will fail on multi-byte character sets that aren&#8217;t <a class="reference internal" href="glossary.html#term-utf-8"><span class="xref std std-term">UTF-8</span></a>.  It
can also fail on data where the sequence of bytes is valid <a class="reference internal" href="glossary.html#term-utf-8"><span class="xref std std-term">UTF-8</span></a> but
the bytes are actually of a different encoding.  The reasons this code fails
is that we don&#8217;t know what encoding the bytes are in and the code must convert
from a byte <code class="xref py py-class docutils literal"><span class="pre">str</span></code> to a <code class="xref py py-class docutils literal"><span class="pre">unicode</span></code> string in order to function.</p>
<p>In order to make this code robust we must know the encoding of <code class="xref py py-attr docutils literal"><span class="pre">msg</span></code>.
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></span><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="s1">&#39;utf8&#39;</span><span class="p">,</span> <span class="n">errors</span><span class="o">=</span><span class="s1">&#39;strict&#39;</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="s1">&#39;NFC&#39;</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></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">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="c1"># 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="c1"># 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 <code class="xref py py-class docutils literal"><span class="pre">unicode</span></code> without knowing more
about the encoding of each of the filenames involved.  Since each filename
could have a different encoding there&#8217;s a few different options to pursue.  We
could make this function always return byte <code class="xref py py-class docutils literal"><span class="pre">str</span></code> since that can
accurately represent anything that could be returned.  If we want to return
<code class="xref py py-class docutils literal"><span class="pre">unicode</span></code> we need to at least allow the user to specify what to do in
case of an error decoding the bytes to <code class="xref py py-class docutils literal"><span class="pre">unicode</span></code>.  We can also let the
user specify the encoding to use for doing the decoding but that won&#8217;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></span><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="s1">&#39;strict&#39;</span><span class="p">):</span>
    <span class="c1"># 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 <code class="xref py py-attr docutils literal"><span class="pre">errors</span></code> in this example as what to pass to
the codec that decodes to <code class="xref py py-class docutils literal"><span class="pre">unicode</span></code> we could also have an
<code class="xref py py-attr docutils literal"><span class="pre">errors</span></code> argument that decides other things to do like skip a filename
entirely, return a placeholder (<code class="docutils literal"><span class="pre">Nondisplayable</span> <span class="pre">filename</span></code>), 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></span><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">&#39;&#39;&#39;Return the first field in a comma separated values string.&#39;&#39;&#39;</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="s1">&#39;,&#39;</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 <code class="xref py py-class docutils literal"><span class="pre">str</span></code> but not all encodings will use
the same sequence of bytes to represent the comma.  If you use an encoding
that&#8217;s not <a class="reference internal" href="glossary.html#term-ascii"><span class="xref std std-term">ASCII</span></a> compatible on the byte level, then the literal comma
<code class="docutils literal"><span class="pre">','</span></code> 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"><span class="xref std std-term">ASCII</span></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&#8217;t clearly document for the API user that
the reason they must give it is to properly match the encoding of the
<code class="xref py py-attr docutils literal"><span class="pre">csv_string</span></code>.  They&#8217;re just as likely to think that it&#8217;s simply a way
to specify an alternate character (like &#8221;:&#8221; or &#8220;|&#8221;) for the separator.</p>
</li>
<li><p class="first">It&#8217;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"><span class="xref std std-term">UTF-8</span></a> is resistant to this as any character&#8217;s sequence of
bytes will never be a subset of another character&#8217;s sequence of bytes.</p>
</div>
</li>
</ol>
<p>With that in mind, here&#8217;s how to improve the API:</p>
<div class="highlight-python"><div class="highlight"><pre><span></span><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="s1">&#39;utf-8&#39;</span><span class="p">,</span> <span class="n">errors</span><span class="o">=</span><span class="s1">&#39;replace&#39;</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="s1">u&#39;,&#39;</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&#8217;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></span><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="s1">&#39;utf-8&#39;</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="s1">&#39;,&#39;</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 <code class="xref py py-class docutils literal"><span class="pre">str</span></code> or
<code class="xref py py-class docutils literal"><span class="pre">unicode</span></code> 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 <code class="xref py py-class docutils literal"><span class="pre">str</span></code> and the other is for
working with <code class="xref py py-class docutils literal"><span class="pre">unicode</span></code> strings:</p>
<div class="highlight-python"><div class="highlight"><pre><span></span><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">&#39;&#39;&#39;Replace values in str with other byte values like unicode.translate&#39;&#39;&#39;</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="s1">&#39;msg must be of type str&#39;</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">&gt;</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="s1">&#39;Keys in table must not exceed 255)&#39;</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">&gt;</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="s1">&#39;table values cannot be more than 255 or less than 0&#39;</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="s1">&#39;character mapping must return integer, None or str&#39;</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="s1">&#39;&#39;</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="s1">&#39;&#39;</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">&#39;&#39;&#39;Replace values in a unicode string with other values&#39;&#39;&#39;</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="s1">&#39;msg must be of type unicode&#39;</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&#8217;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 <code class="xref py py-class docutils literal"><span class="pre">str</span></code> and <code class="xref py py-class docutils literal"><span class="pre">unicode</span></code> 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
<code class="xref py py-class docutils literal"><span class="pre">str</span></code>, <code class="xref py py-class docutils literal"><span class="pre">unicode</span></code> string, or both.  The answer depends on your
use case but I&#8217;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 <code class="xref py py-class docutils literal"><span class="pre">unicode</span></code> strings or byte
<code class="xref py py-class docutils literal"><span class="pre">str</span></code>.  Remember that most external data sources are not going to be
dealing with unicode directly.  Instead, they&#8217;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 <code class="xref py py-class docutils literal"><span class="pre">str</span></code> or convert to
a byte <code class="xref py py-class docutils literal"><span class="pre">str</span></code> inside the function.</p>
<p>Next you need to think about the type of data that you&#8217;re receiving.  If it&#8217;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 <code class="xref py py-class docutils literal"><span class="pre">unicode</span></code> strings and do the conversion inside your function.
On the other hand, if this is a lower level function that&#8217;s passing data into
a network socket, it probably should be taking byte <code class="xref py py-class docutils literal"><span class="pre">str</span></code> instead.</p>
<p>Just as noted in the API notes above, you should specify an <code class="xref py py-attr docutils literal"><span class="pre">encoding</span></code>
and <code class="xref py py-attr docutils literal"><span class="pre">errors</span></code> argument if you need to transform from <code class="xref py py-class docutils literal"><span class="pre">unicode</span></code>
string to byte <code class="xref py py-class docutils literal"><span class="pre">str</span></code> 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&#8217;re
giving you.  Most of the time, you&#8217;ll want to take <code class="xref py py-class docutils literal"><span class="pre">unicode</span></code> strings
and enter them into the data structure as <code class="xref py py-class docutils literal"><span class="pre">unicode</span></code> when the data is
textual in nature.  You&#8217;ll want to take byte <code class="xref py py-class docutils literal"><span class="pre">str</span></code> and enter them into
the data structure as byte <code class="xref py py-class docutils literal"><span class="pre">str</span></code> when the data is not text.  Use
a naming convention so the user knows what&#8217;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 <code class="xref py py-class docutils literal"><span class="pre">str</span></code> at some point and
converts it to <code class="xref py py-class docutils literal"><span class="pre">unicode</span></code> because it&#8217;s usually thought to be text.
However, there are times when the bytes fail to convert to a <code class="xref py py-class docutils literal"><span class="pre">unicode</span></code>
string.  When that happens, this API returns the raw byte <code class="xref py py-class docutils literal"><span class="pre">str</span></code> instead
of a <code class="xref py py-class docutils literal"><span class="pre">unicode</span></code> string.  One example of this is present in the <a class="reference external" href="http://docs.python.org/library">python standard library</a>:
python2&#8217;s <code class="xref py py-func docutils literal"><span class="pre">os.listdir()</span></code>:</p>
<div class="highlight-python"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">os</span>
<span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">locale</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">locale</span><span class="o">.</span><span class="n">getpreferredencoding</span><span class="p">()</span>
<span class="go">&#39;UTF-8&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">os</span><span class="o">.</span><span class="n">mkdir</span><span class="p">(</span><span class="s1">&#39;/tmp/mine&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">os</span><span class="o">.</span><span class="n">chdir</span><span class="p">(</span><span class="s1">&#39;/tmp/mine&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">open</span><span class="p">(</span><span class="s1">&#39;nonsense_char_</span><span class="se">\xff</span><span class="s1">&#39;</span><span class="p">,</span> <span class="s1">&#39;w&#39;</span><span class="p">)</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">open</span><span class="p">(</span><span class="s1">&#39;all_ascii&#39;</span><span class="p">,</span> <span class="s1">&#39;w&#39;</span><span class="p">)</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">os</span><span class="o">.</span><span class="n">listdir</span><span class="p">(</span><span class="s1">u&#39;.&#39;</span><span class="p">)</span>
<span class="go">[u&#39;all_ascii&#39;, &#39;nonsense_char_\xff&#39;]</span>
</pre></div>
</div>
<p>The problem with APIs like this is that they cause failures that are hard to
debug because they don&#8217;t happen where the variables are set.  For instance,
let&#8217;s say you take the filenames from <code class="xref py py-func docutils literal"><span class="pre">os.listdir()</span></code> and give it to this
function:</p>
<div class="highlight-python"><div class="highlight"><pre><span></span><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">&#39;&#39;&#39;Change spaces and dashes into underscores&#39;&#39;&#39;</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="s1">u&#39; &#39;</span><span class="p">):</span><span class="s1">u&#39;_&#39;</span><span class="p">,</span> <span class="nb">ord</span><span class="p">(</span><span class="s1">u&#39; &#39;</span><span class="p">):</span><span class="s1">u&#39;_&#39;</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
<code class="xref py py-func docutils literal"><span class="pre">os.listdir()</span></code> suddenly include byte <code class="xref py py-class docutils literal"><span class="pre">str</span></code>.  And byte <code class="xref py py-class docutils literal"><span class="pre">str</span></code>
has a different <code class="xref py py-func docutils literal"><span class="pre">string.translate()</span></code> function that takes different values.
So the code raises an exception where it&#8217;s not immediately obvious that
<code class="xref py py-func docutils literal"><span class="pre">os.listdir()</span></code> 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 <code class="xref py py-func docutils literal"><span class="pre">os.listdir()</span></code> problem
pointed out in the last section by returning all values that were decodable to
<code class="xref py py-class docutils literal"><span class="pre">unicode</span></code> and omitting the filenames that were not.  This lead to the
following output:</p>
<div class="highlight-python"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">os</span>
<span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">locale</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">locale</span><span class="o">.</span><span class="n">getpreferredencoding</span><span class="p">()</span>
<span class="go">&#39;UTF-8&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">os</span><span class="o">.</span><span class="n">mkdir</span><span class="p">(</span><span class="s1">&#39;/tmp/mine&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">os</span><span class="o">.</span><span class="n">chdir</span><span class="p">(</span><span class="s1">&#39;/tmp/mine&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">open</span><span class="p">(</span><span class="n">b</span><span class="s1">&#39;nonsense_char_</span><span class="se">\xff</span><span class="s1">&#39;</span><span class="p">,</span> <span class="s1">&#39;w&#39;</span><span class="p">)</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">open</span><span class="p">(</span><span class="s1">&#39;all_ascii&#39;</span><span class="p">,</span> <span class="s1">&#39;w&#39;</span><span class="p">)</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">os</span><span class="o">.</span><span class="n">listdir</span><span class="p">(</span><span class="s1">&#39;.&#39;</span><span class="p">)</span>
<span class="go">[&#39;all_ascii&#39;]</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
<code class="xref py py-func docutils literal"><span class="pre">os.listdir()</span></code>.  Instead, it silently ignores some of the files, returning
only a subset.  This leads to code that doesn&#8217;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 <code class="xref py py-exc docutils literal"><span class="pre">UnicodeError</span></code>.  What seems to occur
in these libraries is that the library has functions that expect to receive
a <code class="xref py py-class docutils literal"><span class="pre">unicode</span></code> string.  However, internally, those functions call other
functions that expect to receive a byte <code class="xref py py-class docutils literal"><span class="pre">str</span></code>.  The programmer of the
API was smart enough to convert from a <code class="xref py py-class docutils literal"><span class="pre">unicode</span></code> string to a byte
<code class="xref py py-class docutils literal"><span class="pre">str</span></code> 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 <code class="xref py py-class docutils literal"><span class="pre">str</span></code> because the initial function wants
a <code class="xref py py-class docutils literal"><span class="pre">unicode</span></code> string and exceptions when the user passes in
a <code class="xref py py-class docutils literal"><span class="pre">unicode</span></code> string because the function can&#8217;t convert the string to
bytes in the encoding that it&#8217;s selected.</p>
<p>Do not put the user in the position of not being able to use your API without
raising a <code class="xref py py-exc docutils literal"><span class="pre">UnicodeError</span></code> with certain values.  If you can only safely
take <code class="xref py py-class docutils literal"><span class="pre">unicode</span></code> strings, document that byte <code class="xref py py-class docutils literal"><span class="pre">str</span></code> 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 <code class="xref py py-exc docutils literal"><span class="pre">UnicodeError</span></code> with non-<a class="reference internal" href="glossary.html#term-ascii"><span class="xref std std-term">ASCII</span></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&#8217;ve read all the way down to this section without skipping you&#8217;ve seen
several admonitions about the type of data you are processing affecting the
viability of the various API choices.</p>
<p>Here&#8217;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
<code class="xref py py-class docutils literal"><span class="pre">str</span></code>.  There&#8217;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 <code class="xref py py-class docutils literal"><span class="pre">unicode</span></code> strings and let the function convert that
into the byte <code class="xref py py-class docutils literal"><span class="pre">str</span></code> that it then sends over the wire.</p>
<p>There are also times when it might make sense to operate only on
<code class="xref py py-class docutils literal"><span class="pre">unicode</span></code> strings.  <code class="xref py py-class docutils literal"><span class="pre">unicode</span></code> represents text so anytime that
you are working on textual data that isn&#8217;t going to leave python it has the
potential to be a <code class="xref py py-class docutils literal"><span class="pre">unicode</span></code>-only API.  However, there&#8217;s two things that
you should consider when designing a <code class="xref py py-class docutils literal"><span class="pre">unicode</span></code>-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 <code class="xref py py-class docutils literal"><span class="pre">str</span></code> and <code class="xref py py-class docutils literal"><span class="pre">unicode</span></code> are often used
interchangeably with each other.  That means that people programming against
your API may have received <code class="xref py py-class docutils literal"><span class="pre">str</span></code> 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&#8217;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 <code class="xref py py-class docutils literal"><span class="pre">str</span></code> 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 (<code class="docutils literal"><span class="pre">,</span></code>) in a byte
<code class="xref py py-class docutils literal"><span class="pre">str</span></code> 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"><span class="xref std std-term">ASCII
compatible</span></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"><span class="xref std std-term">ASCII compatible</span></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"><span class="xref std std-term">code points</span></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"><span class="xref std std-term">ASCII compatible</span></a>.  <a class="reference internal" href="glossary.html#term-ascii-compatible"><span class="xref std std-term">ASCII
compatible</span></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.  <code class="docutils literal"><span class="pre">UTF-32</span></code> 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
<code class="docutils literal"><span class="pre">UTF-32</span></code> where the <a class="reference internal" href="glossary.html#term-code-point"><span class="xref std std-term">code point</span></a> for <a class="reference internal" href="glossary.html#term-ascii"><span class="xref std std-term">ASCII</span></a> characters is the
same as in <a class="reference internal" href="glossary.html#term-ascii"><span class="xref std std-term">ASCII</span></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"><span class="xref std std-term">UTF-8</span></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"><span class="xref std std-term">ASCII compatible</span></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"><span class="xref std std-term">ASCII</span></a> characters are represented by the byte that they
are in the <a class="reference internal" href="glossary.html#term-ascii"><span class="xref std std-term">ASCII</span></a> encoding.</li>
<li>None of the <a class="reference internal" href="glossary.html#term-ascii"><span class="xref std std-term">ASCII</span></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"><span class="xref std std-term">ASCII</span></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"><span class="xref std std-term">ASCII</span></a> values.
<code class="docutils literal"><span class="pre">UTF-7</span></code> is one such encoding that can encode all of the unicode
<a class="reference internal" href="glossary.html#term-code-points"><span class="xref std std-term">code points</span></a>.  For instance, here&#8217;s a some Japanese characters encoded as
<code class="docutils literal"><span class="pre">UTF-7</span></code>:</p>
<div class="highlight-python"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">a</span> <span class="o">=</span> <span class="s1">u&#39;</span><span class="se">\u304f\u3089\u3068\u307f</span><span class="s1">&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">print</span> <span class="n">a</span>
<span class="go">くらとみ</span>
<span class="gp">&gt;&gt;&gt; </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="s1">&#39;utf-7&#39;</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"><span class="xref std std-term">ASCII</span></a> characters for inclusion in an <a class="reference internal" href="glossary.html#term-ascii"><span class="xref std std-term">ASCII</span></a> only
transport medium or file.</p>
<p>However, they are not <a class="reference internal" href="glossary.html#term-ascii-compatible"><span class="xref std std-term">ASCII compatible</span></a> in the sense that we used
earlier as the bytes that represent a <a class="reference internal" href="glossary.html#term-ascii"><span class="xref std std-term">ASCII</span></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 <code class="docutils literal"><span class="pre">UTF-16</span></code>
and <code class="docutils literal"><span class="pre">shift-JIS</span></code>.  Many of these are not <a class="reference internal" href="glossary.html#term-ascii-compatible"><span class="xref std std-term">ASCII compatible</span></a> so you
cannot search for a literal <a class="reference internal" href="glossary.html#term-ascii"><span class="xref std std-term">ASCII</span></a> character without danger of false
positives or false negatives.</p>
</div>
</div>
</div>
</div>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <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>
  <div role="note" aria-label="source link">
    <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>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <form class="search" action="search.html" method="get">
      <div><input type="text" name="q" /></div>
      <div><input type="submit" value="Go" /></div>
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>
    <div class="related" role="navigation" aria-label="related navigation">
      <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 class="nav-item nav-item-0"><a href="index.html">kitchen 1.2.4 documentation</a> &#187;</li>
          <li class="nav-item nav-item-1"><a href="tutorial.html" >Using kitchen to write good code</a> &#187;</li> 
      </ul>
    </div>
    <div class="footer" role="contentinfo">
        &#169; Copyright 2016 Red Hat, Inc. and others.
      Created using <a href="http://sphinx-doc.org/">Sphinx</a> 1.4.6.
    </div>
  </body>
</html>