Update to 2.7.3
[profile/ivi/python.git] / Doc / library / codecs.rst
1
2 :mod:`codecs` --- Codec registry and base classes
3 =================================================
4
5 .. module:: codecs
6    :synopsis: Encode and decode data and streams.
7 .. moduleauthor:: Marc-Andre Lemburg <mal@lemburg.com>
8 .. sectionauthor:: Marc-Andre Lemburg <mal@lemburg.com>
9 .. sectionauthor:: Martin v. Löwis <martin@v.loewis.de>
10
11
12 .. index::
13    single: Unicode
14    single: Codecs
15    pair: Codecs; encode
16    pair: Codecs; decode
17    single: streams
18    pair: stackable; streams
19
20 This module defines base classes for standard Python codecs (encoders and
21 decoders) and provides access to the internal Python codec registry which
22 manages the codec and error handling lookup process.
23
24 It defines the following functions:
25
26
27 .. function:: register(search_function)
28
29    Register a codec search function. Search functions are expected to take one
30    argument, the encoding name in all lower case letters, and return a
31    :class:`CodecInfo` object having the following attributes:
32
33    * ``name`` The name of the encoding;
34
35    * ``encode`` The stateless encoding function;
36
37    * ``decode`` The stateless decoding function;
38
39    * ``incrementalencoder`` An incremental encoder class or factory function;
40
41    * ``incrementaldecoder`` An incremental decoder class or factory function;
42
43    * ``streamwriter`` A stream writer class or factory function;
44
45    * ``streamreader`` A stream reader class or factory function.
46
47    The various functions or classes take the following arguments:
48
49    *encode* and *decode*: These must be functions or methods which have the same
50    interface as the :meth:`encode`/:meth:`decode` methods of Codec instances (see
51    Codec Interface). The functions/methods are expected to work in a stateless
52    mode.
53
54    *incrementalencoder* and *incrementaldecoder*: These have to be factory
55    functions providing the following interface:
56
57       ``factory(errors='strict')``
58
59    The factory functions must return objects providing the interfaces defined by
60    the base classes :class:`IncrementalEncoder` and :class:`IncrementalDecoder`,
61    respectively. Incremental codecs can maintain state.
62
63    *streamreader* and *streamwriter*: These have to be factory functions providing
64    the following interface:
65
66       ``factory(stream, errors='strict')``
67
68    The factory functions must return objects providing the interfaces defined by
69    the base classes :class:`StreamWriter` and :class:`StreamReader`, respectively.
70    Stream codecs can maintain state.
71
72    Possible values for errors are
73
74    * ``'strict'``: raise an exception in case of an encoding error
75    * ``'replace'``: replace malformed data with a suitable replacement marker,
76      such as ``'?'`` or ``'\ufffd'``
77    * ``'ignore'``: ignore malformed data and continue without further notice
78    * ``'xmlcharrefreplace'``: replace with the appropriate XML character
79      reference (for encoding only)
80    * ``'backslashreplace'``: replace with backslashed escape sequences (for
81      encoding only)
82
83    as well as any other error handling name defined via :func:`register_error`.
84
85    In case a search function cannot find a given encoding, it should return
86    ``None``.
87
88
89 .. function:: lookup(encoding)
90
91    Looks up the codec info in the Python codec registry and returns a
92    :class:`CodecInfo` object as defined above.
93
94    Encodings are first looked up in the registry's cache. If not found, the list of
95    registered search functions is scanned. If no :class:`CodecInfo` object is
96    found, a :exc:`LookupError` is raised. Otherwise, the :class:`CodecInfo` object
97    is stored in the cache and returned to the caller.
98
99 To simplify access to the various codecs, the module provides these additional
100 functions which use :func:`lookup` for the codec lookup:
101
102
103 .. function:: getencoder(encoding)
104
105    Look up the codec for the given encoding and return its encoder function.
106
107    Raises a :exc:`LookupError` in case the encoding cannot be found.
108
109
110 .. function:: getdecoder(encoding)
111
112    Look up the codec for the given encoding and return its decoder function.
113
114    Raises a :exc:`LookupError` in case the encoding cannot be found.
115
116
117 .. function:: getincrementalencoder(encoding)
118
119    Look up the codec for the given encoding and return its incremental encoder
120    class or factory function.
121
122    Raises a :exc:`LookupError` in case the encoding cannot be found or the codec
123    doesn't support an incremental encoder.
124
125    .. versionadded:: 2.5
126
127
128 .. function:: getincrementaldecoder(encoding)
129
130    Look up the codec for the given encoding and return its incremental decoder
131    class or factory function.
132
133    Raises a :exc:`LookupError` in case the encoding cannot be found or the codec
134    doesn't support an incremental decoder.
135
136    .. versionadded:: 2.5
137
138
139 .. function:: getreader(encoding)
140
141    Look up the codec for the given encoding and return its StreamReader class or
142    factory function.
143
144    Raises a :exc:`LookupError` in case the encoding cannot be found.
145
146
147 .. function:: getwriter(encoding)
148
149    Look up the codec for the given encoding and return its StreamWriter class or
150    factory function.
151
152    Raises a :exc:`LookupError` in case the encoding cannot be found.
153
154
155 .. function:: register_error(name, error_handler)
156
157    Register the error handling function *error_handler* under the name *name*.
158    *error_handler* will be called during encoding and decoding in case of an error,
159    when *name* is specified as the errors parameter.
160
161    For encoding *error_handler* will be called with a :exc:`UnicodeEncodeError`
162    instance, which contains information about the location of the error. The error
163    handler must either raise this or a different exception or return a tuple with a
164    replacement for the unencodable part of the input and a position where encoding
165    should continue. The encoder will encode the replacement and continue encoding
166    the original input at the specified position. Negative position values will be
167    treated as being relative to the end of the input string. If the resulting
168    position is out of bound an :exc:`IndexError` will be raised.
169
170    Decoding and translating works similar, except :exc:`UnicodeDecodeError` or
171    :exc:`UnicodeTranslateError` will be passed to the handler and that the
172    replacement from the error handler will be put into the output directly.
173
174
175 .. function:: lookup_error(name)
176
177    Return the error handler previously registered under the name *name*.
178
179    Raises a :exc:`LookupError` in case the handler cannot be found.
180
181
182 .. function:: strict_errors(exception)
183
184    Implements the ``strict`` error handling: each encoding or decoding error
185    raises a :exc:`UnicodeError`.
186
187
188 .. function:: replace_errors(exception)
189
190    Implements the ``replace`` error handling: malformed data is replaced with a
191    suitable replacement character such as ``'?'`` in bytestrings and
192    ``'\ufffd'`` in Unicode strings.
193
194
195 .. function:: ignore_errors(exception)
196
197    Implements the ``ignore`` error handling: malformed data is ignored and
198    encoding or decoding is continued without further notice.
199
200
201 .. function:: xmlcharrefreplace_errors(exception)
202
203    Implements the ``xmlcharrefreplace`` error handling (for encoding only): the
204    unencodable character is replaced by an appropriate XML character reference.
205
206
207 .. function:: backslashreplace_errors(exception)
208
209    Implements the ``backslashreplace`` error handling (for encoding only): the
210    unencodable character is replaced by a backslashed escape sequence.
211
212 To simplify working with encoded files or stream, the module also defines these
213 utility functions:
214
215
216 .. function:: open(filename, mode[, encoding[, errors[, buffering]]])
217
218    Open an encoded file using the given *mode* and return a wrapped version
219    providing transparent encoding/decoding.  The default file mode is ``'r'``
220    meaning to open the file in read mode.
221
222    .. note::
223
224       The wrapped version will only accept the object format defined by the codecs,
225       i.e. Unicode objects for most built-in codecs.  Output is also codec-dependent
226       and will usually be Unicode as well.
227
228    .. note::
229
230       Files are always opened in binary mode, even if no binary mode was
231       specified.  This is done to avoid data loss due to encodings using 8-bit
232       values.  This means that no automatic conversion of ``'\n'`` is done
233       on reading and writing.
234
235    *encoding* specifies the encoding which is to be used for the file.
236
237    *errors* may be given to define the error handling. It defaults to ``'strict'``
238    which causes a :exc:`ValueError` to be raised in case an encoding error occurs.
239
240    *buffering* has the same meaning as for the built-in :func:`open` function.  It
241    defaults to line buffered.
242
243
244 .. function:: EncodedFile(file, input[, output[, errors]])
245
246    Return a wrapped version of file which provides transparent encoding
247    translation.
248
249    Strings written to the wrapped file are interpreted according to the given
250    *input* encoding and then written to the original file as strings using the
251    *output* encoding. The intermediate encoding will usually be Unicode but depends
252    on the specified codecs.
253
254    If *output* is not given, it defaults to *input*.
255
256    *errors* may be given to define the error handling. It defaults to ``'strict'``,
257    which causes :exc:`ValueError` to be raised in case an encoding error occurs.
258
259
260 .. function:: iterencode(iterable, encoding[, errors])
261
262    Uses an incremental encoder to iteratively encode the input provided by
263    *iterable*. This function is a :term:`generator`.  *errors* (as well as any
264    other keyword argument) is passed through to the incremental encoder.
265
266    .. versionadded:: 2.5
267
268
269 .. function:: iterdecode(iterable, encoding[, errors])
270
271    Uses an incremental decoder to iteratively decode the input provided by
272    *iterable*. This function is a :term:`generator`.  *errors* (as well as any
273    other keyword argument) is passed through to the incremental decoder.
274
275    .. versionadded:: 2.5
276
277 The module also provides the following constants which are useful for reading
278 and writing to platform dependent files:
279
280
281 .. data:: BOM
282           BOM_BE
283           BOM_LE
284           BOM_UTF8
285           BOM_UTF16
286           BOM_UTF16_BE
287           BOM_UTF16_LE
288           BOM_UTF32
289           BOM_UTF32_BE
290           BOM_UTF32_LE
291
292    These constants define various encodings of the Unicode byte order mark (BOM)
293    used in UTF-16 and UTF-32 data streams to indicate the byte order used in the
294    stream or file and in UTF-8 as a Unicode signature. :const:`BOM_UTF16` is either
295    :const:`BOM_UTF16_BE` or :const:`BOM_UTF16_LE` depending on the platform's
296    native byte order, :const:`BOM` is an alias for :const:`BOM_UTF16`,
297    :const:`BOM_LE` for :const:`BOM_UTF16_LE` and :const:`BOM_BE` for
298    :const:`BOM_UTF16_BE`. The others represent the BOM in UTF-8 and UTF-32
299    encodings.
300
301
302 .. _codec-base-classes:
303
304 Codec Base Classes
305 ------------------
306
307 The :mod:`codecs` module defines a set of base classes which define the
308 interface and can also be used to easily write your own codecs for use in
309 Python.
310
311 Each codec has to define four interfaces to make it usable as codec in Python:
312 stateless encoder, stateless decoder, stream reader and stream writer. The
313 stream reader and writers typically reuse the stateless encoder/decoder to
314 implement the file protocols.
315
316 The :class:`Codec` class defines the interface for stateless encoders/decoders.
317
318 To simplify and standardize error handling, the :meth:`encode` and
319 :meth:`decode` methods may implement different error handling schemes by
320 providing the *errors* string argument.  The following string values are defined
321 and implemented by all standard Python codecs:
322
323 +-------------------------+-----------------------------------------------+
324 | Value                   | Meaning                                       |
325 +=========================+===============================================+
326 | ``'strict'``            | Raise :exc:`UnicodeError` (or a subclass);    |
327 |                         | this is the default.                          |
328 +-------------------------+-----------------------------------------------+
329 | ``'ignore'``            | Ignore the character and continue with the    |
330 |                         | next.                                         |
331 +-------------------------+-----------------------------------------------+
332 | ``'replace'``           | Replace with a suitable replacement           |
333 |                         | character; Python will use the official       |
334 |                         | U+FFFD REPLACEMENT CHARACTER for the built-in |
335 |                         | Unicode codecs on decoding and '?' on         |
336 |                         | encoding.                                     |
337 +-------------------------+-----------------------------------------------+
338 | ``'xmlcharrefreplace'`` | Replace with the appropriate XML character    |
339 |                         | reference (only for encoding).                |
340 +-------------------------+-----------------------------------------------+
341 | ``'backslashreplace'``  | Replace with backslashed escape sequences     |
342 |                         | (only for encoding).                          |
343 +-------------------------+-----------------------------------------------+
344
345 The set of allowed values can be extended via :meth:`register_error`.
346
347
348 .. _codec-objects:
349
350 Codec Objects
351 ^^^^^^^^^^^^^
352
353 The :class:`Codec` class defines these methods which also define the function
354 interfaces of the stateless encoder and decoder:
355
356
357 .. method:: Codec.encode(input[, errors])
358
359    Encodes the object *input* and returns a tuple (output object, length consumed).
360    While codecs are not restricted to use with Unicode, in a Unicode context,
361    encoding converts a Unicode object to a plain string using a particular
362    character set encoding (e.g., ``cp1252`` or ``iso-8859-1``).
363
364    *errors* defines the error handling to apply. It defaults to ``'strict'``
365    handling.
366
367    The method may not store state in the :class:`Codec` instance. Use
368    :class:`StreamCodec` for codecs which have to keep state in order to make
369    encoding/decoding efficient.
370
371    The encoder must be able to handle zero length input and return an empty object
372    of the output object type in this situation.
373
374
375 .. method:: Codec.decode(input[, errors])
376
377    Decodes the object *input* and returns a tuple (output object, length consumed).
378    In a Unicode context, decoding converts a plain string encoded using a
379    particular character set encoding to a Unicode object.
380
381    *input* must be an object which provides the ``bf_getreadbuf`` buffer slot.
382    Python strings, buffer objects and memory mapped files are examples of objects
383    providing this slot.
384
385    *errors* defines the error handling to apply. It defaults to ``'strict'``
386    handling.
387
388    The method may not store state in the :class:`Codec` instance. Use
389    :class:`StreamCodec` for codecs which have to keep state in order to make
390    encoding/decoding efficient.
391
392    The decoder must be able to handle zero length input and return an empty object
393    of the output object type in this situation.
394
395 The :class:`IncrementalEncoder` and :class:`IncrementalDecoder` classes provide
396 the basic interface for incremental encoding and decoding. Encoding/decoding the
397 input isn't done with one call to the stateless encoder/decoder function, but
398 with multiple calls to the :meth:`encode`/:meth:`decode` method of the
399 incremental encoder/decoder. The incremental encoder/decoder keeps track of the
400 encoding/decoding process during method calls.
401
402 The joined output of calls to the :meth:`encode`/:meth:`decode` method is the
403 same as if all the single inputs were joined into one, and this input was
404 encoded/decoded with the stateless encoder/decoder.
405
406
407 .. _incremental-encoder-objects:
408
409 IncrementalEncoder Objects
410 ^^^^^^^^^^^^^^^^^^^^^^^^^^
411
412 .. versionadded:: 2.5
413
414 The :class:`IncrementalEncoder` class is used for encoding an input in multiple
415 steps. It defines the following methods which every incremental encoder must
416 define in order to be compatible with the Python codec registry.
417
418
419 .. class:: IncrementalEncoder([errors])
420
421    Constructor for an :class:`IncrementalEncoder` instance.
422
423    All incremental encoders must provide this constructor interface. They are free
424    to add additional keyword arguments, but only the ones defined here are used by
425    the Python codec registry.
426
427    The :class:`IncrementalEncoder` may implement different error handling schemes
428    by providing the *errors* keyword argument. These parameters are predefined:
429
430    * ``'strict'`` Raise :exc:`ValueError` (or a subclass); this is the default.
431
432    * ``'ignore'`` Ignore the character and continue with the next.
433
434    * ``'replace'`` Replace with a suitable replacement character
435
436    * ``'xmlcharrefreplace'`` Replace with the appropriate XML character reference
437
438    * ``'backslashreplace'`` Replace with backslashed escape sequences.
439
440    The *errors* argument will be assigned to an attribute of the same name.
441    Assigning to this attribute makes it possible to switch between different error
442    handling strategies during the lifetime of the :class:`IncrementalEncoder`
443    object.
444
445    The set of allowed values for the *errors* argument can be extended with
446    :func:`register_error`.
447
448
449    .. method:: encode(object[, final])
450
451       Encodes *object* (taking the current state of the encoder into account)
452       and returns the resulting encoded object. If this is the last call to
453       :meth:`encode` *final* must be true (the default is false).
454
455
456    .. method:: reset()
457
458       Reset the encoder to the initial state.
459
460
461 .. _incremental-decoder-objects:
462
463 IncrementalDecoder Objects
464 ^^^^^^^^^^^^^^^^^^^^^^^^^^
465
466 The :class:`IncrementalDecoder` class is used for decoding an input in multiple
467 steps. It defines the following methods which every incremental decoder must
468 define in order to be compatible with the Python codec registry.
469
470
471 .. class:: IncrementalDecoder([errors])
472
473    Constructor for an :class:`IncrementalDecoder` instance.
474
475    All incremental decoders must provide this constructor interface. They are free
476    to add additional keyword arguments, but only the ones defined here are used by
477    the Python codec registry.
478
479    The :class:`IncrementalDecoder` may implement different error handling schemes
480    by providing the *errors* keyword argument. These parameters are predefined:
481
482    * ``'strict'`` Raise :exc:`ValueError` (or a subclass); this is the default.
483
484    * ``'ignore'`` Ignore the character and continue with the next.
485
486    * ``'replace'`` Replace with a suitable replacement character.
487
488    The *errors* argument will be assigned to an attribute of the same name.
489    Assigning to this attribute makes it possible to switch between different error
490    handling strategies during the lifetime of the :class:`IncrementalDecoder`
491    object.
492
493    The set of allowed values for the *errors* argument can be extended with
494    :func:`register_error`.
495
496
497    .. method:: decode(object[, final])
498
499       Decodes *object* (taking the current state of the decoder into account)
500       and returns the resulting decoded object. If this is the last call to
501       :meth:`decode` *final* must be true (the default is false). If *final* is
502       true the decoder must decode the input completely and must flush all
503       buffers. If this isn't possible (e.g. because of incomplete byte sequences
504       at the end of the input) it must initiate error handling just like in the
505       stateless case (which might raise an exception).
506
507
508    .. method:: reset()
509
510       Reset the decoder to the initial state.
511
512
513 The :class:`StreamWriter` and :class:`StreamReader` classes provide generic
514 working interfaces which can be used to implement new encoding submodules very
515 easily. See :mod:`encodings.utf_8` for an example of how this is done.
516
517
518 .. _stream-writer-objects:
519
520 StreamWriter Objects
521 ^^^^^^^^^^^^^^^^^^^^
522
523 The :class:`StreamWriter` class is a subclass of :class:`Codec` and defines the
524 following methods which every stream writer must define in order to be
525 compatible with the Python codec registry.
526
527
528 .. class:: StreamWriter(stream[, errors])
529
530    Constructor for a :class:`StreamWriter` instance.
531
532    All stream writers must provide this constructor interface. They are free to add
533    additional keyword arguments, but only the ones defined here are used by the
534    Python codec registry.
535
536    *stream* must be a file-like object open for writing binary data.
537
538    The :class:`StreamWriter` may implement different error handling schemes by
539    providing the *errors* keyword argument. These parameters are predefined:
540
541    * ``'strict'`` Raise :exc:`ValueError` (or a subclass); this is the default.
542
543    * ``'ignore'`` Ignore the character and continue with the next.
544
545    * ``'replace'`` Replace with a suitable replacement character
546
547    * ``'xmlcharrefreplace'`` Replace with the appropriate XML character reference
548
549    * ``'backslashreplace'`` Replace with backslashed escape sequences.
550
551    The *errors* argument will be assigned to an attribute of the same name.
552    Assigning to this attribute makes it possible to switch between different error
553    handling strategies during the lifetime of the :class:`StreamWriter` object.
554
555    The set of allowed values for the *errors* argument can be extended with
556    :func:`register_error`.
557
558
559    .. method:: write(object)
560
561       Writes the object's contents encoded to the stream.
562
563
564    .. method:: writelines(list)
565
566       Writes the concatenated list of strings to the stream (possibly by reusing
567       the :meth:`write` method).
568
569
570    .. method:: reset()
571
572       Flushes and resets the codec buffers used for keeping state.
573
574       Calling this method should ensure that the data on the output is put into
575       a clean state that allows appending of new fresh data without having to
576       rescan the whole stream to recover state.
577
578
579 In addition to the above methods, the :class:`StreamWriter` must also inherit
580 all other methods and attributes from the underlying stream.
581
582
583 .. _stream-reader-objects:
584
585 StreamReader Objects
586 ^^^^^^^^^^^^^^^^^^^^
587
588 The :class:`StreamReader` class is a subclass of :class:`Codec` and defines the
589 following methods which every stream reader must define in order to be
590 compatible with the Python codec registry.
591
592
593 .. class:: StreamReader(stream[, errors])
594
595    Constructor for a :class:`StreamReader` instance.
596
597    All stream readers must provide this constructor interface. They are free to add
598    additional keyword arguments, but only the ones defined here are used by the
599    Python codec registry.
600
601    *stream* must be a file-like object open for reading (binary) data.
602
603    The :class:`StreamReader` may implement different error handling schemes by
604    providing the *errors* keyword argument. These parameters are defined:
605
606    * ``'strict'`` Raise :exc:`ValueError` (or a subclass); this is the default.
607
608    * ``'ignore'`` Ignore the character and continue with the next.
609
610    * ``'replace'`` Replace with a suitable replacement character.
611
612    The *errors* argument will be assigned to an attribute of the same name.
613    Assigning to this attribute makes it possible to switch between different error
614    handling strategies during the lifetime of the :class:`StreamReader` object.
615
616    The set of allowed values for the *errors* argument can be extended with
617    :func:`register_error`.
618
619
620    .. method:: read([size[, chars, [firstline]]])
621
622       Decodes data from the stream and returns the resulting object.
623
624       *chars* indicates the number of characters to read from the
625       stream. :func:`read` will never return more than *chars* characters, but
626       it might return less, if there are not enough characters available.
627
628       *size* indicates the approximate maximum number of bytes to read from the
629       stream for decoding purposes. The decoder can modify this setting as
630       appropriate. The default value -1 indicates to read and decode as much as
631       possible.  *size* is intended to prevent having to decode huge files in
632       one step.
633
634       *firstline* indicates that it would be sufficient to only return the first
635       line, if there are decoding errors on later lines.
636
637       The method should use a greedy read strategy meaning that it should read
638       as much data as is allowed within the definition of the encoding and the
639       given size, e.g.  if optional encoding endings or state markers are
640       available on the stream, these should be read too.
641
642       .. versionchanged:: 2.4
643          *chars* argument added.
644
645       .. versionchanged:: 2.4.2
646          *firstline* argument added.
647
648
649    .. method:: readline([size[, keepends]])
650
651       Read one line from the input stream and return the decoded data.
652
653       *size*, if given, is passed as size argument to the stream's
654       :meth:`readline` method.
655
656       If *keepends* is false line-endings will be stripped from the lines
657       returned.
658
659       .. versionchanged:: 2.4
660          *keepends* argument added.
661
662
663    .. method:: readlines([sizehint[, keepends]])
664
665       Read all lines available on the input stream and return them as a list of
666       lines.
667
668       Line-endings are implemented using the codec's decoder method and are
669       included in the list entries if *keepends* is true.
670
671       *sizehint*, if given, is passed as the *size* argument to the stream's
672       :meth:`read` method.
673
674
675    .. method:: reset()
676
677       Resets the codec buffers used for keeping state.
678
679       Note that no stream repositioning should take place.  This method is
680       primarily intended to be able to recover from decoding errors.
681
682
683 In addition to the above methods, the :class:`StreamReader` must also inherit
684 all other methods and attributes from the underlying stream.
685
686 The next two base classes are included for convenience. They are not needed by
687 the codec registry, but may provide useful in practice.
688
689
690 .. _stream-reader-writer:
691
692 StreamReaderWriter Objects
693 ^^^^^^^^^^^^^^^^^^^^^^^^^^
694
695 The :class:`StreamReaderWriter` allows wrapping streams which work in both read
696 and write modes.
697
698 The design is such that one can use the factory functions returned by the
699 :func:`lookup` function to construct the instance.
700
701
702 .. class:: StreamReaderWriter(stream, Reader, Writer, errors)
703
704    Creates a :class:`StreamReaderWriter` instance. *stream* must be a file-like
705    object. *Reader* and *Writer* must be factory functions or classes providing the
706    :class:`StreamReader` and :class:`StreamWriter` interface resp. Error handling
707    is done in the same way as defined for the stream readers and writers.
708
709 :class:`StreamReaderWriter` instances define the combined interfaces of
710 :class:`StreamReader` and :class:`StreamWriter` classes. They inherit all other
711 methods and attributes from the underlying stream.
712
713
714 .. _stream-recoder-objects:
715
716 StreamRecoder Objects
717 ^^^^^^^^^^^^^^^^^^^^^
718
719 The :class:`StreamRecoder` provide a frontend - backend view of encoding data
720 which is sometimes useful when dealing with different encoding environments.
721
722 The design is such that one can use the factory functions returned by the
723 :func:`lookup` function to construct the instance.
724
725
726 .. class:: StreamRecoder(stream, encode, decode, Reader, Writer, errors)
727
728    Creates a :class:`StreamRecoder` instance which implements a two-way conversion:
729    *encode* and *decode* work on the frontend (the input to :meth:`read` and output
730    of :meth:`write`) while *Reader* and *Writer* work on the backend (reading and
731    writing to the stream).
732
733    You can use these objects to do transparent direct recodings from e.g. Latin-1
734    to UTF-8 and back.
735
736    *stream* must be a file-like object.
737
738    *encode*, *decode* must adhere to the :class:`Codec` interface. *Reader*,
739    *Writer* must be factory functions or classes providing objects of the
740    :class:`StreamReader` and :class:`StreamWriter` interface respectively.
741
742    *encode* and *decode* are needed for the frontend translation, *Reader* and
743    *Writer* for the backend translation.  The intermediate format used is
744    determined by the two sets of codecs, e.g. the Unicode codecs will use Unicode
745    as the intermediate encoding.
746
747    Error handling is done in the same way as defined for the stream readers and
748    writers.
749
750
751 :class:`StreamRecoder` instances define the combined interfaces of
752 :class:`StreamReader` and :class:`StreamWriter` classes. They inherit all other
753 methods and attributes from the underlying stream.
754
755
756 .. _encodings-overview:
757
758 Encodings and Unicode
759 ---------------------
760
761 Unicode strings are stored internally as sequences of codepoints (to be precise
762 as :c:type:`Py_UNICODE` arrays). Depending on the way Python is compiled (either
763 via ``--enable-unicode=ucs2`` or ``--enable-unicode=ucs4``, with the
764 former being the default) :c:type:`Py_UNICODE` is either a 16-bit or 32-bit data
765 type. Once a Unicode object is used outside of CPU and memory, CPU endianness
766 and how these arrays are stored as bytes become an issue.  Transforming a
767 unicode object into a sequence of bytes is called encoding and recreating the
768 unicode object from the sequence of bytes is known as decoding.  There are many
769 different methods for how this transformation can be done (these methods are
770 also called encodings). The simplest method is to map the codepoints 0-255 to
771 the bytes ``0x0``-``0xff``. This means that a unicode object that contains
772 codepoints above ``U+00FF`` can't be encoded with this method (which is called
773 ``'latin-1'`` or ``'iso-8859-1'``). :func:`unicode.encode` will raise a
774 :exc:`UnicodeEncodeError` that looks like this: ``UnicodeEncodeError: 'latin-1'
775 codec can't encode character u'\u1234' in position 3: ordinal not in
776 range(256)``.
777
778 There's another group of encodings (the so called charmap encodings) that choose
779 a different subset of all unicode code points and how these codepoints are
780 mapped to the bytes ``0x0``-``0xff``. To see how this is done simply open
781 e.g. :file:`encodings/cp1252.py` (which is an encoding that is used primarily on
782 Windows). There's a string constant with 256 characters that shows you which
783 character is mapped to which byte value.
784
785 All of these encodings can only encode 256 of the 1114112 codepoints
786 defined in unicode. A simple and straightforward way that can store each Unicode
787 code point, is to store each codepoint as four consecutive bytes. There are two
788 possibilities: store the bytes in big endian or in little endian order. These
789 two encodings are called ``UTF-32-BE`` and ``UTF-32-LE`` respectively. Their
790 disadvantage is that if e.g. you use ``UTF-32-BE`` on a little endian machine you
791 will always have to swap bytes on encoding and decoding. ``UTF-32`` avoids this
792 problem: bytes will always be in natural endianness. When these bytes are read
793 by a CPU with a different endianness, then bytes have to be swapped though. To
794 be able to detect the endianness of a ``UTF-16`` or ``UTF-32`` byte sequence,
795 there's the so called BOM ("Byte Order Mark"). This is the Unicode character
796 ``U+FEFF``. This character can be prepended to every ``UTF-16`` or ``UTF-32``
797 byte sequence. The byte swapped version of this character (``0xFFFE``) is an
798 illegal character that may not appear in a Unicode text. So when the
799 first character in an ``UTF-16`` or ``UTF-32`` byte sequence
800 appears to be a ``U+FFFE`` the bytes have to be swapped on decoding.
801 Unfortunately the character ``U+FEFF`` had a second purpose as
802 a ``ZERO WIDTH NO-BREAK SPACE``: a character that has no width and doesn't allow
803 a word to be split. It can e.g. be used to give hints to a ligature algorithm.
804 With Unicode 4.0 using ``U+FEFF`` as a ``ZERO WIDTH NO-BREAK SPACE`` has been
805 deprecated (with ``U+2060`` (``WORD JOINER``) assuming this role). Nevertheless
806 Unicode software still must be able to handle ``U+FEFF`` in both roles: as a BOM
807 it's a device to determine the storage layout of the encoded bytes, and vanishes
808 once the byte sequence has been decoded into a Unicode string; as a ``ZERO WIDTH
809 NO-BREAK SPACE`` it's a normal character that will be decoded like any other.
810
811 There's another encoding that is able to encoding the full range of Unicode
812 characters: UTF-8. UTF-8 is an 8-bit encoding, which means there are no issues
813 with byte order in UTF-8. Each byte in a UTF-8 byte sequence consists of two
814 parts: marker bits (the most significant bits) and payload bits. The marker bits
815 are a sequence of zero to four ``1`` bits followed by a ``0`` bit. Unicode characters are
816 encoded like this (with x being payload bits, which when concatenated give the
817 Unicode character):
818
819 +-----------------------------------+----------------------------------------------+
820 | Range                             | Encoding                                     |
821 +===================================+==============================================+
822 | ``U-00000000`` ... ``U-0000007F`` | 0xxxxxxx                                     |
823 +-----------------------------------+----------------------------------------------+
824 | ``U-00000080`` ... ``U-000007FF`` | 110xxxxx 10xxxxxx                            |
825 +-----------------------------------+----------------------------------------------+
826 | ``U-00000800`` ... ``U-0000FFFF`` | 1110xxxx 10xxxxxx 10xxxxxx                   |
827 +-----------------------------------+----------------------------------------------+
828 | ``U-00010000`` ... ``U-0010FFFF`` | 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx          |
829 +-----------------------------------+----------------------------------------------+
830
831 The least significant bit of the Unicode character is the rightmost x bit.
832
833 As UTF-8 is an 8-bit encoding no BOM is required and any ``U+FEFF`` character in
834 the decoded Unicode string (even if it's the first character) is treated as a
835 ``ZERO WIDTH NO-BREAK SPACE``.
836
837 Without external information it's impossible to reliably determine which
838 encoding was used for encoding a Unicode string. Each charmap encoding can
839 decode any random byte sequence. However that's not possible with UTF-8, as
840 UTF-8 byte sequences have a structure that doesn't allow arbitrary byte
841 sequences. To increase the reliability with which a UTF-8 encoding can be
842 detected, Microsoft invented a variant of UTF-8 (that Python 2.5 calls
843 ``"utf-8-sig"``) for its Notepad program: Before any of the Unicode characters
844 is written to the file, a UTF-8 encoded BOM (which looks like this as a byte
845 sequence: ``0xef``, ``0xbb``, ``0xbf``) is written. As it's rather improbable
846 that any charmap encoded file starts with these byte values (which would e.g.
847 map to
848
849    | LATIN SMALL LETTER I WITH DIAERESIS
850    | RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK
851    | INVERTED QUESTION MARK
852
853 in iso-8859-1), this increases the probability that a ``utf-8-sig`` encoding can be
854 correctly guessed from the byte sequence. So here the BOM is not used to be able
855 to determine the byte order used for generating the byte sequence, but as a
856 signature that helps in guessing the encoding. On encoding the utf-8-sig codec
857 will write ``0xef``, ``0xbb``, ``0xbf`` as the first three bytes to the file. On
858 decoding ``utf-8-sig`` will skip those three bytes if they appear as the first
859 three bytes in the file.  In UTF-8, the use of the BOM is discouraged and
860 should generally be avoided.
861
862
863 .. _standard-encodings:
864
865 Standard Encodings
866 ------------------
867
868 Python comes with a number of codecs built-in, either implemented as C functions
869 or with dictionaries as mapping tables. The following table lists the codecs by
870 name, together with a few common aliases, and the languages for which the
871 encoding is likely used. Neither the list of aliases nor the list of languages
872 is meant to be exhaustive. Notice that spelling alternatives that only differ in
873 case or use a hyphen instead of an underscore are also valid aliases; therefore,
874 e.g. ``'utf-8'`` is a valid alias for the ``'utf_8'`` codec.
875
876 Many of the character sets support the same languages. They vary in individual
877 characters (e.g. whether the EURO SIGN is supported or not), and in the
878 assignment of characters to code positions. For the European languages in
879 particular, the following variants typically exist:
880
881 * an ISO 8859 codeset
882
883 * a Microsoft Windows code page, which is typically derived from a 8859 codeset,
884   but replaces control characters with additional graphic characters
885
886 * an IBM EBCDIC code page
887
888 * an IBM PC code page, which is ASCII compatible
889
890 +-----------------+--------------------------------+--------------------------------+
891 | Codec           | Aliases                        | Languages                      |
892 +=================+================================+================================+
893 | ascii           | 646, us-ascii                  | English                        |
894 +-----------------+--------------------------------+--------------------------------+
895 | big5            | big5-tw, csbig5                | Traditional Chinese            |
896 +-----------------+--------------------------------+--------------------------------+
897 | big5hkscs       | big5-hkscs, hkscs              | Traditional Chinese            |
898 +-----------------+--------------------------------+--------------------------------+
899 | cp037           | IBM037, IBM039                 | English                        |
900 +-----------------+--------------------------------+--------------------------------+
901 | cp424           | EBCDIC-CP-HE, IBM424           | Hebrew                         |
902 +-----------------+--------------------------------+--------------------------------+
903 | cp437           | 437, IBM437                    | English                        |
904 +-----------------+--------------------------------+--------------------------------+
905 | cp500           | EBCDIC-CP-BE, EBCDIC-CP-CH,    | Western Europe                 |
906 |                 | IBM500                         |                                |
907 +-----------------+--------------------------------+--------------------------------+
908 | cp720           |                                | Arabic                         |
909 +-----------------+--------------------------------+--------------------------------+
910 | cp737           |                                | Greek                          |
911 +-----------------+--------------------------------+--------------------------------+
912 | cp775           | IBM775                         | Baltic languages               |
913 +-----------------+--------------------------------+--------------------------------+
914 | cp850           | 850, IBM850                    | Western Europe                 |
915 +-----------------+--------------------------------+--------------------------------+
916 | cp852           | 852, IBM852                    | Central and Eastern Europe     |
917 +-----------------+--------------------------------+--------------------------------+
918 | cp855           | 855, IBM855                    | Bulgarian, Byelorussian,       |
919 |                 |                                | Macedonian, Russian, Serbian   |
920 +-----------------+--------------------------------+--------------------------------+
921 | cp856           |                                | Hebrew                         |
922 +-----------------+--------------------------------+--------------------------------+
923 | cp857           | 857, IBM857                    | Turkish                        |
924 +-----------------+--------------------------------+--------------------------------+
925 | cp858           | 858, IBM858                    | Western Europe                 |
926 +-----------------+--------------------------------+--------------------------------+
927 | cp860           | 860, IBM860                    | Portuguese                     |
928 +-----------------+--------------------------------+--------------------------------+
929 | cp861           | 861, CP-IS, IBM861             | Icelandic                      |
930 +-----------------+--------------------------------+--------------------------------+
931 | cp862           | 862, IBM862                    | Hebrew                         |
932 +-----------------+--------------------------------+--------------------------------+
933 | cp863           | 863, IBM863                    | Canadian                       |
934 +-----------------+--------------------------------+--------------------------------+
935 | cp864           | IBM864                         | Arabic                         |
936 +-----------------+--------------------------------+--------------------------------+
937 | cp865           | 865, IBM865                    | Danish, Norwegian              |
938 +-----------------+--------------------------------+--------------------------------+
939 | cp866           | 866, IBM866                    | Russian                        |
940 +-----------------+--------------------------------+--------------------------------+
941 | cp869           | 869, CP-GR, IBM869             | Greek                          |
942 +-----------------+--------------------------------+--------------------------------+
943 | cp874           |                                | Thai                           |
944 +-----------------+--------------------------------+--------------------------------+
945 | cp875           |                                | Greek                          |
946 +-----------------+--------------------------------+--------------------------------+
947 | cp932           | 932, ms932, mskanji, ms-kanji  | Japanese                       |
948 +-----------------+--------------------------------+--------------------------------+
949 | cp949           | 949, ms949, uhc                | Korean                         |
950 +-----------------+--------------------------------+--------------------------------+
951 | cp950           | 950, ms950                     | Traditional Chinese            |
952 +-----------------+--------------------------------+--------------------------------+
953 | cp1006          |                                | Urdu                           |
954 +-----------------+--------------------------------+--------------------------------+
955 | cp1026          | ibm1026                        | Turkish                        |
956 +-----------------+--------------------------------+--------------------------------+
957 | cp1140          | ibm1140                        | Western Europe                 |
958 +-----------------+--------------------------------+--------------------------------+
959 | cp1250          | windows-1250                   | Central and Eastern Europe     |
960 +-----------------+--------------------------------+--------------------------------+
961 | cp1251          | windows-1251                   | Bulgarian, Byelorussian,       |
962 |                 |                                | Macedonian, Russian, Serbian   |
963 +-----------------+--------------------------------+--------------------------------+
964 | cp1252          | windows-1252                   | Western Europe                 |
965 +-----------------+--------------------------------+--------------------------------+
966 | cp1253          | windows-1253                   | Greek                          |
967 +-----------------+--------------------------------+--------------------------------+
968 | cp1254          | windows-1254                   | Turkish                        |
969 +-----------------+--------------------------------+--------------------------------+
970 | cp1255          | windows-1255                   | Hebrew                         |
971 +-----------------+--------------------------------+--------------------------------+
972 | cp1256          | windows-1256                   | Arabic                         |
973 +-----------------+--------------------------------+--------------------------------+
974 | cp1257          | windows-1257                   | Baltic languages               |
975 +-----------------+--------------------------------+--------------------------------+
976 | cp1258          | windows-1258                   | Vietnamese                     |
977 +-----------------+--------------------------------+--------------------------------+
978 | euc_jp          | eucjp, ujis, u-jis             | Japanese                       |
979 +-----------------+--------------------------------+--------------------------------+
980 | euc_jis_2004    | jisx0213, eucjis2004           | Japanese                       |
981 +-----------------+--------------------------------+--------------------------------+
982 | euc_jisx0213    | eucjisx0213                    | Japanese                       |
983 +-----------------+--------------------------------+--------------------------------+
984 | euc_kr          | euckr, korean, ksc5601,        | Korean                         |
985 |                 | ks_c-5601, ks_c-5601-1987,     |                                |
986 |                 | ksx1001, ks_x-1001             |                                |
987 +-----------------+--------------------------------+--------------------------------+
988 | gb2312          | chinese, csiso58gb231280, euc- | Simplified Chinese             |
989 |                 | cn, euccn, eucgb2312-cn,       |                                |
990 |                 | gb2312-1980, gb2312-80, iso-   |                                |
991 |                 | ir-58                          |                                |
992 +-----------------+--------------------------------+--------------------------------+
993 | gbk             | 936, cp936, ms936              | Unified Chinese                |
994 +-----------------+--------------------------------+--------------------------------+
995 | gb18030         | gb18030-2000                   | Unified Chinese                |
996 +-----------------+--------------------------------+--------------------------------+
997 | hz              | hzgb, hz-gb, hz-gb-2312        | Simplified Chinese             |
998 +-----------------+--------------------------------+--------------------------------+
999 | iso2022_jp      | csiso2022jp, iso2022jp,        | Japanese                       |
1000 |                 | iso-2022-jp                    |                                |
1001 +-----------------+--------------------------------+--------------------------------+
1002 | iso2022_jp_1    | iso2022jp-1, iso-2022-jp-1     | Japanese                       |
1003 +-----------------+--------------------------------+--------------------------------+
1004 | iso2022_jp_2    | iso2022jp-2, iso-2022-jp-2     | Japanese, Korean, Simplified   |
1005 |                 |                                | Chinese, Western Europe, Greek |
1006 +-----------------+--------------------------------+--------------------------------+
1007 | iso2022_jp_2004 | iso2022jp-2004,                | Japanese                       |
1008 |                 | iso-2022-jp-2004               |                                |
1009 +-----------------+--------------------------------+--------------------------------+
1010 | iso2022_jp_3    | iso2022jp-3, iso-2022-jp-3     | Japanese                       |
1011 +-----------------+--------------------------------+--------------------------------+
1012 | iso2022_jp_ext  | iso2022jp-ext, iso-2022-jp-ext | Japanese                       |
1013 +-----------------+--------------------------------+--------------------------------+
1014 | iso2022_kr      | csiso2022kr, iso2022kr,        | Korean                         |
1015 |                 | iso-2022-kr                    |                                |
1016 +-----------------+--------------------------------+--------------------------------+
1017 | latin_1         | iso-8859-1, iso8859-1, 8859,   | West Europe                    |
1018 |                 | cp819, latin, latin1, L1       |                                |
1019 +-----------------+--------------------------------+--------------------------------+
1020 | iso8859_2       | iso-8859-2, latin2, L2         | Central and Eastern Europe     |
1021 +-----------------+--------------------------------+--------------------------------+
1022 | iso8859_3       | iso-8859-3, latin3, L3         | Esperanto, Maltese             |
1023 +-----------------+--------------------------------+--------------------------------+
1024 | iso8859_4       | iso-8859-4, latin4, L4         | Baltic languages               |
1025 +-----------------+--------------------------------+--------------------------------+
1026 | iso8859_5       | iso-8859-5, cyrillic           | Bulgarian, Byelorussian,       |
1027 |                 |                                | Macedonian, Russian, Serbian   |
1028 +-----------------+--------------------------------+--------------------------------+
1029 | iso8859_6       | iso-8859-6, arabic             | Arabic                         |
1030 +-----------------+--------------------------------+--------------------------------+
1031 | iso8859_7       | iso-8859-7, greek, greek8      | Greek                          |
1032 +-----------------+--------------------------------+--------------------------------+
1033 | iso8859_8       | iso-8859-8, hebrew             | Hebrew                         |
1034 +-----------------+--------------------------------+--------------------------------+
1035 | iso8859_9       | iso-8859-9, latin5, L5         | Turkish                        |
1036 +-----------------+--------------------------------+--------------------------------+
1037 | iso8859_10      | iso-8859-10, latin6, L6        | Nordic languages               |
1038 +-----------------+--------------------------------+--------------------------------+
1039 | iso8859_13      | iso-8859-13, latin7, L7        | Baltic languages               |
1040 +-----------------+--------------------------------+--------------------------------+
1041 | iso8859_14      | iso-8859-14, latin8, L8        | Celtic languages               |
1042 +-----------------+--------------------------------+--------------------------------+
1043 | iso8859_15      | iso-8859-15, latin9, L9        | Western Europe                 |
1044 +-----------------+--------------------------------+--------------------------------+
1045 | iso8859_16      | iso-8859-16, latin10, L10      | South-Eastern Europe           |
1046 +-----------------+--------------------------------+--------------------------------+
1047 | johab           | cp1361, ms1361                 | Korean                         |
1048 +-----------------+--------------------------------+--------------------------------+
1049 | koi8_r          |                                | Russian                        |
1050 +-----------------+--------------------------------+--------------------------------+
1051 | koi8_u          |                                | Ukrainian                      |
1052 +-----------------+--------------------------------+--------------------------------+
1053 | mac_cyrillic    | maccyrillic                    | Bulgarian, Byelorussian,       |
1054 |                 |                                | Macedonian, Russian, Serbian   |
1055 +-----------------+--------------------------------+--------------------------------+
1056 | mac_greek       | macgreek                       | Greek                          |
1057 +-----------------+--------------------------------+--------------------------------+
1058 | mac_iceland     | maciceland                     | Icelandic                      |
1059 +-----------------+--------------------------------+--------------------------------+
1060 | mac_latin2      | maclatin2, maccentraleurope    | Central and Eastern Europe     |
1061 +-----------------+--------------------------------+--------------------------------+
1062 | mac_roman       | macroman                       | Western Europe                 |
1063 +-----------------+--------------------------------+--------------------------------+
1064 | mac_turkish     | macturkish                     | Turkish                        |
1065 +-----------------+--------------------------------+--------------------------------+
1066 | ptcp154         | csptcp154, pt154, cp154,       | Kazakh                         |
1067 |                 | cyrillic-asian                 |                                |
1068 +-----------------+--------------------------------+--------------------------------+
1069 | shift_jis       | csshiftjis, shiftjis, sjis,    | Japanese                       |
1070 |                 | s_jis                          |                                |
1071 +-----------------+--------------------------------+--------------------------------+
1072 | shift_jis_2004  | shiftjis2004, sjis_2004,       | Japanese                       |
1073 |                 | sjis2004                       |                                |
1074 +-----------------+--------------------------------+--------------------------------+
1075 | shift_jisx0213  | shiftjisx0213, sjisx0213,      | Japanese                       |
1076 |                 | s_jisx0213                     |                                |
1077 +-----------------+--------------------------------+--------------------------------+
1078 | utf_32          | U32, utf32                     | all languages                  |
1079 +-----------------+--------------------------------+--------------------------------+
1080 | utf_32_be       | UTF-32BE                       | all languages                  |
1081 +-----------------+--------------------------------+--------------------------------+
1082 | utf_32_le       | UTF-32LE                       | all languages                  |
1083 +-----------------+--------------------------------+--------------------------------+
1084 | utf_16          | U16, utf16                     | all languages                  |
1085 +-----------------+--------------------------------+--------------------------------+
1086 | utf_16_be       | UTF-16BE                       | all languages (BMP only)       |
1087 +-----------------+--------------------------------+--------------------------------+
1088 | utf_16_le       | UTF-16LE                       | all languages (BMP only)       |
1089 +-----------------+--------------------------------+--------------------------------+
1090 | utf_7           | U7, unicode-1-1-utf-7          | all languages                  |
1091 +-----------------+--------------------------------+--------------------------------+
1092 | utf_8           | U8, UTF, utf8                  | all languages                  |
1093 +-----------------+--------------------------------+--------------------------------+
1094 | utf_8_sig       |                                | all languages                  |
1095 +-----------------+--------------------------------+--------------------------------+
1096
1097 A number of codecs are specific to Python, so their codec names have no meaning
1098 outside Python. Some of them don't convert from Unicode strings to byte strings,
1099 but instead use the property of the Python codecs machinery that any bijective
1100 function with one argument can be considered as an encoding.
1101
1102 For the codecs listed below, the result in the "encoding" direction is always a
1103 byte string. The result of the "decoding" direction is listed as operand type in
1104 the table.
1105
1106 +--------------------+---------------------------+----------------+---------------------------+
1107 | Codec              | Aliases                   | Operand type   | Purpose                   |
1108 +====================+===========================+================+===========================+
1109 | base64_codec       | base64, base-64           | byte string    | Convert operand to MIME   |
1110 |                    |                           |                | base64                    |
1111 +--------------------+---------------------------+----------------+---------------------------+
1112 | bz2_codec          | bz2                       | byte string    | Compress the operand      |
1113 |                    |                           |                | using bz2                 |
1114 +--------------------+---------------------------+----------------+---------------------------+
1115 | hex_codec          | hex                       | byte string    | Convert operand to        |
1116 |                    |                           |                | hexadecimal               |
1117 |                    |                           |                | representation, with two  |
1118 |                    |                           |                | digits per byte           |
1119 +--------------------+---------------------------+----------------+---------------------------+
1120 | idna               |                           | Unicode string | Implements :rfc:`3490`,   |
1121 |                    |                           |                | see also                  |
1122 |                    |                           |                | :mod:`encodings.idna`     |
1123 +--------------------+---------------------------+----------------+---------------------------+
1124 | mbcs               | dbcs                      | Unicode string | Windows only: Encode      |
1125 |                    |                           |                | operand according to the  |
1126 |                    |                           |                | ANSI codepage (CP_ACP)    |
1127 +--------------------+---------------------------+----------------+---------------------------+
1128 | palmos             |                           | Unicode string | Encoding of PalmOS 3.5    |
1129 +--------------------+---------------------------+----------------+---------------------------+
1130 | punycode           |                           | Unicode string | Implements :rfc:`3492`    |
1131 +--------------------+---------------------------+----------------+---------------------------+
1132 | quopri_codec       | quopri, quoted-printable, | byte string    | Convert operand to MIME   |
1133 |                    | quotedprintable           |                | quoted printable          |
1134 +--------------------+---------------------------+----------------+---------------------------+
1135 | raw_unicode_escape |                           | Unicode string | Produce a string that is  |
1136 |                    |                           |                | suitable as raw Unicode   |
1137 |                    |                           |                | literal in Python source  |
1138 |                    |                           |                | code                      |
1139 +--------------------+---------------------------+----------------+---------------------------+
1140 | rot_13             | rot13                     | Unicode string | Returns the Caesar-cypher |
1141 |                    |                           |                | encryption of the operand |
1142 +--------------------+---------------------------+----------------+---------------------------+
1143 | string_escape      |                           | byte string    | Produce a string that is  |
1144 |                    |                           |                | suitable as string        |
1145 |                    |                           |                | literal in Python source  |
1146 |                    |                           |                | code                      |
1147 +--------------------+---------------------------+----------------+---------------------------+
1148 | undefined          |                           | any            | Raise an exception for    |
1149 |                    |                           |                | all conversions. Can be   |
1150 |                    |                           |                | used as the system        |
1151 |                    |                           |                | encoding if no automatic  |
1152 |                    |                           |                | :term:`coercion` between  |
1153 |                    |                           |                | byte and Unicode strings  |
1154 |                    |                           |                | is desired.               |
1155 +--------------------+---------------------------+----------------+---------------------------+
1156 | unicode_escape     |                           | Unicode string | Produce a string that is  |
1157 |                    |                           |                | suitable as Unicode       |
1158 |                    |                           |                | literal in Python source  |
1159 |                    |                           |                | code                      |
1160 +--------------------+---------------------------+----------------+---------------------------+
1161 | unicode_internal   |                           | Unicode string | Return the internal       |
1162 |                    |                           |                | representation of the     |
1163 |                    |                           |                | operand                   |
1164 +--------------------+---------------------------+----------------+---------------------------+
1165 | uu_codec           | uu                        | byte string    | Convert the operand using |
1166 |                    |                           |                | uuencode                  |
1167 +--------------------+---------------------------+----------------+---------------------------+
1168 | zlib_codec         | zip, zlib                 | byte string    | Compress the operand      |
1169 |                    |                           |                | using gzip                |
1170 +--------------------+---------------------------+----------------+---------------------------+
1171
1172 .. versionadded:: 2.3
1173    The ``idna`` and ``punycode`` encodings.
1174
1175
1176 :mod:`encodings.idna` --- Internationalized Domain Names in Applications
1177 ------------------------------------------------------------------------
1178
1179 .. module:: encodings.idna
1180    :synopsis: Internationalized Domain Names implementation
1181 .. moduleauthor:: Martin v. Löwis
1182
1183 .. versionadded:: 2.3
1184
1185 This module implements :rfc:`3490` (Internationalized Domain Names in
1186 Applications) and :rfc:`3492` (Nameprep: A Stringprep Profile for
1187 Internationalized Domain Names (IDN)). It builds upon the ``punycode`` encoding
1188 and :mod:`stringprep`.
1189
1190 These RFCs together define a protocol to support non-ASCII characters in domain
1191 names. A domain name containing non-ASCII characters (such as
1192 ``www.Alliancefrançaise.nu``) is converted into an ASCII-compatible encoding
1193 (ACE, such as ``www.xn--alliancefranaise-npb.nu``). The ACE form of the domain
1194 name is then used in all places where arbitrary characters are not allowed by
1195 the protocol, such as DNS queries, HTTP :mailheader:`Host` fields, and so
1196 on. This conversion is carried out in the application; if possible invisible to
1197 the user: The application should transparently convert Unicode domain labels to
1198 IDNA on the wire, and convert back ACE labels to Unicode before presenting them
1199 to the user.
1200
1201 Python supports this conversion in several ways:  the ``idna`` codec performs
1202 conversion between Unicode and ACE, separating an input string into labels
1203 based on the separator characters defined in `section 3.1`_ (1) of :rfc:`3490`
1204 and converting each label to ACE as required, and conversely separating an input
1205 byte string into labels based on the ``.`` separator and converting any ACE
1206 labels found into unicode.  Furthermore, the :mod:`socket` module
1207 transparently converts Unicode host names to ACE, so that applications need not
1208 be concerned about converting host names themselves when they pass them to the
1209 socket module. On top of that, modules that have host names as function
1210 parameters, such as :mod:`httplib` and :mod:`ftplib`, accept Unicode host names
1211 (:mod:`httplib` then also transparently sends an IDNA hostname in the
1212 :mailheader:`Host` field if it sends that field at all).
1213
1214 .. _section 3.1: http://tools.ietf.org/html/rfc3490#section-3.1
1215
1216 When receiving host names from the wire (such as in reverse name lookup), no
1217 automatic conversion to Unicode is performed: Applications wishing to present
1218 such host names to the user should decode them to Unicode.
1219
1220 The module :mod:`encodings.idna` also implements the nameprep procedure, which
1221 performs certain normalizations on host names, to achieve case-insensitivity of
1222 international domain names, and to unify similar characters. The nameprep
1223 functions can be used directly if desired.
1224
1225
1226 .. function:: nameprep(label)
1227
1228    Return the nameprepped version of *label*. The implementation currently assumes
1229    query strings, so ``AllowUnassigned`` is true.
1230
1231
1232 .. function:: ToASCII(label)
1233
1234    Convert a label to ASCII, as specified in :rfc:`3490`. ``UseSTD3ASCIIRules`` is
1235    assumed to be false.
1236
1237
1238 .. function:: ToUnicode(label)
1239
1240    Convert a label to Unicode, as specified in :rfc:`3490`.
1241
1242
1243 :mod:`encodings.utf_8_sig` --- UTF-8 codec with BOM signature
1244 -------------------------------------------------------------
1245
1246 .. module:: encodings.utf_8_sig
1247    :synopsis: UTF-8 codec with BOM signature
1248 .. moduleauthor:: Walter Dörwald
1249
1250 .. versionadded:: 2.5
1251
1252 This module implements a variant of the UTF-8 codec: On encoding a UTF-8 encoded
1253 BOM will be prepended to the UTF-8 encoded bytes. For the stateful encoder this
1254 is only done once (on the first write to the byte stream).  For decoding an
1255 optional UTF-8 encoded BOM at the start of the data will be skipped.
1256