2 :mod:`codecs` --- Codec registry and base classes
3 =================================================
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>
18 pair: stackable; streams
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.
24 It defines the following functions:
27 .. function:: register(search_function)
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:
33 * ``name`` The name of the encoding;
35 * ``encode`` The stateless encoding function;
37 * ``decode`` The stateless decoding function;
39 * ``incrementalencoder`` An incremental encoder class or factory function;
41 * ``incrementaldecoder`` An incremental decoder class or factory function;
43 * ``streamwriter`` A stream writer class or factory function;
45 * ``streamreader`` A stream reader class or factory function.
47 The various functions or classes take the following arguments:
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
54 *incrementalencoder* and *incrementaldecoder*: These have to be factory
55 functions providing the following interface:
57 ``factory(errors='strict')``
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.
63 *streamreader* and *streamwriter*: These have to be factory functions providing
64 the following interface:
66 ``factory(stream, errors='strict')``
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.
72 Possible values for errors are
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
83 as well as any other error handling name defined via :func:`register_error`.
85 In case a search function cannot find a given encoding, it should return
89 .. function:: lookup(encoding)
91 Looks up the codec info in the Python codec registry and returns a
92 :class:`CodecInfo` object as defined above.
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.
99 To simplify access to the various codecs, the module provides these additional
100 functions which use :func:`lookup` for the codec lookup:
103 .. function:: getencoder(encoding)
105 Look up the codec for the given encoding and return its encoder function.
107 Raises a :exc:`LookupError` in case the encoding cannot be found.
110 .. function:: getdecoder(encoding)
112 Look up the codec for the given encoding and return its decoder function.
114 Raises a :exc:`LookupError` in case the encoding cannot be found.
117 .. function:: getincrementalencoder(encoding)
119 Look up the codec for the given encoding and return its incremental encoder
120 class or factory function.
122 Raises a :exc:`LookupError` in case the encoding cannot be found or the codec
123 doesn't support an incremental encoder.
125 .. versionadded:: 2.5
128 .. function:: getincrementaldecoder(encoding)
130 Look up the codec for the given encoding and return its incremental decoder
131 class or factory function.
133 Raises a :exc:`LookupError` in case the encoding cannot be found or the codec
134 doesn't support an incremental decoder.
136 .. versionadded:: 2.5
139 .. function:: getreader(encoding)
141 Look up the codec for the given encoding and return its StreamReader class or
144 Raises a :exc:`LookupError` in case the encoding cannot be found.
147 .. function:: getwriter(encoding)
149 Look up the codec for the given encoding and return its StreamWriter class or
152 Raises a :exc:`LookupError` in case the encoding cannot be found.
155 .. function:: register_error(name, error_handler)
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.
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.
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.
175 .. function:: lookup_error(name)
177 Return the error handler previously registered under the name *name*.
179 Raises a :exc:`LookupError` in case the handler cannot be found.
182 .. function:: strict_errors(exception)
184 Implements the ``strict`` error handling: each encoding or decoding error
185 raises a :exc:`UnicodeError`.
188 .. function:: replace_errors(exception)
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.
195 .. function:: ignore_errors(exception)
197 Implements the ``ignore`` error handling: malformed data is ignored and
198 encoding or decoding is continued without further notice.
201 .. function:: xmlcharrefreplace_errors(exception)
203 Implements the ``xmlcharrefreplace`` error handling (for encoding only): the
204 unencodable character is replaced by an appropriate XML character reference.
207 .. function:: backslashreplace_errors(exception)
209 Implements the ``backslashreplace`` error handling (for encoding only): the
210 unencodable character is replaced by a backslashed escape sequence.
212 To simplify working with encoded files or stream, the module also defines these
216 .. function:: open(filename, mode[, encoding[, errors[, buffering]]])
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.
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.
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.
235 *encoding* specifies the encoding which is to be used for the file.
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.
240 *buffering* has the same meaning as for the built-in :func:`open` function. It
241 defaults to line buffered.
244 .. function:: EncodedFile(file, input[, output[, errors]])
246 Return a wrapped version of file which provides transparent encoding
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.
254 If *output* is not given, it defaults to *input*.
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.
260 .. function:: iterencode(iterable, encoding[, errors])
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.
266 .. versionadded:: 2.5
269 .. function:: iterdecode(iterable, encoding[, errors])
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.
275 .. versionadded:: 2.5
277 The module also provides the following constants which are useful for reading
278 and writing to platform dependent files:
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
302 .. _codec-base-classes:
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
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.
316 The :class:`Codec` class defines the interface for stateless encoders/decoders.
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:
323 +-------------------------+-----------------------------------------------+
325 +=========================+===============================================+
326 | ``'strict'`` | Raise :exc:`UnicodeError` (or a subclass); |
327 | | this is the default. |
328 +-------------------------+-----------------------------------------------+
329 | ``'ignore'`` | Ignore the character and continue with the |
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 |
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 +-------------------------+-----------------------------------------------+
345 The set of allowed values can be extended via :meth:`register_error`.
353 The :class:`Codec` class defines these methods which also define the function
354 interfaces of the stateless encoder and decoder:
357 .. method:: Codec.encode(input[, errors])
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``).
364 *errors* defines the error handling to apply. It defaults to ``'strict'``
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.
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.
375 .. method:: Codec.decode(input[, errors])
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.
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
385 *errors* defines the error handling to apply. It defaults to ``'strict'``
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.
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.
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.
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.
407 .. _incremental-encoder-objects:
409 IncrementalEncoder Objects
410 ^^^^^^^^^^^^^^^^^^^^^^^^^^
412 .. versionadded:: 2.5
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.
419 .. class:: IncrementalEncoder([errors])
421 Constructor for an :class:`IncrementalEncoder` instance.
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.
427 The :class:`IncrementalEncoder` may implement different error handling schemes
428 by providing the *errors* keyword argument. These parameters are predefined:
430 * ``'strict'`` Raise :exc:`ValueError` (or a subclass); this is the default.
432 * ``'ignore'`` Ignore the character and continue with the next.
434 * ``'replace'`` Replace with a suitable replacement character
436 * ``'xmlcharrefreplace'`` Replace with the appropriate XML character reference
438 * ``'backslashreplace'`` Replace with backslashed escape sequences.
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`
445 The set of allowed values for the *errors* argument can be extended with
446 :func:`register_error`.
449 .. method:: encode(object[, final])
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).
458 Reset the encoder to the initial state.
461 .. _incremental-decoder-objects:
463 IncrementalDecoder Objects
464 ^^^^^^^^^^^^^^^^^^^^^^^^^^
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.
471 .. class:: IncrementalDecoder([errors])
473 Constructor for an :class:`IncrementalDecoder` instance.
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.
479 The :class:`IncrementalDecoder` may implement different error handling schemes
480 by providing the *errors* keyword argument. These parameters are predefined:
482 * ``'strict'`` Raise :exc:`ValueError` (or a subclass); this is the default.
484 * ``'ignore'`` Ignore the character and continue with the next.
486 * ``'replace'`` Replace with a suitable replacement character.
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`
493 The set of allowed values for the *errors* argument can be extended with
494 :func:`register_error`.
497 .. method:: decode(object[, final])
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).
510 Reset the decoder to the initial state.
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.
518 .. _stream-writer-objects:
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.
528 .. class:: StreamWriter(stream[, errors])
530 Constructor for a :class:`StreamWriter` instance.
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.
536 *stream* must be a file-like object open for writing binary data.
538 The :class:`StreamWriter` may implement different error handling schemes by
539 providing the *errors* keyword argument. These parameters are predefined:
541 * ``'strict'`` Raise :exc:`ValueError` (or a subclass); this is the default.
543 * ``'ignore'`` Ignore the character and continue with the next.
545 * ``'replace'`` Replace with a suitable replacement character
547 * ``'xmlcharrefreplace'`` Replace with the appropriate XML character reference
549 * ``'backslashreplace'`` Replace with backslashed escape sequences.
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.
555 The set of allowed values for the *errors* argument can be extended with
556 :func:`register_error`.
559 .. method:: write(object)
561 Writes the object's contents encoded to the stream.
564 .. method:: writelines(list)
566 Writes the concatenated list of strings to the stream (possibly by reusing
567 the :meth:`write` method).
572 Flushes and resets the codec buffers used for keeping state.
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.
579 In addition to the above methods, the :class:`StreamWriter` must also inherit
580 all other methods and attributes from the underlying stream.
583 .. _stream-reader-objects:
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.
593 .. class:: StreamReader(stream[, errors])
595 Constructor for a :class:`StreamReader` instance.
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.
601 *stream* must be a file-like object open for reading (binary) data.
603 The :class:`StreamReader` may implement different error handling schemes by
604 providing the *errors* keyword argument. These parameters are defined:
606 * ``'strict'`` Raise :exc:`ValueError` (or a subclass); this is the default.
608 * ``'ignore'`` Ignore the character and continue with the next.
610 * ``'replace'`` Replace with a suitable replacement character.
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.
616 The set of allowed values for the *errors* argument can be extended with
617 :func:`register_error`.
620 .. method:: read([size[, chars, [firstline]]])
622 Decodes data from the stream and returns the resulting object.
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.
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
634 *firstline* indicates that it would be sufficient to only return the first
635 line, if there are decoding errors on later lines.
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.
642 .. versionchanged:: 2.4
643 *chars* argument added.
645 .. versionchanged:: 2.4.2
646 *firstline* argument added.
649 .. method:: readline([size[, keepends]])
651 Read one line from the input stream and return the decoded data.
653 *size*, if given, is passed as size argument to the stream's
654 :meth:`readline` method.
656 If *keepends* is false line-endings will be stripped from the lines
659 .. versionchanged:: 2.4
660 *keepends* argument added.
663 .. method:: readlines([sizehint[, keepends]])
665 Read all lines available on the input stream and return them as a list of
668 Line-endings are implemented using the codec's decoder method and are
669 included in the list entries if *keepends* is true.
671 *sizehint*, if given, is passed as the *size* argument to the stream's
677 Resets the codec buffers used for keeping state.
679 Note that no stream repositioning should take place. This method is
680 primarily intended to be able to recover from decoding errors.
683 In addition to the above methods, the :class:`StreamReader` must also inherit
684 all other methods and attributes from the underlying stream.
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.
690 .. _stream-reader-writer:
692 StreamReaderWriter Objects
693 ^^^^^^^^^^^^^^^^^^^^^^^^^^
695 The :class:`StreamReaderWriter` allows wrapping streams which work in both read
698 The design is such that one can use the factory functions returned by the
699 :func:`lookup` function to construct the instance.
702 .. class:: StreamReaderWriter(stream, Reader, Writer, errors)
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.
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.
714 .. _stream-recoder-objects:
716 StreamRecoder Objects
717 ^^^^^^^^^^^^^^^^^^^^^
719 The :class:`StreamRecoder` provide a frontend - backend view of encoding data
720 which is sometimes useful when dealing with different encoding environments.
722 The design is such that one can use the factory functions returned by the
723 :func:`lookup` function to construct the instance.
726 .. class:: StreamRecoder(stream, encode, decode, Reader, Writer, errors)
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).
733 You can use these objects to do transparent direct recodings from e.g. Latin-1
736 *stream* must be a file-like object.
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.
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.
747 Error handling is done in the same way as defined for the stream readers and
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.
756 .. _encodings-overview:
758 Encodings and Unicode
759 ---------------------
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
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.
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.
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
819 +-----------------------------------+----------------------------------------------+
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 +-----------------------------------+----------------------------------------------+
831 The least significant bit of the Unicode character is the rightmost x bit.
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``.
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.
849 | LATIN SMALL LETTER I WITH DIAERESIS
850 | RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK
851 | INVERTED QUESTION MARK
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.
863 .. _standard-encodings:
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.
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:
881 * an ISO 8859 codeset
883 * a Microsoft Windows code page, which is typically derived from a 8859 codeset,
884 but replaces control characters with additional graphic characters
886 * an IBM EBCDIC code page
888 * an IBM PC code page, which is ASCII compatible
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 |
907 +-----------------+--------------------------------+--------------------------------+
909 +-----------------+--------------------------------+--------------------------------+
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 +-----------------+--------------------------------+--------------------------------+
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 +-----------------+--------------------------------+--------------------------------+
944 +-----------------+--------------------------------+--------------------------------+
946 +-----------------+--------------------------------+--------------------------------+
947 | cp932 | 932, ms932, mskanji, ms-kanji | Japanese |
948 +-----------------+--------------------------------+--------------------------------+
949 | cp949 | 949, ms949, uhc | Korean |
950 +-----------------+--------------------------------+--------------------------------+
951 | cp950 | 950, ms950 | Traditional Chinese |
952 +-----------------+--------------------------------+--------------------------------+
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- | |
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 |
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 |
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 |
1071 +-----------------+--------------------------------+--------------------------------+
1072 | shift_jis_2004 | shiftjis2004, sjis_2004, | Japanese |
1074 +-----------------+--------------------------------+--------------------------------+
1075 | shift_jisx0213 | shiftjisx0213, sjisx0213, | Japanese |
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 +-----------------+--------------------------------+--------------------------------+
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.
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
1106 +--------------------+---------------------------+----------------+---------------------------+
1107 | Codec | Aliases | Operand type | Purpose |
1108 +====================+===========================+================+===========================+
1109 | base64_codec | base64, base-64 | byte string | Convert operand to MIME |
1111 +--------------------+---------------------------+----------------+---------------------------+
1112 | bz2_codec | bz2 | byte string | Compress the operand |
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`, |
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 |
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 |
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 |
1160 +--------------------+---------------------------+----------------+---------------------------+
1161 | unicode_internal | | Unicode string | Return the internal |
1162 | | | | representation of the |
1164 +--------------------+---------------------------+----------------+---------------------------+
1165 | uu_codec | uu | byte string | Convert the operand using |
1167 +--------------------+---------------------------+----------------+---------------------------+
1168 | zlib_codec | zip, zlib | byte string | Compress the operand |
1169 | | | | using gzip |
1170 +--------------------+---------------------------+----------------+---------------------------+
1172 .. versionadded:: 2.3
1173 The ``idna`` and ``punycode`` encodings.
1176 :mod:`encodings.idna` --- Internationalized Domain Names in Applications
1177 ------------------------------------------------------------------------
1179 .. module:: encodings.idna
1180 :synopsis: Internationalized Domain Names implementation
1181 .. moduleauthor:: Martin v. Löwis
1183 .. versionadded:: 2.3
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`.
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
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).
1214 .. _section 3.1: http://tools.ietf.org/html/rfc3490#section-3.1
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.
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.
1226 .. function:: nameprep(label)
1228 Return the nameprepped version of *label*. The implementation currently assumes
1229 query strings, so ``AllowUnassigned`` is true.
1232 .. function:: ToASCII(label)
1234 Convert a label to ASCII, as specified in :rfc:`3490`. ``UseSTD3ASCIIRules`` is
1235 assumed to be false.
1238 .. function:: ToUnicode(label)
1240 Convert a label to Unicode, as specified in :rfc:`3490`.
1243 :mod:`encodings.utf_8_sig` --- UTF-8 codec with BOM signature
1244 -------------------------------------------------------------
1246 .. module:: encodings.utf_8_sig
1247 :synopsis: UTF-8 codec with BOM signature
1248 .. moduleauthor:: Walter Dörwald
1250 .. versionadded:: 2.5
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.