rest25/library/codecs.rst => rest262/library/codecs.rst
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
n33-* ``name`` The name of the encoding;
n33+   * ``name`` The name of the encoding;
34
n35-* ``encoder`` The stateless encoding function;
n35+   * ``encode`` The stateless encoding function;
36
n37-* ``decoder`` The stateless decoding function;
n37+   * ``decode`` The stateless decoding function;
38
n39-* ``incrementalencoder`` An incremental encoder class or factory function;
n39+   * ``incrementalencoder`` An incremental encoder class or factory function;
40
n41-* ``incrementaldecoder`` An incremental decoder class or factory function;
n41+   * ``incrementaldecoder`` An incremental decoder class or factory function;
42
n43-* ``streamwriter`` A stream writer class or factory function;
n43+   * ``streamwriter`` A stream writer class or factory function;
44
n45-* ``streamreader`` A stream reader class or factory function.
n45+   * ``streamreader`` A stream reader class or factory function.
46
47   The various functions or classes take the following arguments:
48
n49-   *encoder* and *decoder*: These must be functions or methods which have the same
n49+   *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
n54-   *incrementalencoder* and *incrementalencoder*: These have to be factory
n54+   *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
n60-   the base classes :class:`IncrementalEncoder` and :class:`IncrementalEncoder`,
n60+   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
185   Implements the ``replace`` error handling.
186
187
188.. function:: ignore_errors(exception)
189
190   Implements the ``ignore`` error handling.
191
192
n193-.. function:: xmlcharrefreplace_errors_errors(exception)
n193+.. function:: xmlcharrefreplace_errors(exception)
194
195   Implements the ``xmlcharrefreplace`` error handling.
196
197
n198-.. function:: backslashreplace_errors_errors(exception)
n198+.. function:: backslashreplace_errors(exception)
199
200   Implements the ``backslashreplace`` error handling.
201
202To simplify working with encoded files or stream, the module also defines these
203utility functions:
204
205
206.. function:: open(filename, mode[, encoding[, errors[, buffering]]])
207
208   Open an encoded file using the given *mode* and return a wrapped version
n209-   providing transparent encoding/decoding.
n209+   providing transparent encoding/decoding.  The default file mode is ``'r'``
210+   meaning to open the file in read mode.
210
211   .. note::
212
213      The wrapped version will only accept the object format defined by the codecs,
214      i.e. Unicode objects for most built-in codecs.  Output is also codec-dependent
215      and will usually be Unicode as well.
n217+ 
218+   .. note::
219+ 
220+      Files are always opened in binary mode, even if no binary mode was
221+      specified.  This is done to avoid data loss due to encodings using 8-bit
222+      values.  This means that no automatic conversion of ``'\n'`` is done
223+      on reading and writing.
216
217   *encoding* specifies the encoding which is to be used for the file.
218
219   *errors* may be given to define the error handling. It defaults to ``'strict'``
220   which causes a :exc:`ValueError` to be raised in case an encoding error occurs.
221
222   *buffering* has the same meaning as for the built-in :func:`open` function.  It
223   defaults to line buffered.
237
238   *errors* may be given to define the error handling. It defaults to ``'strict'``,
239   which causes :exc:`ValueError` to be raised in case an encoding error occurs.
240
241
242.. function:: iterencode(iterable, encoding[, errors])
243
244   Uses an incremental encoder to iteratively encode the input provided by
n245-   *iterable*. This function is a generator. *errors* (as well as any other keyword
n253+   *iterable*. This function is a :term:`generator`.  *errors* (as well as any
246-   argument) is passed through to the incremental encoder.
254+   other keyword argument) is passed through to the incremental encoder.
247
248   .. versionadded:: 2.5
249
250
251.. function:: iterdecode(iterable, encoding[, errors])
252
253   Uses an incremental decoder to iteratively decode the input provided by
n254-   *iterable*. This function is a generator. *errors* (as well as any other keyword
n262+   *iterable*. This function is a :term:`generator`.  *errors* (as well as any
255-   argument) is passed through to the incremental encoder.
263+   other keyword argument) is passed through to the incremental decoder.
256
257   .. versionadded:: 2.5
258
259The module also provides the following constants which are useful for reading
260and writing to platform dependent files:
261
262
263.. data:: BOM
282
283
284.. _codec-base-classes:
285
286Codec Base Classes
287------------------
288
289The :mod:`codecs` module defines a set of base classes which define the
n290-interface and can also be used to easily write you own codecs for use in Python.
n298+interface and can also be used to easily write your own codecs for use in
299+Python.
291
292Each codec has to define four interfaces to make it usable as codec in Python:
293stateless encoder, stateless decoder, stream reader and stream writer. The
294stream reader and writers typically reuse the stateless encoder/decoder to
295implement the file protocols.
296
297The :class:`Codec` class defines the interface for stateless encoders/decoders.
298
330
331Codec Objects
332^^^^^^^^^^^^^
333
334The :class:`Codec` class defines these methods which also define the function
335interfaces of the stateless encoder and decoder:
336
337
n338-.. method:: XXX Class.encode(input[, errors])
n347+.. method:: Codec.encode(input[, errors])
339
340   Encodes the object *input* and returns a tuple (output object, length consumed).
341   While codecs are not restricted to use with Unicode, in a Unicode context,
342   encoding converts a Unicode object to a plain string using a particular
343   character set encoding (e.g., ``cp1252`` or ``iso-8859-1``).
344
345   *errors* defines the error handling to apply. It defaults to ``'strict'``
346   handling.
348   The method may not store state in the :class:`Codec` instance. Use
349   :class:`StreamCodec` for codecs which have to keep state in order to make
350   encoding/decoding efficient.
351
352   The encoder must be able to handle zero length input and return an empty object
353   of the output object type in this situation.
354
355
n356-.. method:: XXX Class.decode(input[, errors])
n365+.. method:: Codec.decode(input[, errors])
357
358   Decodes the object *input* and returns a tuple (output object, length consumed).
359   In a Unicode context, decoding converts a plain string encoded using a
360   particular character set encoding to a Unicode object.
361
362   *input* must be an object which provides the ``bf_getreadbuf`` buffer slot.
363   Python strings, buffer objects and memory mapped files are examples of objects
364   providing this slot.
403
404   All incremental encoders must provide this constructor interface. They are free
405   to add additional keyword arguments, but only the ones defined here are used by
406   the Python codec registry.
407
408   The :class:`IncrementalEncoder` may implement different error handling schemes
409   by providing the *errors* keyword argument. These parameters are predefined:
410
n411-* ``'strict'`` Raise :exc:`ValueError` (or a subclass); this is the default.
n420+   * ``'strict'`` Raise :exc:`ValueError` (or a subclass); this is the default.
412
n413-* ``'ignore'`` Ignore the character and continue with the next.
n422+   * ``'ignore'`` Ignore the character and continue with the next.
414
n415-* ``'replace'`` Replace with a suitable replacement character
n424+   * ``'replace'`` Replace with a suitable replacement character
416
n417-* ``'xmlcharrefreplace'`` Replace with the appropriate XML character reference
n426+   * ``'xmlcharrefreplace'`` Replace with the appropriate XML character reference
418
n419-* ``'backslashreplace'`` Replace with backslashed escape sequences.
n428+   * ``'backslashreplace'`` Replace with backslashed escape sequences.
420
421   The *errors* argument will be assigned to an attribute of the same name.
422   Assigning to this attribute makes it possible to switch between different error
423   handling strategies during the lifetime of the :class:`IncrementalEncoder`
424   object.
425
426   The set of allowed values for the *errors* argument can be extended with
427   :func:`register_error`.
428
429
n430-.. method:: IncrementalEncoder.encode(object[, final])
n439+   .. method:: encode(object[, final])
431
n432-   Encodes *object* (taking the current state of the encoder into account) and
n441+      Encodes *object* (taking the current state of the encoder into account)
433-   returns the resulting encoded object. If this is the last call to :meth:`encode`
442+      and returns the resulting encoded object. If this is the last call to
434-   *final* must be true (the default is false).
443+      :meth:`encode` *final* must be true (the default is false).
435
436
n437-.. method:: IncrementalEncoder.reset()
n446+   .. method:: reset()
438
n439-   Reset the encoder to the initial state.
n448+      Reset the encoder to the initial state.
440
441
442.. _incremental-decoder-objects:
443
444IncrementalDecoder Objects
445^^^^^^^^^^^^^^^^^^^^^^^^^^
446
447The :class:`IncrementalDecoder` class is used for decoding an input in multiple
455
456   All incremental decoders must provide this constructor interface. They are free
457   to add additional keyword arguments, but only the ones defined here are used by
458   the Python codec registry.
459
460   The :class:`IncrementalDecoder` may implement different error handling schemes
461   by providing the *errors* keyword argument. These parameters are predefined:
462
n463-* ``'strict'`` Raise :exc:`ValueError` (or a subclass); this is the default.
n472+   * ``'strict'`` Raise :exc:`ValueError` (or a subclass); this is the default.
464
n465-* ``'ignore'`` Ignore the character and continue with the next.
n474+   * ``'ignore'`` Ignore the character and continue with the next.
466
n467-* ``'replace'`` Replace with a suitable replacement character.
n476+   * ``'replace'`` Replace with a suitable replacement character.
468
469   The *errors* argument will be assigned to an attribute of the same name.
470   Assigning to this attribute makes it possible to switch between different error
n471-   handling strategies during the lifetime of the :class:`IncrementalEncoder`
n480+   handling strategies during the lifetime of the :class:`IncrementalDecoder`
472   object.
473
474   The set of allowed values for the *errors* argument can be extended with
475   :func:`register_error`.
476
477
n478-.. method:: IncrementalDecoder.decode(object[, final])
n487+   .. method:: decode(object[, final])
479
n480-   Decodes *object* (taking the current state of the decoder into account) and
n489+      Decodes *object* (taking the current state of the decoder into account)
481-   returns the resulting decoded object. If this is the last call to :meth:`decode`
490+      and returns the resulting decoded object. If this is the last call to
482-   *final* must be true (the default is false). If *final* is true the decoder must
491+      :meth:`decode` *final* must be true (the default is false). If *final* is
483-   decode the input completely and must flush all buffers. If this isn't possible
492+      true the decoder must decode the input completely and must flush all
484-   (e.g. because of incomplete byte sequences at the end of the input) it must
493+      buffers. If this isn't possible (e.g. because of incomplete byte sequences
485-   initiate error handling just like in the stateless case (which might raise an
494+      at the end of the input) it must initiate error handling just like in the
486-   exception).
495+      stateless case (which might raise an exception).
487
488
n489-.. method:: IncrementalDecoder.reset()
n498+   .. method:: reset()
490
n491-   Reset the decoder to the initial state.
n500+      Reset the decoder to the initial state.
501+ 
492
493The :class:`StreamWriter` and :class:`StreamReader` classes provide generic
494working interfaces which can be used to implement new encoding submodules very
495easily. See :mod:`encodings.utf_8` for an example of how this is done.
496
497
498.. _stream-writer-objects:
499
513   additional keyword arguments, but only the ones defined here are used by the
514   Python codec registry.
515
516   *stream* must be a file-like object open for writing binary data.
517
518   The :class:`StreamWriter` may implement different error handling schemes by
519   providing the *errors* keyword argument. These parameters are predefined:
520
n521-* ``'strict'`` Raise :exc:`ValueError` (or a subclass); this is the default.
n531+   * ``'strict'`` Raise :exc:`ValueError` (or a subclass); this is the default.
522
n523-* ``'ignore'`` Ignore the character and continue with the next.
n533+   * ``'ignore'`` Ignore the character and continue with the next.
524
n525-* ``'replace'`` Replace with a suitable replacement character
n535+   * ``'replace'`` Replace with a suitable replacement character
526
n527-* ``'xmlcharrefreplace'`` Replace with the appropriate XML character reference
n537+   * ``'xmlcharrefreplace'`` Replace with the appropriate XML character reference
528
n529-* ``'backslashreplace'`` Replace with backslashed escape sequences.
n539+   * ``'backslashreplace'`` Replace with backslashed escape sequences.
530
531   The *errors* argument will be assigned to an attribute of the same name.
532   Assigning to this attribute makes it possible to switch between different error
533   handling strategies during the lifetime of the :class:`StreamWriter` object.
534
535   The set of allowed values for the *errors* argument can be extended with
536   :func:`register_error`.
537
538
n539-.. method:: StreamWriter.write(object)
n549+   .. method:: write(object)
540
n541-   Writes the object's contents encoded to the stream.
n551+      Writes the object's contents encoded to the stream.
542
543
n544-.. method:: StreamWriter.writelines(list)
n554+   .. method:: writelines(list)
545
n546-   Writes the concatenated list of strings to the stream (possibly by reusing the
n556+      Writes the concatenated list of strings to the stream (possibly by reusing
547-   :meth:`write` method).
557+      the :meth:`write` method).
548
549
n550-.. method:: StreamWriter.reset()
n560+   .. method:: reset()
551
n552-   Flushes and resets the codec buffers used for keeping state.
n562+      Flushes and resets the codec buffers used for keeping state.
553
n554-   Calling this method should ensure that the data on the output is put into a
n564+      Calling this method should ensure that the data on the output is put into
555-   clean state that allows appending of new fresh data without having to rescan the
565+      a clean state that allows appending of new fresh data without having to
556-   whole stream to recover state.
566+      rescan the whole stream to recover state.
567+ 
557
558In addition to the above methods, the :class:`StreamWriter` must also inherit
559all other methods and attributes from the underlying stream.
560
561
562.. _stream-reader-objects:
563
564StreamReader Objects
577   additional keyword arguments, but only the ones defined here are used by the
578   Python codec registry.
579
580   *stream* must be a file-like object open for reading (binary) data.
581
582   The :class:`StreamReader` may implement different error handling schemes by
583   providing the *errors* keyword argument. These parameters are defined:
584
n585-* ``'strict'`` Raise :exc:`ValueError` (or a subclass); this is the default.
n596+   * ``'strict'`` Raise :exc:`ValueError` (or a subclass); this is the default.
586
n587-* ``'ignore'`` Ignore the character and continue with the next.
n598+   * ``'ignore'`` Ignore the character and continue with the next.
588
n589-* ``'replace'`` Replace with a suitable replacement character.
n600+   * ``'replace'`` Replace with a suitable replacement character.
590
591   The *errors* argument will be assigned to an attribute of the same name.
592   Assigning to this attribute makes it possible to switch between different error
593   handling strategies during the lifetime of the :class:`StreamReader` object.
594
595   The set of allowed values for the *errors* argument can be extended with
596   :func:`register_error`.
597
598
n599-.. method:: StreamReader.read([size[, chars, [firstline]]])
n610+   .. method:: read([size[, chars, [firstline]]])
600
n601-   Decodes data from the stream and returns the resulting object.
n612+      Decodes data from the stream and returns the resulting object.
602
n603-   *chars* indicates the number of characters to read from the stream. :func:`read`
n614+      *chars* indicates the number of characters to read from the
604-   will never return more than *chars* characters, but it might return less, if
615+      stream. :func:`read` will never return more than *chars* characters, but
605-   there are not enough characters available.
616+      it might return less, if there are not enough characters available.
606
n607-   *size* indicates the approximate maximum number of bytes to read from the stream
n618+      *size* indicates the approximate maximum number of bytes to read from the
608-   for decoding purposes. The decoder can modify this setting as appropriate. The
619+      stream for decoding purposes. The decoder can modify this setting as
609-   default value -1 indicates to read and decode as much as possible.  *size* is
620+      appropriate. The default value -1 indicates to read and decode as much as
610-   intended to prevent having to decode huge files in one step.
621+      possible.  *size* is intended to prevent having to decode huge files in
622+      one step.
611
n612-   *firstline* indicates that it would be sufficient to only return the first line,
n624+      *firstline* indicates that it would be sufficient to only return the first
613-   if there are decoding errors on later lines.
625+      line, if there are decoding errors on later lines.
614
n615-   The method should use a greedy read strategy meaning that it should read as much
n627+      The method should use a greedy read strategy meaning that it should read
616-   data as is allowed within the definition of the encoding and the given size,
628+      as much data as is allowed within the definition of the encoding and the
617-   e.g.  if optional encoding endings or state markers are available on the stream,
629+      given size, e.g.  if optional encoding endings or state markers are
618-   these should be read too.
630+      available on the stream, these should be read too.
619
n620-   .. versionchanged:: 2.4
n632+      .. versionchanged:: 2.4
621-      *chars* argument added.
633+         *chars* argument added.
622
n623-   .. versionchanged:: 2.4.2
n635+      .. versionchanged:: 2.4.2
624-      *firstline* argument added.
636+         *firstline* argument added.
625
626
n627-.. method:: StreamReader.readline([size[, keepends]])
n639+   .. method:: readline([size[, keepends]])
628
n629-   Read one line from the input stream and return the decoded data.
n641+      Read one line from the input stream and return the decoded data.
630
n631-   *size*, if given, is passed as size argument to the stream's :meth:`readline`
n643+      *size*, if given, is passed as size argument to the stream's
632-   method.
644+      :meth:`readline` method.
633
n634-   If *keepends* is false line-endings will be stripped from the lines returned.
n646+      If *keepends* is false line-endings will be stripped from the lines
647+      returned.
635
n636-   .. versionchanged:: 2.4
n649+      .. versionchanged:: 2.4
637-      *keepends* argument added.
650+         *keepends* argument added.
638
639
n640-.. method:: StreamReader.readlines([sizehint[, keepends]])
n653+   .. method:: readlines([sizehint[, keepends]])
641
n642-   Read all lines available on the input stream and return them as a list of lines.
n655+      Read all lines available on the input stream and return them as a list of
656+      lines.
643
n644-   Line-endings are implemented using the codec's decoder method and are included
n658+      Line-endings are implemented using the codec's decoder method and are
645-   in the list entries if *keepends* is true.
659+      included in the list entries if *keepends* is true.
646
n647-   *sizehint*, if given, is passed as the *size* argument to the stream's
n661+      *sizehint*, if given, is passed as the *size* argument to the stream's
648-   :meth:`read` method.
662+      :meth:`read` method.
649
650
n651-.. method:: StreamReader.reset()
n665+   .. method:: reset()
652
n653-   Resets the codec buffers used for keeping state.
n667+      Resets the codec buffers used for keeping state.
654
n655-   Note that no stream repositioning should take place.  This method is primarily
n669+      Note that no stream repositioning should take place.  This method is
656-   intended to be able to recover from decoding errors.
670+      primarily intended to be able to recover from decoding errors.
671+ 
657
658In addition to the above methods, the :class:`StreamReader` must also inherit
659all other methods and attributes from the underlying stream.
660
661The next two base classes are included for convenience. They are not needed by
662the codec registry, but may provide useful in practice.
663
664
717   *encode* and *decode* are needed for the frontend translation, *Reader* and
718   *Writer* for the backend translation.  The intermediate format used is
719   determined by the two sets of codecs, e.g. the Unicode codecs will use Unicode
720   as the intermediate encoding.
721
722   Error handling is done in the same way as defined for the stream readers and
723   writers.
724
n740+ 
725:class:`StreamRecoder` instances define the combined interfaces of
726:class:`StreamReader` and :class:`StreamWriter` classes. They inherit all other
727methods and attributes from the underlying stream.
728
729
730.. _encodings-overview:
731
732Encodings and Unicode
733---------------------
734
735Unicode strings are stored internally as sequences of codepoints (to be precise
736as :ctype:`Py_UNICODE` arrays). Depending on the way Python is compiled (either
n737-via :option:`--enable-unicode=ucs2` or  :option:`--enable-unicode=ucs4`, with
n753+via :option:`--enable-unicode=ucs2` or :option:`--enable-unicode=ucs4`, with the
738-the former being the default) :ctype:`Py_UNICODE` is either a 16-bit or 32-bit
754+former being the default) :ctype:`Py_UNICODE` is either a 16-bit or 32-bit data
739-data type. Once a Unicode object is used outside of CPU and memory, CPU
755+type. Once a Unicode object is used outside of CPU and memory, CPU endianness
740-endianness and how these arrays are stored as bytes become an issue.
756+and how these arrays are stored as bytes become an issue.  Transforming a
741-Transforming a unicode object into a sequence of bytes is called encoding and
757+unicode object into a sequence of bytes is called encoding and recreating the
742-recreating the unicode object from the sequence of bytes is known as decoding.
758+unicode object from the sequence of bytes is known as decoding.  There are many
743-There are many different methods for how this transformation can be done (these
759+different methods for how this transformation can be done (these methods are
744-methods are also called encodings). The simplest method is to map the codepoints
760+also called encodings). The simplest method is to map the codepoints 0-255 to
745-0-255 to the bytes ``0x0``-``0xff``. This means that a unicode object that
761+the bytes ``0x0``-``0xff``. This means that a unicode object that contains
746-contains  codepoints above ``U+00FF`` can't be encoded with this method (which
762+codepoints above ``U+00FF`` can't be encoded with this method (which is called
747-is called ``'latin-1'`` or ``'iso-8859-1'``). :func:`unicode.encode` will raise
763+``'latin-1'`` or ``'iso-8859-1'``). :func:`unicode.encode` will raise a
748-:exc:`UnicodeEncodeError` that looks like this: ``UnicodeEncodeError:
764+:exc:`UnicodeEncodeError` that looks like this: ``UnicodeEncodeError: 'latin-1'
749-'latin-1' codec can't encode character u'\u1234' in position 3: ordinal not in
765+codec can't encode character u'\u1234' in position 3: ordinal not in
750range(256)``.
751
752There's another group of encodings (the so called charmap encodings) that choose
753a different subset of all unicode code points and how these codepoints are
n754-mapped to the bytes ``0x0``-``0xff.`` To see how this is done simply open
n770+mapped to the bytes ``0x0``-``0xff``. To see how this is done simply open
755e.g. :file:`encodings/cp1252.py` (which is an encoding that is used primarily on
756Windows). There's a string constant with 256 characters that shows you which
757character is mapped to which byte value.
758
759All of these encodings can only encode 256 of the 65536 (or 1114111) codepoints
760defined in unicode. A simple and straightforward way that can store each Unicode
761code point, is to store each codepoint as two consecutive bytes. There are two
762possibilities: Store the bytes in big endian or in little endian order. These
811As UTF-8 is an 8-bit encoding no BOM is required and any ``U+FEFF`` character in
812the decoded Unicode string (even if it's the first character) is treated as a
813``ZERO WIDTH NO-BREAK SPACE``.
814
815Without external information it's impossible to reliably determine which
816encoding was used for encoding a Unicode string. Each charmap encoding can
817decode any random byte sequence. However that's not possible with UTF-8, as
818UTF-8 byte sequences have a structure that doesn't allow arbitrary byte
n819-sequence. To increase the reliability with which a UTF-8 encoding can be
n835+sequences. To increase the reliability with which a UTF-8 encoding can be
820detected, Microsoft invented a variant of UTF-8 (that Python 2.5 calls
821``"utf-8-sig"``) for its Notepad program: Before any of the Unicode characters
822is written to the file, a UTF-8 encoded BOM (which looks like this as a byte
823sequence: ``0xef``, ``0xbb``, ``0xbf``) is written. As it's rather improbable
824that any charmap encoded file starts with these byte values (which would e.g.
825map to
826
n827-LATIN SMALL LETTER I WITH DIAERESIS  ---  RIGHT-POINTING DOUBLE ANGLE QUOTATION
n843+   | LATIN SMALL LETTER I WITH DIAERESIS
844+   | RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK
828-MARK  ---  INVERTED QUESTION MARK
845+   | INVERTED QUESTION MARK
829
830in iso-8859-1), this increases the probability that a utf-8-sig encoding can be
831correctly guessed from the byte sequence. So here the BOM is not used to be able
832to determine the byte order used for generating the byte sequence, but as a
833signature that helps in guessing the encoding. On encoding the utf-8-sig codec
834will write ``0xef``, ``0xbb``, ``0xbf`` as the first three bytes to the file. On
835decoding utf-8-sig will skip those three bytes if they appear as the first three
836bytes in the file.
987+-----------------+--------------------------------+--------------------------------+
988| latin_1         | iso-8859-1, iso8859-1, 8859,   | West Europe                    |
989|                 | cp819, latin, latin1, L1       |                                |
990+-----------------+--------------------------------+--------------------------------+
991| iso8859_2       | iso-8859-2, latin2, L2         | Central and Eastern Europe     |
992+-----------------+--------------------------------+--------------------------------+
993| iso8859_3       | iso-8859-3, latin3, L3         | Esperanto, Maltese             |
994+-----------------+--------------------------------+--------------------------------+
n995-| iso8859_4       | iso-8859-4, latin4, L4         | Baltic languagues              |
n1012+| iso8859_4       | iso-8859-4, latin4, L4         | Baltic languages               |
996+-----------------+--------------------------------+--------------------------------+
997| iso8859_5       | iso-8859-5, cyrillic           | Bulgarian, Byelorussian,       |
998|                 |                                | Macedonian, Russian, Serbian   |
999+-----------------+--------------------------------+--------------------------------+
1000| iso8859_6       | iso-8859-6, arabic             | Arabic                         |
1001+-----------------+--------------------------------+--------------------------------+
1002| iso8859_7       | iso-8859-7, greek, greek8      | Greek                          |
1003+-----------------+--------------------------------+--------------------------------+
1038| shift_jis       | csshiftjis, shiftjis, sjis,    | Japanese                       |
1039|                 | s_jis                          |                                |
1040+-----------------+--------------------------------+--------------------------------+
1041| shift_jis_2004  | shiftjis2004, sjis_2004,       | Japanese                       |
1042|                 | sjis2004                       |                                |
1043+-----------------+--------------------------------+--------------------------------+
1044| shift_jisx0213  | shiftjisx0213, sjisx0213,      | Japanese                       |
1045|                 | s_jisx0213                     |                                |
n1063++-----------------+--------------------------------+--------------------------------+
1064+| utf_32          | U32, utf32                     | all languages                  |
1065++-----------------+--------------------------------+--------------------------------+
1066+| utf_32_be       | UTF-32BE                       | all languages                  |
1067++-----------------+--------------------------------+--------------------------------+
1068+| utf_32_le       | UTF-32LE                       | all languages                  |
1046+-----------------+--------------------------------+--------------------------------+
1047| utf_16          | U16, utf16                     | all languages                  |
1048+-----------------+--------------------------------+--------------------------------+
1049| utf_16_be       | UTF-16BE                       | all languages (BMP only)       |
1050+-----------------+--------------------------------+--------------------------------+
1051| utf_16_le       | UTF-16LE                       | all languages (BMP only)       |
1052+-----------------+--------------------------------+--------------------------------+
1053| utf_7           | U7, unicode-1-1-utf-7          | all languages                  |
1075| bz2_codec          | bz2                       | byte string    | Compress the operand      |
1076|                    |                           |                | using bz2                 |
1077+--------------------+---------------------------+----------------+---------------------------+
1078| hex_codec          | hex                       | byte string    | Convert operand to        |
1079|                    |                           |                | hexadecimal               |
1080|                    |                           |                | representation, with two  |
1081|                    |                           |                | digits per byte           |
1082+--------------------+---------------------------+----------------+---------------------------+
n1083-| idna               |                           | Unicode string | Implements :rfc:`3490`.   |
n1106+| idna               |                           | Unicode string | Implements :rfc:`3490`,   |
1084-|                    |                           |                | See also                  |
1107+|                    |                           |                | see also                  |
1085|                    |                           |                | :mod:`encodings.idna`     |
1086+--------------------+---------------------------+----------------+---------------------------+
1087| mbcs               | dbcs                      | Unicode string | Windows only: Encode      |
1088|                    |                           |                | operand according to the  |
1089|                    |                           |                | ANSI codepage (CP_ACP)    |
1090+--------------------+---------------------------+----------------+---------------------------+
1091| palmos             |                           | Unicode string | Encoding of PalmOS 3.5    |
1092+--------------------+---------------------------+----------------+---------------------------+
n1093-| punycode           |                           | Unicode string | Implements :rfc:`3492`.   |
n1116+| punycode           |                           | Unicode string | Implements :rfc:`3492`    |
1094+--------------------+---------------------------+----------------+---------------------------+
1095| quopri_codec       | quopri, quoted-printable, | byte string    | Convert operand to MIME   |
1096|                    | quotedprintable           |                | quoted printable          |
1097+--------------------+---------------------------+----------------+---------------------------+
1098| raw_unicode_escape |                           | Unicode string | Produce a string that is  |
1099|                    |                           |                | suitable as raw Unicode   |
1100|                    |                           |                | literal in Python source  |
1101|                    |                           |                | code                      |
1107|                    |                           |                | suitable as string        |
1108|                    |                           |                | literal in Python source  |
1109|                    |                           |                | code                      |
1110+--------------------+---------------------------+----------------+---------------------------+
1111| undefined          |                           | any            | Raise an exception for    |
1112|                    |                           |                | all conversions. Can be   |
1113|                    |                           |                | used as the system        |
1114|                    |                           |                | encoding if no automatic  |
n1115-|                    |                           |                | coercion between byte and |
n1138+|                    |                           |                | :term:`coercion` between  |
1116-|                    |                           |                | Unicode strings is        |
1139+|                    |                           |                | byte and Unicode strings  |
1117-|                    |                           |                | desired.                  |
1140+|                    |                           |                | is desired.               |
1118+--------------------+---------------------------+----------------+---------------------------+
1119| unicode_escape     |                           | Unicode string | Produce a string that is  |
1120|                    |                           |                | suitable as Unicode       |
1121|                    |                           |                | literal in Python source  |
1122|                    |                           |                | code                      |
1123+--------------------+---------------------------+----------------+---------------------------+
1124| unicode_internal   |                           | Unicode string | Return the internal       |
1125|                    |                           |                | representation of the     |
1127+--------------------+---------------------------+----------------+---------------------------+
1128| uu_codec           | uu                        | byte string    | Convert the operand using |
1129|                    |                           |                | uuencode                  |
1130+--------------------+---------------------------+----------------+---------------------------+
1131| zlib_codec         | zip, zlib                 | byte string    | Compress the operand      |
1132|                    |                           |                | using gzip                |
1133+--------------------+---------------------------+----------------+---------------------------+
1134
n1158+.. versionadded:: 2.3
1159+   The ``idna`` and ``punycode`` encodings.
1160+ 
1135
1136:mod:`encodings.idna` --- Internationalized Domain Names in Applications
1137------------------------------------------------------------------------
1138
1139.. module:: encodings.idna
1140   :synopsis: Internationalized Domain Names implementation
n1141- 
1142- 
1143-.. % XXX The next line triggers a formatting bug, so it's commented out
1144-.. % until that can be fixed.
1145-.. % \moduleauthor{Martin v. L\"owis}
1167+.. moduleauthor:: Martin v. Löwis
1146
1147.. versionadded:: 2.3
1148
1149This module implements :rfc:`3490` (Internationalized Domain Names in
1150Applications) and :rfc:`3492` (Nameprep: A Stringprep Profile for
1151Internationalized Domain Names (IDN)). It builds upon the ``punycode`` encoding
1152and :mod:`stringprep`.
1153
1154These RFCs together define a protocol to support non-ASCII characters in domain
1155names. A domain name containing non-ASCII characters (such as
n1156-"www.Alliancefrançaise.nu") is converted into an ASCII-compatible encoding (ACE,
n1178+``www.Alliancefrançaise.nu``) is converted into an ASCII-compatible encoding
1157-such as "www.xn--alliancefranaise-npb.nu"). The ACE form of the domain name is
1179+(ACE, such as ``www.xn--alliancefranaise-npb.nu``). The ACE form of the domain
1158-then used in all places where arbitrary characters are not allowed by the
1180+name is then used in all places where arbitrary characters are not allowed by
1159-protocol, such as DNS queries, HTTP :mailheader:`Host` fields, and so on. This
1181+the protocol, such as DNS queries, HTTP :mailheader:`Host` fields, and so
1160-conversion is carried out in the application; if possible invisible to the user:
1182+on. This conversion is carried out in the application; if possible invisible to
1161-The application should transparently convert Unicode domain labels to IDNA on
1183+the user: The application should transparently convert Unicode domain labels to
1162-the wire, and convert back ACE labels to Unicode before presenting them to the
1184+IDNA on the wire, and convert back ACE labels to Unicode before presenting them
1163-user.
1185+to the user.
1164
1165Python supports this conversion in several ways: The ``idna`` codec allows to
1166convert between Unicode and the ACE. Furthermore, the :mod:`socket` module
1167transparently converts Unicode host names to ACE, so that applications need not
1168be concerned about converting host names themselves when they pass them to the
1169socket module. On top of that, modules that have host names as function
1170parameters, such as :mod:`httplib` and :mod:`ftplib`, accept Unicode host names
1171(:mod:`httplib` then also transparently sends an IDNA hostname in the
1196.. function:: ToUnicode(label)
1197
1198   Convert a label to Unicode, as specified in :rfc:`3490`.
1199
1200
1201:mod:`encodings.utf_8_sig` --- UTF-8 codec with BOM signature
1202-------------------------------------------------------------
1203
n1204-.. module:: encodings.utf-8-sig
n1226+.. module:: encodings.utf_8_sig
1205   :synopsis: UTF-8 codec with BOM signature
1206.. moduleauthor:: Walter Dörwald
t1207- 
1208- 
1209-.. % XXX utf_8_sig gives TeX errors
1210
1211.. versionadded:: 2.5
1212
1213This module implements a variant of the UTF-8 codec: On encoding a UTF-8 encoded
1214BOM will be prepended to the UTF-8 encoded bytes. For the stateful encoder this
1215is only done once (on the first write to the byte stream).  For decoding an
1216optional UTF-8 encoded BOM at the start of the data will be skipped.
1217
Legends
Colors
 Added 
Changed
Deleted
Links
(f)irst change
(n)ext change
(t)op