blob: c6b6a56e433e3e619986fa33a62690c27bd6b967 [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +00001:mod:`codecs` --- Codec registry and base classes
2=================================================
3
4.. module:: codecs
5 :synopsis: Encode and decode data and streams.
Terry Jan Reedyfa089b92016-06-11 15:02:54 -04006
Antoine Pitroufbd4f802012-08-11 16:51:50 +02007.. moduleauthor:: Marc-André Lemburg <mal@lemburg.com>
8.. sectionauthor:: Marc-André Lemburg <mal@lemburg.com>
Georg Brandl116aa622007-08-15 14:28:22 +00009.. sectionauthor:: Martin v. Löwis <martin@v.loewis.de>
10
Andrew Kuchling2e3743c2014-03-19 16:23:01 -040011**Source code:** :source:`Lib/codecs.py`
Georg Brandl116aa622007-08-15 14:28:22 +000012
13.. index::
14 single: Unicode
15 single: Codecs
16 pair: Codecs; encode
17 pair: Codecs; decode
18 single: streams
19 pair: stackable; streams
20
Terry Jan Reedyfa089b92016-06-11 15:02:54 -040021--------------
22
Georg Brandl116aa622007-08-15 14:28:22 +000023This module defines base classes for standard Python codecs (encoders and
Nick Coghlanb9fdb7a2015-01-07 00:22:00 +100024decoders) and provides access to the internal Python codec registry, which
25manages the codec and error handling lookup process. Most standard codecs
26are :term:`text encodings <text encoding>`, which encode text to bytes,
27but there are also codecs provided that encode text to text, and bytes to
28bytes. Custom codecs may encode and decode between arbitrary types, but some
29module features are restricted to use specifically with
30:term:`text encodings <text encoding>`, or with codecs that encode to
31:class:`bytes`.
Georg Brandl116aa622007-08-15 14:28:22 +000032
Nick Coghlanb9fdb7a2015-01-07 00:22:00 +100033The module defines the following functions for encoding and decoding with
34any codec:
Georg Brandl116aa622007-08-15 14:28:22 +000035
Nick Coghlan6cb2b5b2013-10-14 00:22:13 +100036.. function:: encode(obj, encoding='utf-8', errors='strict')
37
38 Encodes *obj* using the codec registered for *encoding*.
39
40 *Errors* may be given to set the desired error handling scheme. The
Nick Coghlanb9fdb7a2015-01-07 00:22:00 +100041 default error handler is ``'strict'`` meaning that encoding errors raise
Nick Coghlan6cb2b5b2013-10-14 00:22:13 +100042 :exc:`ValueError` (or a more codec specific subclass, such as
43 :exc:`UnicodeEncodeError`). Refer to :ref:`codec-base-classes` for more
44 information on codec error handling.
45
46.. function:: decode(obj, encoding='utf-8', errors='strict')
47
48 Decodes *obj* using the codec registered for *encoding*.
49
50 *Errors* may be given to set the desired error handling scheme. The
Nick Coghlanb9fdb7a2015-01-07 00:22:00 +100051 default error handler is ``'strict'`` meaning that decoding errors raise
Nick Coghlan6cb2b5b2013-10-14 00:22:13 +100052 :exc:`ValueError` (or a more codec specific subclass, such as
53 :exc:`UnicodeDecodeError`). Refer to :ref:`codec-base-classes` for more
54 information on codec error handling.
Georg Brandl116aa622007-08-15 14:28:22 +000055
Nick Coghlanb9fdb7a2015-01-07 00:22:00 +100056The full details for each codec can also be looked up directly:
Georg Brandl116aa622007-08-15 14:28:22 +000057
58.. function:: lookup(encoding)
59
60 Looks up the codec info in the Python codec registry and returns a
Nick Coghlanb9fdb7a2015-01-07 00:22:00 +100061 :class:`CodecInfo` object as defined below.
Georg Brandl116aa622007-08-15 14:28:22 +000062
63 Encodings are first looked up in the registry's cache. If not found, the list of
64 registered search functions is scanned. If no :class:`CodecInfo` object is
65 found, a :exc:`LookupError` is raised. Otherwise, the :class:`CodecInfo` object
66 is stored in the cache and returned to the caller.
67
Nick Coghlanb9fdb7a2015-01-07 00:22:00 +100068.. class:: CodecInfo(encode, decode, streamreader=None, streamwriter=None, incrementalencoder=None, incrementaldecoder=None, name=None)
Georg Brandl116aa622007-08-15 14:28:22 +000069
Nick Coghlanb9fdb7a2015-01-07 00:22:00 +100070 Codec details when looking up the codec registry. The constructor
71 arguments are stored in attributes of the same name:
72
73
74 .. attribute:: name
75
76 The name of the encoding.
77
78
79 .. attribute:: encode
80 decode
81
82 The stateless encoding and decoding functions. These must be
83 functions or methods which have the same interface as
84 the :meth:`~Codec.encode` and :meth:`~Codec.decode` methods of Codec
85 instances (see :ref:`Codec Interface <codec-objects>`).
86 The functions or methods are expected to work in a stateless mode.
87
88
89 .. attribute:: incrementalencoder
90 incrementaldecoder
91
92 Incremental encoder and decoder classes or factory functions.
93 These have to provide the interface defined by the base classes
94 :class:`IncrementalEncoder` and :class:`IncrementalDecoder`,
95 respectively. Incremental codecs can maintain state.
96
97
98 .. attribute:: streamwriter
99 streamreader
100
101 Stream writer and reader classes or factory functions. These have to
102 provide the interface defined by the base classes
103 :class:`StreamWriter` and :class:`StreamReader`, respectively.
104 Stream codecs can maintain state.
105
106To simplify access to the various codec components, the module provides
107these additional functions which use :func:`lookup` for the codec lookup:
Georg Brandl116aa622007-08-15 14:28:22 +0000108
109.. function:: getencoder(encoding)
110
111 Look up the codec for the given encoding and return its encoder function.
112
113 Raises a :exc:`LookupError` in case the encoding cannot be found.
114
115
116.. function:: getdecoder(encoding)
117
118 Look up the codec for the given encoding and return its decoder function.
119
120 Raises a :exc:`LookupError` in case the encoding cannot be found.
121
122
123.. function:: getincrementalencoder(encoding)
124
125 Look up the codec for the given encoding and return its incremental encoder
126 class or factory function.
127
128 Raises a :exc:`LookupError` in case the encoding cannot be found or the codec
129 doesn't support an incremental encoder.
130
Georg Brandl116aa622007-08-15 14:28:22 +0000131
132.. function:: getincrementaldecoder(encoding)
133
134 Look up the codec for the given encoding and return its incremental decoder
135 class or factory function.
136
137 Raises a :exc:`LookupError` in case the encoding cannot be found or the codec
138 doesn't support an incremental decoder.
139
Georg Brandl116aa622007-08-15 14:28:22 +0000140
141.. function:: getreader(encoding)
142
Berker Peksag732ba822016-05-21 14:56:35 +0300143 Look up the codec for the given encoding and return its :class:`StreamReader`
144 class or factory function.
Georg Brandl116aa622007-08-15 14:28:22 +0000145
146 Raises a :exc:`LookupError` in case the encoding cannot be found.
147
148
149.. function:: getwriter(encoding)
150
Berker Peksag732ba822016-05-21 14:56:35 +0300151 Look up the codec for the given encoding and return its :class:`StreamWriter`
152 class or factory function.
Georg Brandl116aa622007-08-15 14:28:22 +0000153
154 Raises a :exc:`LookupError` in case the encoding cannot be found.
155
Nick Coghlanb9fdb7a2015-01-07 00:22:00 +1000156Custom codecs are made available by registering a suitable codec search
157function:
Georg Brandl116aa622007-08-15 14:28:22 +0000158
Nick Coghlanb9fdb7a2015-01-07 00:22:00 +1000159.. function:: register(search_function)
Georg Brandl116aa622007-08-15 14:28:22 +0000160
Nick Coghlanb9fdb7a2015-01-07 00:22:00 +1000161 Register a codec search function. Search functions are expected to take one
162 argument, being the encoding name in all lower case letters, and return a
163 :class:`CodecInfo` object. In case a search function cannot find
164 a given encoding, it should return ``None``.
Georg Brandl116aa622007-08-15 14:28:22 +0000165
166 .. note::
167
Nick Coghlanb9fdb7a2015-01-07 00:22:00 +1000168 Search function registration is not currently reversible,
169 which may cause problems in some cases, such as unit testing or
170 module reloading.
171
172While the builtin :func:`open` and the associated :mod:`io` module are the
173recommended approach for working with encoded text files, this module
174provides additional utility functions and classes that allow the use of a
175wider range of codecs when working with binary files:
176
177.. function:: open(filename, mode='r', encoding=None, errors='strict', buffering=1)
178
179 Open an encoded file using the given *mode* and return an instance of
180 :class:`StreamReaderWriter`, providing transparent encoding/decoding.
181 The default file mode is ``'r'``, meaning to open the file in read mode.
Georg Brandl116aa622007-08-15 14:28:22 +0000182
Christian Heimes18c66892008-02-17 13:31:39 +0000183 .. note::
184
Nick Coghlanb9fdb7a2015-01-07 00:22:00 +1000185 Underlying encoded files are always opened in binary mode.
186 No automatic conversion of ``'\n'`` is done on reading and writing.
187 The *mode* argument may be any binary mode acceptable to the built-in
188 :func:`open` function; the ``'b'`` is automatically added.
Christian Heimes18c66892008-02-17 13:31:39 +0000189
Georg Brandl116aa622007-08-15 14:28:22 +0000190 *encoding* specifies the encoding which is to be used for the file.
Nick Coghlanb9fdb7a2015-01-07 00:22:00 +1000191 Any encoding that encodes to and decodes from bytes is allowed, and
192 the data types supported by the file methods depend on the codec used.
Georg Brandl116aa622007-08-15 14:28:22 +0000193
194 *errors* may be given to define the error handling. It defaults to ``'strict'``
195 which causes a :exc:`ValueError` to be raised in case an encoding error occurs.
196
197 *buffering* has the same meaning as for the built-in :func:`open` function. It
198 defaults to line buffered.
199
200
Georg Brandl0d8f0732009-04-05 22:20:44 +0000201.. function:: EncodedFile(file, data_encoding, file_encoding=None, errors='strict')
Georg Brandl116aa622007-08-15 14:28:22 +0000202
Nick Coghlanb9fdb7a2015-01-07 00:22:00 +1000203 Return a :class:`StreamRecoder` instance, a wrapped version of *file*
204 which provides transparent transcoding. The original file is closed
205 when the wrapped version is closed.
Georg Brandl116aa622007-08-15 14:28:22 +0000206
Nick Coghlanb9fdb7a2015-01-07 00:22:00 +1000207 Data written to the wrapped file is decoded according to the given
208 *data_encoding* and then written to the original file as bytes using
209 *file_encoding*. Bytes read from the original file are decoded
210 according to *file_encoding*, and the result is encoded
211 using *data_encoding*.
Georg Brandl116aa622007-08-15 14:28:22 +0000212
Georg Brandl0d8f0732009-04-05 22:20:44 +0000213 If *file_encoding* is not given, it defaults to *data_encoding*.
Georg Brandl116aa622007-08-15 14:28:22 +0000214
Georg Brandl0d8f0732009-04-05 22:20:44 +0000215 *errors* may be given to define the error handling. It defaults to
216 ``'strict'``, which causes :exc:`ValueError` to be raised in case an encoding
217 error occurs.
Georg Brandl116aa622007-08-15 14:28:22 +0000218
219
Georg Brandl0d8f0732009-04-05 22:20:44 +0000220.. function:: iterencode(iterator, encoding, errors='strict', **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +0000221
222 Uses an incremental encoder to iteratively encode the input provided by
Nick Coghlanb9fdb7a2015-01-07 00:22:00 +1000223 *iterator*. This function is a :term:`generator`.
224 The *errors* argument (as well as any
Georg Brandl9afde1c2007-11-01 20:32:30 +0000225 other keyword argument) is passed through to the incremental encoder.
Georg Brandl116aa622007-08-15 14:28:22 +0000226
Georg Brandl116aa622007-08-15 14:28:22 +0000227
Georg Brandl0d8f0732009-04-05 22:20:44 +0000228.. function:: iterdecode(iterator, encoding, errors='strict', **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +0000229
230 Uses an incremental decoder to iteratively decode the input provided by
Nick Coghlanb9fdb7a2015-01-07 00:22:00 +1000231 *iterator*. This function is a :term:`generator`.
232 The *errors* argument (as well as any
Georg Brandl9afde1c2007-11-01 20:32:30 +0000233 other keyword argument) is passed through to the incremental decoder.
Georg Brandl116aa622007-08-15 14:28:22 +0000234
Georg Brandl0d8f0732009-04-05 22:20:44 +0000235
Georg Brandl116aa622007-08-15 14:28:22 +0000236The module also provides the following constants which are useful for reading
237and writing to platform dependent files:
238
239
240.. data:: BOM
241 BOM_BE
242 BOM_LE
243 BOM_UTF8
244 BOM_UTF16
245 BOM_UTF16_BE
246 BOM_UTF16_LE
247 BOM_UTF32
248 BOM_UTF32_BE
249 BOM_UTF32_LE
250
Nick Coghlanb9fdb7a2015-01-07 00:22:00 +1000251 These constants define various byte sequences,
252 being Unicode byte order marks (BOMs) for several encodings. They are
253 used in UTF-16 and UTF-32 data streams to indicate the byte order used,
254 and in UTF-8 as a Unicode signature. :const:`BOM_UTF16` is either
Georg Brandl116aa622007-08-15 14:28:22 +0000255 :const:`BOM_UTF16_BE` or :const:`BOM_UTF16_LE` depending on the platform's
256 native byte order, :const:`BOM` is an alias for :const:`BOM_UTF16`,
257 :const:`BOM_LE` for :const:`BOM_UTF16_LE` and :const:`BOM_BE` for
258 :const:`BOM_UTF16_BE`. The others represent the BOM in UTF-8 and UTF-32
259 encodings.
260
261
262.. _codec-base-classes:
263
264Codec Base Classes
265------------------
266
267The :mod:`codecs` module defines a set of base classes which define the
Nick Coghlanb9fdb7a2015-01-07 00:22:00 +1000268interfaces for working with codec objects, and can also be used as the basis
269for custom codec implementations.
Georg Brandl116aa622007-08-15 14:28:22 +0000270
271Each codec has to define four interfaces to make it usable as codec in Python:
272stateless encoder, stateless decoder, stream reader and stream writer. The
273stream reader and writers typically reuse the stateless encoder/decoder to
Nick Coghlanb9fdb7a2015-01-07 00:22:00 +1000274implement the file protocols. Codec authors also need to define how the
275codec will handle encoding and decoding errors.
Georg Brandl116aa622007-08-15 14:28:22 +0000276
Georg Brandl116aa622007-08-15 14:28:22 +0000277
Nick Coghlanf2126362015-01-07 13:14:47 +1000278.. _surrogateescape:
Nick Coghlanb9fdb7a2015-01-07 00:22:00 +1000279.. _error-handlers:
280
281Error Handlers
282^^^^^^^^^^^^^^
283
284To simplify and standardize error handling,
285codecs may implement different error handling schemes by
286accepting the *errors* string argument. The following string values are
287defined and implemented by all standard Python codecs:
Georg Brandl116aa622007-08-15 14:28:22 +0000288
Georg Brandl44ea77b2013-03-28 13:28:44 +0100289.. tabularcolumns:: |l|L|
290
Georg Brandl116aa622007-08-15 14:28:22 +0000291+-------------------------+-----------------------------------------------+
292| Value | Meaning |
293+=========================+===============================================+
294| ``'strict'`` | Raise :exc:`UnicodeError` (or a subclass); |
Nick Coghlanb9fdb7a2015-01-07 00:22:00 +1000295| | this is the default. Implemented in |
296| | :func:`strict_errors`. |
Georg Brandl116aa622007-08-15 14:28:22 +0000297+-------------------------+-----------------------------------------------+
Nick Coghlanb9fdb7a2015-01-07 00:22:00 +1000298| ``'ignore'`` | Ignore the malformed data and continue |
299| | without further notice. Implemented in |
300| | :func:`ignore_errors`. |
Georg Brandl116aa622007-08-15 14:28:22 +0000301+-------------------------+-----------------------------------------------+
Nick Coghlanb9fdb7a2015-01-07 00:22:00 +1000302
303The following error handlers are only applicable to
304:term:`text encodings <text encoding>`:
305
306+-------------------------+-----------------------------------------------+
307| Value | Meaning |
308+=========================+===============================================+
Georg Brandl116aa622007-08-15 14:28:22 +0000309| ``'replace'`` | Replace with a suitable replacement |
Nick Coghlanb9fdb7a2015-01-07 00:22:00 +1000310| | marker; Python will use the official |
311| | ``U+FFFD`` REPLACEMENT CHARACTER for the |
312| | built-in codecs on decoding, and '?' on |
313| | encoding. Implemented in |
314| | :func:`replace_errors`. |
Georg Brandl116aa622007-08-15 14:28:22 +0000315+-------------------------+-----------------------------------------------+
316| ``'xmlcharrefreplace'`` | Replace with the appropriate XML character |
Nick Coghlanb9fdb7a2015-01-07 00:22:00 +1000317| | reference (only for encoding). Implemented |
318| | in :func:`xmlcharrefreplace_errors`. |
Georg Brandl116aa622007-08-15 14:28:22 +0000319+-------------------------+-----------------------------------------------+
Serhiy Storchaka07985ef2015-01-25 22:56:57 +0200320| ``'backslashreplace'`` | Replace with backslashed escape sequences. |
321| | Implemented in |
Nick Coghlanb9fdb7a2015-01-07 00:22:00 +1000322| | :func:`backslashreplace_errors`. |
Georg Brandl116aa622007-08-15 14:28:22 +0000323+-------------------------+-----------------------------------------------+
Serhiy Storchaka166ebc42014-11-25 13:57:17 +0200324| ``'namereplace'`` | Replace with ``\N{...}`` escape sequences |
Nick Coghlanf2126362015-01-07 13:14:47 +1000325| | (only for encoding). Implemented in |
326| | :func:`namereplace_errors`. |
Serhiy Storchaka166ebc42014-11-25 13:57:17 +0200327+-------------------------+-----------------------------------------------+
Nick Coghlanb9fdb7a2015-01-07 00:22:00 +1000328| ``'surrogateescape'`` | On decoding, replace byte with individual |
329| | surrogate code ranging from ``U+DC80`` to |
330| | ``U+DCFF``. This code will then be turned |
331| | back into the same byte when the |
332| | ``'surrogateescape'`` error handler is used |
333| | when encoding the data. (See :pep:`383` for |
334| | more.) |
Martin v. Löwis011e8422009-05-05 04:43:17 +0000335+-------------------------+-----------------------------------------------+
Georg Brandl116aa622007-08-15 14:28:22 +0000336
Nick Coghlanb9fdb7a2015-01-07 00:22:00 +1000337In addition, the following error handler is specific to the given codecs:
Martin v. Löwisdb12d452009-05-02 18:52:14 +0000338
Serhiy Storchaka58cf6072013-11-19 11:32:41 +0200339+-------------------+------------------------+-------------------------------------------+
Nick Coghlanb9fdb7a2015-01-07 00:22:00 +1000340| Value | Codecs | Meaning |
Serhiy Storchaka58cf6072013-11-19 11:32:41 +0200341+===================+========================+===========================================+
342|``'surrogatepass'``| utf-8, utf-16, utf-32, | Allow encoding and decoding of surrogate |
Nick Coghlanb9fdb7a2015-01-07 00:22:00 +1000343| | utf-16-be, utf-16-le, | codes. These codecs normally treat the |
344| | utf-32-be, utf-32-le | presence of surrogates as an error. |
Serhiy Storchaka58cf6072013-11-19 11:32:41 +0200345+-------------------+------------------------+-------------------------------------------+
Martin v. Löwisdb12d452009-05-02 18:52:14 +0000346
347.. versionadded:: 3.1
Martin v. Löwis43c57782009-05-10 08:15:24 +0000348 The ``'surrogateescape'`` and ``'surrogatepass'`` error handlers.
Martin v. Löwisdb12d452009-05-02 18:52:14 +0000349
Serhiy Storchaka58cf6072013-11-19 11:32:41 +0200350.. versionchanged:: 3.4
351 The ``'surrogatepass'`` error handlers now works with utf-16\* and utf-32\* codecs.
352
Berker Peksag87f6c222014-11-25 18:59:20 +0200353.. versionadded:: 3.5
Serhiy Storchaka166ebc42014-11-25 13:57:17 +0200354 The ``'namereplace'`` error handler.
355
Serhiy Storchaka07985ef2015-01-25 22:56:57 +0200356.. versionchanged:: 3.5
357 The ``'backslashreplace'`` error handlers now works with decoding and
358 translating.
359
Nick Coghlanb9fdb7a2015-01-07 00:22:00 +1000360The set of allowed values can be extended by registering a new named error
361handler:
362
363.. function:: register_error(name, error_handler)
364
365 Register the error handling function *error_handler* under the name *name*.
366 The *error_handler* argument will be called during encoding and decoding
367 in case of an error, when *name* is specified as the errors parameter.
368
369 For encoding, *error_handler* will be called with a :exc:`UnicodeEncodeError`
370 instance, which contains information about the location of the error. The
371 error handler must either raise this or a different exception, or return a
372 tuple with a replacement for the unencodable part of the input and a position
373 where encoding should continue. The replacement may be either :class:`str` or
374 :class:`bytes`. If the replacement is bytes, the encoder will simply copy
375 them into the output buffer. If the replacement is a string, the encoder will
376 encode the replacement. Encoding continues on original input at the
377 specified position. Negative position values will be treated as being
378 relative to the end of the input string. If the resulting position is out of
379 bound an :exc:`IndexError` will be raised.
380
381 Decoding and translating works similarly, except :exc:`UnicodeDecodeError` or
382 :exc:`UnicodeTranslateError` will be passed to the handler and that the
383 replacement from the error handler will be put into the output directly.
384
385
386Previously registered error handlers (including the standard error handlers)
387can be looked up by name:
388
389.. function:: lookup_error(name)
390
391 Return the error handler previously registered under the name *name*.
392
393 Raises a :exc:`LookupError` in case the handler cannot be found.
394
395The following standard error handlers are also made available as module level
396functions:
397
398.. function:: strict_errors(exception)
399
400 Implements the ``'strict'`` error handling: each encoding or
401 decoding error raises a :exc:`UnicodeError`.
402
403
404.. function:: replace_errors(exception)
405
406 Implements the ``'replace'`` error handling (for :term:`text encodings
407 <text encoding>` only): substitutes ``'?'`` for encoding errors
408 (to be encoded by the codec), and ``'\ufffd'`` (the Unicode replacement
Georg Brandl7e91af32015-02-25 13:05:53 +0100409 character) for decoding errors.
Nick Coghlanb9fdb7a2015-01-07 00:22:00 +1000410
411
412.. function:: ignore_errors(exception)
413
414 Implements the ``'ignore'`` error handling: malformed data is ignored and
415 encoding or decoding is continued without further notice.
416
417
418.. function:: xmlcharrefreplace_errors(exception)
419
420 Implements the ``'xmlcharrefreplace'`` error handling (for encoding with
421 :term:`text encodings <text encoding>` only): the
422 unencodable character is replaced by an appropriate XML character reference.
423
424
425.. function:: backslashreplace_errors(exception)
426
Serhiy Storchaka07985ef2015-01-25 22:56:57 +0200427 Implements the ``'backslashreplace'`` error handling (for
428 :term:`text encodings <text encoding>` only): malformed data is
429 replaced by a backslashed escape sequence.
Georg Brandl116aa622007-08-15 14:28:22 +0000430
Nick Coghlan582acb72015-01-07 00:37:01 +1000431.. function:: namereplace_errors(exception)
432
Nick Coghlanf2126362015-01-07 13:14:47 +1000433 Implements the ``'namereplace'`` error handling (for encoding with
434 :term:`text encodings <text encoding>` only): the
Nick Coghlan582acb72015-01-07 00:37:01 +1000435 unencodable character is replaced by a ``\N{...}`` escape sequence.
436
437 .. versionadded:: 3.5
Georg Brandl116aa622007-08-15 14:28:22 +0000438
439
440.. _codec-objects:
441
Nick Coghlanb9fdb7a2015-01-07 00:22:00 +1000442Stateless Encoding and Decoding
443^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Georg Brandl116aa622007-08-15 14:28:22 +0000444
Nick Coghlanb9fdb7a2015-01-07 00:22:00 +1000445The base :class:`Codec` class defines these methods which also define the
446function interfaces of the stateless encoder and decoder:
Georg Brandl116aa622007-08-15 14:28:22 +0000447
448
449.. method:: Codec.encode(input[, errors])
450
451 Encodes the object *input* and returns a tuple (output object, length consumed).
Nick Coghlanb9fdb7a2015-01-07 00:22:00 +1000452 For instance, :term:`text encoding` converts
453 a string object to a bytes object using a particular
Georg Brandl116aa622007-08-15 14:28:22 +0000454 character set encoding (e.g., ``cp1252`` or ``iso-8859-1``).
455
Nick Coghlanb9fdb7a2015-01-07 00:22:00 +1000456 The *errors* argument defines the error handling to apply.
457 It defaults to ``'strict'`` handling.
Georg Brandl116aa622007-08-15 14:28:22 +0000458
459 The method may not store state in the :class:`Codec` instance. Use
Berker Peksag41ca8282015-07-30 18:26:10 +0300460 :class:`StreamWriter` for codecs which have to keep state in order to make
461 encoding efficient.
Georg Brandl116aa622007-08-15 14:28:22 +0000462
463 The encoder must be able to handle zero length input and return an empty object
464 of the output object type in this situation.
465
466
467.. method:: Codec.decode(input[, errors])
468
Georg Brandl30c78d62008-05-11 14:52:00 +0000469 Decodes the object *input* and returns a tuple (output object, length
Nick Coghlanb9fdb7a2015-01-07 00:22:00 +1000470 consumed). For instance, for a :term:`text encoding`, decoding converts
471 a bytes object encoded using a particular
Georg Brandl30c78d62008-05-11 14:52:00 +0000472 character set encoding to a string object.
Georg Brandl116aa622007-08-15 14:28:22 +0000473
Nick Coghlanb9fdb7a2015-01-07 00:22:00 +1000474 For text encodings and bytes-to-bytes codecs,
475 *input* must be a bytes object or one which provides the read-only
Georg Brandl30c78d62008-05-11 14:52:00 +0000476 buffer interface -- for example, buffer objects and memory mapped files.
Georg Brandl116aa622007-08-15 14:28:22 +0000477
Nick Coghlanb9fdb7a2015-01-07 00:22:00 +1000478 The *errors* argument defines the error handling to apply.
479 It defaults to ``'strict'`` handling.
Georg Brandl116aa622007-08-15 14:28:22 +0000480
481 The method may not store state in the :class:`Codec` instance. Use
Berker Peksag41ca8282015-07-30 18:26:10 +0300482 :class:`StreamReader` for codecs which have to keep state in order to make
483 decoding efficient.
Georg Brandl116aa622007-08-15 14:28:22 +0000484
485 The decoder must be able to handle zero length input and return an empty object
486 of the output object type in this situation.
487
Nick Coghlanb9fdb7a2015-01-07 00:22:00 +1000488
489Incremental Encoding and Decoding
490^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
491
Georg Brandl116aa622007-08-15 14:28:22 +0000492The :class:`IncrementalEncoder` and :class:`IncrementalDecoder` classes provide
493the basic interface for incremental encoding and decoding. Encoding/decoding the
494input isn't done with one call to the stateless encoder/decoder function, but
Serhiy Storchakabfdcd432013-10-13 23:09:14 +0300495with multiple calls to the
496:meth:`~IncrementalEncoder.encode`/:meth:`~IncrementalDecoder.decode` method of
497the incremental encoder/decoder. The incremental encoder/decoder keeps track of
498the encoding/decoding process during method calls.
Georg Brandl116aa622007-08-15 14:28:22 +0000499
Serhiy Storchakabfdcd432013-10-13 23:09:14 +0300500The joined output of calls to the
501:meth:`~IncrementalEncoder.encode`/:meth:`~IncrementalDecoder.decode` method is
502the same as if all the single inputs were joined into one, and this input was
Georg Brandl116aa622007-08-15 14:28:22 +0000503encoded/decoded with the stateless encoder/decoder.
504
505
506.. _incremental-encoder-objects:
507
508IncrementalEncoder Objects
Nick Coghlanb9fdb7a2015-01-07 00:22:00 +1000509~~~~~~~~~~~~~~~~~~~~~~~~~~
Georg Brandl116aa622007-08-15 14:28:22 +0000510
Georg Brandl116aa622007-08-15 14:28:22 +0000511The :class:`IncrementalEncoder` class is used for encoding an input in multiple
512steps. It defines the following methods which every incremental encoder must
513define in order to be compatible with the Python codec registry.
514
515
Nick Coghlanb9fdb7a2015-01-07 00:22:00 +1000516.. class:: IncrementalEncoder(errors='strict')
Georg Brandl116aa622007-08-15 14:28:22 +0000517
518 Constructor for an :class:`IncrementalEncoder` instance.
519
520 All incremental encoders must provide this constructor interface. They are free
521 to add additional keyword arguments, but only the ones defined here are used by
522 the Python codec registry.
523
524 The :class:`IncrementalEncoder` may implement different error handling schemes
Nick Coghlanb9fdb7a2015-01-07 00:22:00 +1000525 by providing the *errors* keyword argument. See :ref:`error-handlers` for
526 possible values.
Serhiy Storchaka166ebc42014-11-25 13:57:17 +0200527
Georg Brandl116aa622007-08-15 14:28:22 +0000528 The *errors* argument will be assigned to an attribute of the same name.
529 Assigning to this attribute makes it possible to switch between different error
530 handling strategies during the lifetime of the :class:`IncrementalEncoder`
531 object.
532
Georg Brandl116aa622007-08-15 14:28:22 +0000533
Benjamin Petersone41251e2008-04-25 01:59:09 +0000534 .. method:: encode(object[, final])
Georg Brandl116aa622007-08-15 14:28:22 +0000535
Benjamin Petersone41251e2008-04-25 01:59:09 +0000536 Encodes *object* (taking the current state of the encoder into account)
537 and returns the resulting encoded object. If this is the last call to
538 :meth:`encode` *final* must be true (the default is false).
Georg Brandl116aa622007-08-15 14:28:22 +0000539
540
Benjamin Petersone41251e2008-04-25 01:59:09 +0000541 .. method:: reset()
Georg Brandl116aa622007-08-15 14:28:22 +0000542
Victor Stinnere15dce32011-05-30 22:56:00 +0200543 Reset the encoder to the initial state. The output is discarded: call
Nick Coghlanb9fdb7a2015-01-07 00:22:00 +1000544 ``.encode(object, final=True)``, passing an empty byte or text string
545 if necessary, to reset the encoder and to get the output.
Georg Brandl116aa622007-08-15 14:28:22 +0000546
547
548.. method:: IncrementalEncoder.getstate()
549
550 Return the current state of the encoder which must be an integer. The
551 implementation should make sure that ``0`` is the most common state. (States
552 that are more complicated than integers can be converted into an integer by
553 marshaling/pickling the state and encoding the bytes of the resulting string
554 into an integer).
555
Georg Brandl116aa622007-08-15 14:28:22 +0000556
557.. method:: IncrementalEncoder.setstate(state)
558
559 Set the state of the encoder to *state*. *state* must be an encoder state
560 returned by :meth:`getstate`.
561
Georg Brandl116aa622007-08-15 14:28:22 +0000562
563.. _incremental-decoder-objects:
564
565IncrementalDecoder Objects
Nick Coghlanb9fdb7a2015-01-07 00:22:00 +1000566~~~~~~~~~~~~~~~~~~~~~~~~~~
Georg Brandl116aa622007-08-15 14:28:22 +0000567
568The :class:`IncrementalDecoder` class is used for decoding an input in multiple
569steps. It defines the following methods which every incremental decoder must
570define in order to be compatible with the Python codec registry.
571
572
Nick Coghlanb9fdb7a2015-01-07 00:22:00 +1000573.. class:: IncrementalDecoder(errors='strict')
Georg Brandl116aa622007-08-15 14:28:22 +0000574
575 Constructor for an :class:`IncrementalDecoder` instance.
576
577 All incremental decoders must provide this constructor interface. They are free
578 to add additional keyword arguments, but only the ones defined here are used by
579 the Python codec registry.
580
581 The :class:`IncrementalDecoder` may implement different error handling schemes
Nick Coghlanb9fdb7a2015-01-07 00:22:00 +1000582 by providing the *errors* keyword argument. See :ref:`error-handlers` for
583 possible values.
Georg Brandl116aa622007-08-15 14:28:22 +0000584
585 The *errors* argument will be assigned to an attribute of the same name.
586 Assigning to this attribute makes it possible to switch between different error
Benjamin Peterson3e4f0552008-09-02 00:31:15 +0000587 handling strategies during the lifetime of the :class:`IncrementalDecoder`
Georg Brandl116aa622007-08-15 14:28:22 +0000588 object.
589
Georg Brandl116aa622007-08-15 14:28:22 +0000590
Benjamin Petersone41251e2008-04-25 01:59:09 +0000591 .. method:: decode(object[, final])
Georg Brandl116aa622007-08-15 14:28:22 +0000592
Benjamin Petersone41251e2008-04-25 01:59:09 +0000593 Decodes *object* (taking the current state of the decoder into account)
594 and returns the resulting decoded object. If this is the last call to
595 :meth:`decode` *final* must be true (the default is false). If *final* is
596 true the decoder must decode the input completely and must flush all
597 buffers. If this isn't possible (e.g. because of incomplete byte sequences
598 at the end of the input) it must initiate error handling just like in the
599 stateless case (which might raise an exception).
Georg Brandl116aa622007-08-15 14:28:22 +0000600
601
Benjamin Petersone41251e2008-04-25 01:59:09 +0000602 .. method:: reset()
Georg Brandl116aa622007-08-15 14:28:22 +0000603
Benjamin Petersone41251e2008-04-25 01:59:09 +0000604 Reset the decoder to the initial state.
Georg Brandl116aa622007-08-15 14:28:22 +0000605
606
Benjamin Petersone41251e2008-04-25 01:59:09 +0000607 .. method:: getstate()
Georg Brandl116aa622007-08-15 14:28:22 +0000608
Benjamin Petersone41251e2008-04-25 01:59:09 +0000609 Return the current state of the decoder. This must be a tuple with two
610 items, the first must be the buffer containing the still undecoded
611 input. The second must be an integer and can be additional state
612 info. (The implementation should make sure that ``0`` is the most common
613 additional state info.) If this additional state info is ``0`` it must be
614 possible to set the decoder to the state which has no input buffered and
615 ``0`` as the additional state info, so that feeding the previously
616 buffered input to the decoder returns it to the previous state without
617 producing any output. (Additional state info that is more complicated than
618 integers can be converted into an integer by marshaling/pickling the info
619 and encoding the bytes of the resulting string into an integer.)
Georg Brandl116aa622007-08-15 14:28:22 +0000620
Georg Brandl116aa622007-08-15 14:28:22 +0000621
Benjamin Petersone41251e2008-04-25 01:59:09 +0000622 .. method:: setstate(state)
Georg Brandl116aa622007-08-15 14:28:22 +0000623
Benjamin Petersone41251e2008-04-25 01:59:09 +0000624 Set the state of the encoder to *state*. *state* must be a decoder state
625 returned by :meth:`getstate`.
626
Georg Brandl116aa622007-08-15 14:28:22 +0000627
Nick Coghlanb9fdb7a2015-01-07 00:22:00 +1000628Stream Encoding and Decoding
629^^^^^^^^^^^^^^^^^^^^^^^^^^^^
630
631
Georg Brandl116aa622007-08-15 14:28:22 +0000632The :class:`StreamWriter` and :class:`StreamReader` classes provide generic
633working interfaces which can be used to implement new encoding submodules very
634easily. See :mod:`encodings.utf_8` for an example of how this is done.
635
636
637.. _stream-writer-objects:
638
639StreamWriter Objects
Nick Coghlanb9fdb7a2015-01-07 00:22:00 +1000640~~~~~~~~~~~~~~~~~~~~
Georg Brandl116aa622007-08-15 14:28:22 +0000641
642The :class:`StreamWriter` class is a subclass of :class:`Codec` and defines the
643following methods which every stream writer must define in order to be
644compatible with the Python codec registry.
645
646
Nick Coghlanb9fdb7a2015-01-07 00:22:00 +1000647.. class:: StreamWriter(stream, errors='strict')
Georg Brandl116aa622007-08-15 14:28:22 +0000648
649 Constructor for a :class:`StreamWriter` instance.
650
651 All stream writers must provide this constructor interface. They are free to add
652 additional keyword arguments, but only the ones defined here are used by the
653 Python codec registry.
654
Nick Coghlanb9fdb7a2015-01-07 00:22:00 +1000655 The *stream* argument must be a file-like object open for writing
656 text or binary data, as appropriate for the specific codec.
Georg Brandl116aa622007-08-15 14:28:22 +0000657
658 The :class:`StreamWriter` may implement different error handling schemes by
Nick Coghlanb9fdb7a2015-01-07 00:22:00 +1000659 providing the *errors* keyword argument. See :ref:`error-handlers` for
660 the standard error handlers the underlying stream codec may support.
Serhiy Storchaka166ebc42014-11-25 13:57:17 +0200661
Georg Brandl116aa622007-08-15 14:28:22 +0000662 The *errors* argument will be assigned to an attribute of the same name.
663 Assigning to this attribute makes it possible to switch between different error
664 handling strategies during the lifetime of the :class:`StreamWriter` object.
665
Benjamin Petersone41251e2008-04-25 01:59:09 +0000666 .. method:: write(object)
Georg Brandl116aa622007-08-15 14:28:22 +0000667
Benjamin Petersone41251e2008-04-25 01:59:09 +0000668 Writes the object's contents encoded to the stream.
Georg Brandl116aa622007-08-15 14:28:22 +0000669
670
Benjamin Petersone41251e2008-04-25 01:59:09 +0000671 .. method:: writelines(list)
Georg Brandl116aa622007-08-15 14:28:22 +0000672
Benjamin Petersone41251e2008-04-25 01:59:09 +0000673 Writes the concatenated list of strings to the stream (possibly by reusing
Nick Coghlanb9fdb7a2015-01-07 00:22:00 +1000674 the :meth:`write` method). The standard bytes-to-bytes codecs
675 do not support this method.
Georg Brandl116aa622007-08-15 14:28:22 +0000676
677
Benjamin Petersone41251e2008-04-25 01:59:09 +0000678 .. method:: reset()
Georg Brandl116aa622007-08-15 14:28:22 +0000679
Benjamin Petersone41251e2008-04-25 01:59:09 +0000680 Flushes and resets the codec buffers used for keeping state.
Georg Brandl116aa622007-08-15 14:28:22 +0000681
Benjamin Petersone41251e2008-04-25 01:59:09 +0000682 Calling this method should ensure that the data on the output is put into
683 a clean state that allows appending of new fresh data without having to
684 rescan the whole stream to recover state.
685
Georg Brandl116aa622007-08-15 14:28:22 +0000686
687In addition to the above methods, the :class:`StreamWriter` must also inherit
688all other methods and attributes from the underlying stream.
689
690
691.. _stream-reader-objects:
692
693StreamReader Objects
Nick Coghlanb9fdb7a2015-01-07 00:22:00 +1000694~~~~~~~~~~~~~~~~~~~~
Georg Brandl116aa622007-08-15 14:28:22 +0000695
696The :class:`StreamReader` class is a subclass of :class:`Codec` and defines the
697following methods which every stream reader must define in order to be
698compatible with the Python codec registry.
699
700
Nick Coghlanb9fdb7a2015-01-07 00:22:00 +1000701.. class:: StreamReader(stream, errors='strict')
Georg Brandl116aa622007-08-15 14:28:22 +0000702
703 Constructor for a :class:`StreamReader` instance.
704
705 All stream readers must provide this constructor interface. They are free to add
706 additional keyword arguments, but only the ones defined here are used by the
707 Python codec registry.
708
Nick Coghlanb9fdb7a2015-01-07 00:22:00 +1000709 The *stream* argument must be a file-like object open for reading
710 text or binary data, as appropriate for the specific codec.
Georg Brandl116aa622007-08-15 14:28:22 +0000711
712 The :class:`StreamReader` may implement different error handling schemes by
Nick Coghlanb9fdb7a2015-01-07 00:22:00 +1000713 providing the *errors* keyword argument. See :ref:`error-handlers` for
714 the standard error handlers the underlying stream codec may support.
Georg Brandl116aa622007-08-15 14:28:22 +0000715
716 The *errors* argument will be assigned to an attribute of the same name.
717 Assigning to this attribute makes it possible to switch between different error
718 handling strategies during the lifetime of the :class:`StreamReader` object.
719
720 The set of allowed values for the *errors* argument can be extended with
721 :func:`register_error`.
722
723
Benjamin Petersone41251e2008-04-25 01:59:09 +0000724 .. method:: read([size[, chars, [firstline]]])
Georg Brandl116aa622007-08-15 14:28:22 +0000725
Benjamin Petersone41251e2008-04-25 01:59:09 +0000726 Decodes data from the stream and returns the resulting object.
Georg Brandl116aa622007-08-15 14:28:22 +0000727
Nick Coghlanb9fdb7a2015-01-07 00:22:00 +1000728 The *chars* argument indicates the number of decoded
729 code points or bytes to return. The :func:`read` method will
730 never return more data than requested, but it might return less,
731 if there is not enough available.
Georg Brandl116aa622007-08-15 14:28:22 +0000732
Nick Coghlanb9fdb7a2015-01-07 00:22:00 +1000733 The *size* argument indicates the approximate maximum
734 number of encoded bytes or code points to read
735 for decoding. The decoder can modify this setting as
Benjamin Petersone41251e2008-04-25 01:59:09 +0000736 appropriate. The default value -1 indicates to read and decode as much as
Nick Coghlanb9fdb7a2015-01-07 00:22:00 +1000737 possible. This parameter is intended to
738 prevent having to decode huge files in one step.
Georg Brandl116aa622007-08-15 14:28:22 +0000739
Nick Coghlanb9fdb7a2015-01-07 00:22:00 +1000740 The *firstline* flag indicates that
741 it would be sufficient to only return the first
Benjamin Petersone41251e2008-04-25 01:59:09 +0000742 line, if there are decoding errors on later lines.
Georg Brandl116aa622007-08-15 14:28:22 +0000743
Benjamin Petersone41251e2008-04-25 01:59:09 +0000744 The method should use a greedy read strategy meaning that it should read
745 as much data as is allowed within the definition of the encoding and the
746 given size, e.g. if optional encoding endings or state markers are
747 available on the stream, these should be read too.
Georg Brandl116aa622007-08-15 14:28:22 +0000748
Georg Brandl116aa622007-08-15 14:28:22 +0000749
Benjamin Petersone41251e2008-04-25 01:59:09 +0000750 .. method:: readline([size[, keepends]])
Georg Brandl116aa622007-08-15 14:28:22 +0000751
Benjamin Petersone41251e2008-04-25 01:59:09 +0000752 Read one line from the input stream and return the decoded data.
Georg Brandl116aa622007-08-15 14:28:22 +0000753
Benjamin Petersone41251e2008-04-25 01:59:09 +0000754 *size*, if given, is passed as size argument to the stream's
Serhiy Storchakacca40ff2013-07-11 18:26:13 +0300755 :meth:`read` method.
Georg Brandl116aa622007-08-15 14:28:22 +0000756
Benjamin Petersone41251e2008-04-25 01:59:09 +0000757 If *keepends* is false line-endings will be stripped from the lines
758 returned.
Georg Brandl116aa622007-08-15 14:28:22 +0000759
Georg Brandl116aa622007-08-15 14:28:22 +0000760
Benjamin Petersone41251e2008-04-25 01:59:09 +0000761 .. method:: readlines([sizehint[, keepends]])
Georg Brandl116aa622007-08-15 14:28:22 +0000762
Benjamin Petersone41251e2008-04-25 01:59:09 +0000763 Read all lines available on the input stream and return them as a list of
764 lines.
Georg Brandl116aa622007-08-15 14:28:22 +0000765
Benjamin Petersone41251e2008-04-25 01:59:09 +0000766 Line-endings are implemented using the codec's decoder method and are
767 included in the list entries if *keepends* is true.
Georg Brandl116aa622007-08-15 14:28:22 +0000768
Benjamin Petersone41251e2008-04-25 01:59:09 +0000769 *sizehint*, if given, is passed as the *size* argument to the stream's
770 :meth:`read` method.
Georg Brandl116aa622007-08-15 14:28:22 +0000771
772
Benjamin Petersone41251e2008-04-25 01:59:09 +0000773 .. method:: reset()
Georg Brandl116aa622007-08-15 14:28:22 +0000774
Benjamin Petersone41251e2008-04-25 01:59:09 +0000775 Resets the codec buffers used for keeping state.
Georg Brandl116aa622007-08-15 14:28:22 +0000776
Benjamin Petersone41251e2008-04-25 01:59:09 +0000777 Note that no stream repositioning should take place. This method is
778 primarily intended to be able to recover from decoding errors.
779
Georg Brandl116aa622007-08-15 14:28:22 +0000780
781In addition to the above methods, the :class:`StreamReader` must also inherit
782all other methods and attributes from the underlying stream.
783
Georg Brandl116aa622007-08-15 14:28:22 +0000784.. _stream-reader-writer:
785
786StreamReaderWriter Objects
Nick Coghlanb9fdb7a2015-01-07 00:22:00 +1000787~~~~~~~~~~~~~~~~~~~~~~~~~~
Georg Brandl116aa622007-08-15 14:28:22 +0000788
Nick Coghlanb9fdb7a2015-01-07 00:22:00 +1000789The :class:`StreamReaderWriter` is a convenience class that allows wrapping
790streams which work in both read and write modes.
Georg Brandl116aa622007-08-15 14:28:22 +0000791
792The design is such that one can use the factory functions returned by the
793:func:`lookup` function to construct the instance.
794
795
796.. class:: StreamReaderWriter(stream, Reader, Writer, errors)
797
798 Creates a :class:`StreamReaderWriter` instance. *stream* must be a file-like
799 object. *Reader* and *Writer* must be factory functions or classes providing the
800 :class:`StreamReader` and :class:`StreamWriter` interface resp. Error handling
801 is done in the same way as defined for the stream readers and writers.
802
803:class:`StreamReaderWriter` instances define the combined interfaces of
804:class:`StreamReader` and :class:`StreamWriter` classes. They inherit all other
805methods and attributes from the underlying stream.
806
807
808.. _stream-recoder-objects:
809
810StreamRecoder Objects
Nick Coghlanb9fdb7a2015-01-07 00:22:00 +1000811~~~~~~~~~~~~~~~~~~~~~
Georg Brandl116aa622007-08-15 14:28:22 +0000812
Nick Coghlanb9fdb7a2015-01-07 00:22:00 +1000813The :class:`StreamRecoder` translates data from one encoding to another,
Georg Brandl116aa622007-08-15 14:28:22 +0000814which is sometimes useful when dealing with different encoding environments.
815
816The design is such that one can use the factory functions returned by the
817:func:`lookup` function to construct the instance.
818
819
820.. class:: StreamRecoder(stream, encode, decode, Reader, Writer, errors)
821
822 Creates a :class:`StreamRecoder` instance which implements a two-way conversion:
Nick Coghlanb9fdb7a2015-01-07 00:22:00 +1000823 *encode* and *decode* work on the frontend — the data visible to
824 code calling :meth:`read` and :meth:`write`, while *Reader* and *Writer*
825 work on the backend — the data in *stream*.
Georg Brandl116aa622007-08-15 14:28:22 +0000826
Nick Coghlanb9fdb7a2015-01-07 00:22:00 +1000827 You can use these objects to do transparent transcodings from e.g. Latin-1
Georg Brandl116aa622007-08-15 14:28:22 +0000828 to UTF-8 and back.
829
Nick Coghlanb9fdb7a2015-01-07 00:22:00 +1000830 The *stream* argument must be a file-like object.
Georg Brandl116aa622007-08-15 14:28:22 +0000831
Nick Coghlanb9fdb7a2015-01-07 00:22:00 +1000832 The *encode* and *decode* arguments must
833 adhere to the :class:`Codec` interface. *Reader* and
Georg Brandl116aa622007-08-15 14:28:22 +0000834 *Writer* must be factory functions or classes providing objects of the
835 :class:`StreamReader` and :class:`StreamWriter` interface respectively.
836
Georg Brandl116aa622007-08-15 14:28:22 +0000837 Error handling is done in the same way as defined for the stream readers and
838 writers.
839
Benjamin Petersone41251e2008-04-25 01:59:09 +0000840
Georg Brandl116aa622007-08-15 14:28:22 +0000841:class:`StreamRecoder` instances define the combined interfaces of
842:class:`StreamReader` and :class:`StreamWriter` classes. They inherit all other
843methods and attributes from the underlying stream.
844
845
846.. _encodings-overview:
847
848Encodings and Unicode
849---------------------
850
Georg Brandl3be472b2015-01-14 08:26:30 +0100851Strings are stored internally as sequences of code points in
Nick Coghlanb9fdb7a2015-01-07 00:22:00 +1000852range ``0x0``-``0x10FFFF``. (See :pep:`393` for
853more details about the implementation.)
854Once a string object is used outside of CPU and memory, endianness
855and how these arrays are stored as bytes become an issue. As with other
856codecs, serialising a string into a sequence of bytes is known as *encoding*,
857and recreating the string from the sequence of bytes is known as *decoding*.
858There are a variety of different text serialisation codecs, which are
859collectivity referred to as :term:`text encodings <text encoding>`.
860
861The simplest text encoding (called ``'latin-1'`` or ``'iso-8859-1'``) maps
Georg Brandl3be472b2015-01-14 08:26:30 +0100862the code points 0-255 to the bytes ``0x0``-``0xff``, which means that a string
863object that contains code points above ``U+00FF`` can't be encoded with this
Nick Coghlanb9fdb7a2015-01-07 00:22:00 +1000864codec. Doing so will raise a :exc:`UnicodeEncodeError` that looks
865like the following (although the details of the error message may differ):
866``UnicodeEncodeError: 'latin-1' codec can't encode character '\u1234' in
867position 3: ordinal not in range(256)``.
Georg Brandl116aa622007-08-15 14:28:22 +0000868
869There's another group of encodings (the so called charmap encodings) that choose
Georg Brandl3be472b2015-01-14 08:26:30 +0100870a different subset of all Unicode code points and how these code points are
Georg Brandl116aa622007-08-15 14:28:22 +0000871mapped to the bytes ``0x0``-``0xff``. To see how this is done simply open
872e.g. :file:`encodings/cp1252.py` (which is an encoding that is used primarily on
873Windows). There's a string constant with 256 characters that shows you which
874character is mapped to which byte value.
875
Georg Brandl3be472b2015-01-14 08:26:30 +0100876All of these encodings can only encode 256 of the 1114112 code points
Georg Brandl30c78d62008-05-11 14:52:00 +0000877defined in Unicode. A simple and straightforward way that can store each Unicode
Georg Brandl3be472b2015-01-14 08:26:30 +0100878code point, is to store each code point as four consecutive bytes. There are two
Ezio Melottifbb39812011-10-25 10:40:38 +0300879possibilities: store the bytes in big endian or in little endian order. These
880two encodings are called ``UTF-32-BE`` and ``UTF-32-LE`` respectively. Their
881disadvantage is that if e.g. you use ``UTF-32-BE`` on a little endian machine you
882will always have to swap bytes on encoding and decoding. ``UTF-32`` avoids this
883problem: bytes will always be in natural endianness. When these bytes are read
Georg Brandl116aa622007-08-15 14:28:22 +0000884by a CPU with a different endianness, then bytes have to be swapped though. To
Ezio Melottifbb39812011-10-25 10:40:38 +0300885be able to detect the endianness of a ``UTF-16`` or ``UTF-32`` byte sequence,
886there's the so called BOM ("Byte Order Mark"). This is the Unicode character
887``U+FEFF``. This character can be prepended to every ``UTF-16`` or ``UTF-32``
888byte sequence. The byte swapped version of this character (``0xFFFE``) is an
889illegal character that may not appear in a Unicode text. So when the
890first character in an ``UTF-16`` or ``UTF-32`` byte sequence
Georg Brandl116aa622007-08-15 14:28:22 +0000891appears to be a ``U+FFFE`` the bytes have to be swapped on decoding.
Ezio Melottifbb39812011-10-25 10:40:38 +0300892Unfortunately the character ``U+FEFF`` had a second purpose as
893a ``ZERO WIDTH NO-BREAK SPACE``: a character that has no width and doesn't allow
Georg Brandl116aa622007-08-15 14:28:22 +0000894a word to be split. It can e.g. be used to give hints to a ligature algorithm.
895With Unicode 4.0 using ``U+FEFF`` as a ``ZERO WIDTH NO-BREAK SPACE`` has been
896deprecated (with ``U+2060`` (``WORD JOINER``) assuming this role). Nevertheless
Ezio Melottifbb39812011-10-25 10:40:38 +0300897Unicode software still must be able to handle ``U+FEFF`` in both roles: as a BOM
Georg Brandl116aa622007-08-15 14:28:22 +0000898it's a device to determine the storage layout of the encoded bytes, and vanishes
Georg Brandl30c78d62008-05-11 14:52:00 +0000899once the byte sequence has been decoded into a string; as a ``ZERO WIDTH
Georg Brandl116aa622007-08-15 14:28:22 +0000900NO-BREAK SPACE`` it's a normal character that will be decoded like any other.
901
902There's another encoding that is able to encoding the full range of Unicode
903characters: UTF-8. UTF-8 is an 8-bit encoding, which means there are no issues
904with byte order in UTF-8. Each byte in a UTF-8 byte sequence consists of two
Ezio Melottifbb39812011-10-25 10:40:38 +0300905parts: marker bits (the most significant bits) and payload bits. The marker bits
Ezio Melotti222b2082011-09-01 08:11:28 +0300906are a sequence of zero to four ``1`` bits followed by a ``0`` bit. Unicode characters are
Georg Brandl116aa622007-08-15 14:28:22 +0000907encoded like this (with x being payload bits, which when concatenated give the
908Unicode character):
909
910+-----------------------------------+----------------------------------------------+
911| Range | Encoding |
912+===================================+==============================================+
913| ``U-00000000`` ... ``U-0000007F`` | 0xxxxxxx |
914+-----------------------------------+----------------------------------------------+
915| ``U-00000080`` ... ``U-000007FF`` | 110xxxxx 10xxxxxx |
916+-----------------------------------+----------------------------------------------+
917| ``U-00000800`` ... ``U-0000FFFF`` | 1110xxxx 10xxxxxx 10xxxxxx |
918+-----------------------------------+----------------------------------------------+
Ezio Melotti222b2082011-09-01 08:11:28 +0300919| ``U-00010000`` ... ``U-0010FFFF`` | 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx |
Georg Brandl116aa622007-08-15 14:28:22 +0000920+-----------------------------------+----------------------------------------------+
921
922The least significant bit of the Unicode character is the rightmost x bit.
923
924As UTF-8 is an 8-bit encoding no BOM is required and any ``U+FEFF`` character in
Georg Brandl30c78d62008-05-11 14:52:00 +0000925the decoded string (even if it's the first character) is treated as a ``ZERO
926WIDTH NO-BREAK SPACE``.
Georg Brandl116aa622007-08-15 14:28:22 +0000927
928Without external information it's impossible to reliably determine which
Georg Brandl30c78d62008-05-11 14:52:00 +0000929encoding was used for encoding a string. Each charmap encoding can
Georg Brandl116aa622007-08-15 14:28:22 +0000930decode any random byte sequence. However that's not possible with UTF-8, as
931UTF-8 byte sequences have a structure that doesn't allow arbitrary byte
Thomas Wouters89d996e2007-09-08 17:39:28 +0000932sequences. To increase the reliability with which a UTF-8 encoding can be
Georg Brandl116aa622007-08-15 14:28:22 +0000933detected, Microsoft invented a variant of UTF-8 (that Python 2.5 calls
934``"utf-8-sig"``) for its Notepad program: Before any of the Unicode characters
935is written to the file, a UTF-8 encoded BOM (which looks like this as a byte
936sequence: ``0xef``, ``0xbb``, ``0xbf``) is written. As it's rather improbable
937that any charmap encoded file starts with these byte values (which would e.g.
938map to
939
940 | LATIN SMALL LETTER I WITH DIAERESIS
941 | RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK
942 | INVERTED QUESTION MARK
943
Ezio Melottifbb39812011-10-25 10:40:38 +0300944in iso-8859-1), this increases the probability that a ``utf-8-sig`` encoding can be
Georg Brandl116aa622007-08-15 14:28:22 +0000945correctly guessed from the byte sequence. So here the BOM is not used to be able
946to determine the byte order used for generating the byte sequence, but as a
947signature that helps in guessing the encoding. On encoding the utf-8-sig codec
948will write ``0xef``, ``0xbb``, ``0xbf`` as the first three bytes to the file. On
Ezio Melottifbb39812011-10-25 10:40:38 +0300949decoding ``utf-8-sig`` will skip those three bytes if they appear as the first
950three bytes in the file. In UTF-8, the use of the BOM is discouraged and
951should generally be avoided.
Georg Brandl116aa622007-08-15 14:28:22 +0000952
953
954.. _standard-encodings:
955
956Standard Encodings
957------------------
958
959Python comes with a number of codecs built-in, either implemented as C functions
960or with dictionaries as mapping tables. The following table lists the codecs by
961name, together with a few common aliases, and the languages for which the
962encoding is likely used. Neither the list of aliases nor the list of languages
963is meant to be exhaustive. Notice that spelling alternatives that only differ in
Georg Brandla6053b42009-09-01 08:11:14 +0000964case or use a hyphen instead of an underscore are also valid aliases; therefore,
965e.g. ``'utf-8'`` is a valid alias for the ``'utf_8'`` codec.
Georg Brandl116aa622007-08-15 14:28:22 +0000966
Alexander Belopolsky1d521462011-02-25 19:19:57 +0000967.. impl-detail::
968
969 Some common encodings can bypass the codecs lookup machinery to
970 improve performance. These optimization opportunities are only
971 recognized by CPython for a limited set of aliases: utf-8, utf8,
972 latin-1, latin1, iso-8859-1, mbcs (Windows only), ascii, utf-16,
973 and utf-32. Using alternative spellings for these encodings may
974 result in slower execution.
975
Georg Brandl116aa622007-08-15 14:28:22 +0000976Many of the character sets support the same languages. They vary in individual
977characters (e.g. whether the EURO SIGN is supported or not), and in the
978assignment of characters to code positions. For the European languages in
979particular, the following variants typically exist:
980
981* an ISO 8859 codeset
982
Martin Panter4c359642016-05-08 13:53:41 +0000983* a Microsoft Windows code page, which is typically derived from an 8859 codeset,
Georg Brandl116aa622007-08-15 14:28:22 +0000984 but replaces control characters with additional graphic characters
985
986* an IBM EBCDIC code page
987
988* an IBM PC code page, which is ASCII compatible
989
Georg Brandl44ea77b2013-03-28 13:28:44 +0100990.. tabularcolumns:: |l|p{0.3\linewidth}|p{0.3\linewidth}|
991
Georg Brandl116aa622007-08-15 14:28:22 +0000992+-----------------+--------------------------------+--------------------------------+
993| Codec | Aliases | Languages |
994+=================+================================+================================+
995| ascii | 646, us-ascii | English |
996+-----------------+--------------------------------+--------------------------------+
997| big5 | big5-tw, csbig5 | Traditional Chinese |
998+-----------------+--------------------------------+--------------------------------+
999| big5hkscs | big5-hkscs, hkscs | Traditional Chinese |
1000+-----------------+--------------------------------+--------------------------------+
1001| cp037 | IBM037, IBM039 | English |
1002+-----------------+--------------------------------+--------------------------------+
R David Murray47d083c2014-03-07 21:00:34 -05001003| cp273 | 273, IBM273, csIBM273 | German |
1004| | | |
1005| | | .. versionadded:: 3.4 |
1006+-----------------+--------------------------------+--------------------------------+
Georg Brandl116aa622007-08-15 14:28:22 +00001007| cp424 | EBCDIC-CP-HE, IBM424 | Hebrew |
1008+-----------------+--------------------------------+--------------------------------+
1009| cp437 | 437, IBM437 | English |
1010+-----------------+--------------------------------+--------------------------------+
1011| cp500 | EBCDIC-CP-BE, EBCDIC-CP-CH, | Western Europe |
1012| | IBM500 | |
1013+-----------------+--------------------------------+--------------------------------+
Amaury Forgeot d'Arcae6388d2009-07-15 19:21:18 +00001014| cp720 | | Arabic |
1015+-----------------+--------------------------------+--------------------------------+
Georg Brandl116aa622007-08-15 14:28:22 +00001016| cp737 | | Greek |
1017+-----------------+--------------------------------+--------------------------------+
1018| cp775 | IBM775 | Baltic languages |
1019+-----------------+--------------------------------+--------------------------------+
1020| cp850 | 850, IBM850 | Western Europe |
1021+-----------------+--------------------------------+--------------------------------+
1022| cp852 | 852, IBM852 | Central and Eastern Europe |
1023+-----------------+--------------------------------+--------------------------------+
1024| cp855 | 855, IBM855 | Bulgarian, Byelorussian, |
1025| | | Macedonian, Russian, Serbian |
1026+-----------------+--------------------------------+--------------------------------+
1027| cp856 | | Hebrew |
1028+-----------------+--------------------------------+--------------------------------+
1029| cp857 | 857, IBM857 | Turkish |
1030+-----------------+--------------------------------+--------------------------------+
Benjamin Peterson5a6214a2010-06-27 22:41:29 +00001031| cp858 | 858, IBM858 | Western Europe |
1032+-----------------+--------------------------------+--------------------------------+
Georg Brandl116aa622007-08-15 14:28:22 +00001033| cp860 | 860, IBM860 | Portuguese |
1034+-----------------+--------------------------------+--------------------------------+
1035| cp861 | 861, CP-IS, IBM861 | Icelandic |
1036+-----------------+--------------------------------+--------------------------------+
1037| cp862 | 862, IBM862 | Hebrew |
1038+-----------------+--------------------------------+--------------------------------+
1039| cp863 | 863, IBM863 | Canadian |
1040+-----------------+--------------------------------+--------------------------------+
1041| cp864 | IBM864 | Arabic |
1042+-----------------+--------------------------------+--------------------------------+
1043| cp865 | 865, IBM865 | Danish, Norwegian |
1044+-----------------+--------------------------------+--------------------------------+
1045| cp866 | 866, IBM866 | Russian |
1046+-----------------+--------------------------------+--------------------------------+
1047| cp869 | 869, CP-GR, IBM869 | Greek |
1048+-----------------+--------------------------------+--------------------------------+
1049| cp874 | | Thai |
1050+-----------------+--------------------------------+--------------------------------+
1051| cp875 | | Greek |
1052+-----------------+--------------------------------+--------------------------------+
1053| cp932 | 932, ms932, mskanji, ms-kanji | Japanese |
1054+-----------------+--------------------------------+--------------------------------+
1055| cp949 | 949, ms949, uhc | Korean |
1056+-----------------+--------------------------------+--------------------------------+
1057| cp950 | 950, ms950 | Traditional Chinese |
1058+-----------------+--------------------------------+--------------------------------+
1059| cp1006 | | Urdu |
1060+-----------------+--------------------------------+--------------------------------+
1061| cp1026 | ibm1026 | Turkish |
1062+-----------------+--------------------------------+--------------------------------+
Serhiy Storchakabe0c3252013-11-23 18:52:23 +02001063| cp1125 | 1125, ibm1125, cp866u, ruscii | Ukrainian |
1064| | | |
1065| | | .. versionadded:: 3.4 |
1066+-----------------+--------------------------------+--------------------------------+
Georg Brandl116aa622007-08-15 14:28:22 +00001067| cp1140 | ibm1140 | Western Europe |
1068+-----------------+--------------------------------+--------------------------------+
1069| cp1250 | windows-1250 | Central and Eastern Europe |
1070+-----------------+--------------------------------+--------------------------------+
1071| cp1251 | windows-1251 | Bulgarian, Byelorussian, |
1072| | | Macedonian, Russian, Serbian |
1073+-----------------+--------------------------------+--------------------------------+
1074| cp1252 | windows-1252 | Western Europe |
1075+-----------------+--------------------------------+--------------------------------+
1076| cp1253 | windows-1253 | Greek |
1077+-----------------+--------------------------------+--------------------------------+
1078| cp1254 | windows-1254 | Turkish |
1079+-----------------+--------------------------------+--------------------------------+
1080| cp1255 | windows-1255 | Hebrew |
1081+-----------------+--------------------------------+--------------------------------+
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00001082| cp1256 | windows-1256 | Arabic |
Georg Brandl116aa622007-08-15 14:28:22 +00001083+-----------------+--------------------------------+--------------------------------+
1084| cp1257 | windows-1257 | Baltic languages |
1085+-----------------+--------------------------------+--------------------------------+
1086| cp1258 | windows-1258 | Vietnamese |
1087+-----------------+--------------------------------+--------------------------------+
Victor Stinner2f3ca9f2011-10-27 01:38:56 +02001088| cp65001 | | Windows only: Windows UTF-8 |
1089| | | (``CP_UTF8``) |
1090| | | |
1091| | | .. versionadded:: 3.3 |
1092+-----------------+--------------------------------+--------------------------------+
Georg Brandl116aa622007-08-15 14:28:22 +00001093| euc_jp | eucjp, ujis, u-jis | Japanese |
1094+-----------------+--------------------------------+--------------------------------+
1095| euc_jis_2004 | jisx0213, eucjis2004 | Japanese |
1096+-----------------+--------------------------------+--------------------------------+
1097| euc_jisx0213 | eucjisx0213 | Japanese |
1098+-----------------+--------------------------------+--------------------------------+
1099| euc_kr | euckr, korean, ksc5601, | Korean |
1100| | ks_c-5601, ks_c-5601-1987, | |
1101| | ksx1001, ks_x-1001 | |
1102+-----------------+--------------------------------+--------------------------------+
1103| gb2312 | chinese, csiso58gb231280, euc- | Simplified Chinese |
1104| | cn, euccn, eucgb2312-cn, | |
1105| | gb2312-1980, gb2312-80, iso- | |
1106| | ir-58 | |
1107+-----------------+--------------------------------+--------------------------------+
1108| gbk | 936, cp936, ms936 | Unified Chinese |
1109+-----------------+--------------------------------+--------------------------------+
1110| gb18030 | gb18030-2000 | Unified Chinese |
1111+-----------------+--------------------------------+--------------------------------+
1112| hz | hzgb, hz-gb, hz-gb-2312 | Simplified Chinese |
1113+-----------------+--------------------------------+--------------------------------+
1114| iso2022_jp | csiso2022jp, iso2022jp, | Japanese |
1115| | iso-2022-jp | |
1116+-----------------+--------------------------------+--------------------------------+
1117| iso2022_jp_1 | iso2022jp-1, iso-2022-jp-1 | Japanese |
1118+-----------------+--------------------------------+--------------------------------+
1119| iso2022_jp_2 | iso2022jp-2, iso-2022-jp-2 | Japanese, Korean, Simplified |
1120| | | Chinese, Western Europe, Greek |
1121+-----------------+--------------------------------+--------------------------------+
1122| iso2022_jp_2004 | iso2022jp-2004, | Japanese |
1123| | iso-2022-jp-2004 | |
1124+-----------------+--------------------------------+--------------------------------+
1125| iso2022_jp_3 | iso2022jp-3, iso-2022-jp-3 | Japanese |
1126+-----------------+--------------------------------+--------------------------------+
1127| iso2022_jp_ext | iso2022jp-ext, iso-2022-jp-ext | Japanese |
1128+-----------------+--------------------------------+--------------------------------+
1129| iso2022_kr | csiso2022kr, iso2022kr, | Korean |
1130| | iso-2022-kr | |
1131+-----------------+--------------------------------+--------------------------------+
1132| latin_1 | iso-8859-1, iso8859-1, 8859, | West Europe |
1133| | cp819, latin, latin1, L1 | |
1134+-----------------+--------------------------------+--------------------------------+
1135| iso8859_2 | iso-8859-2, latin2, L2 | Central and Eastern Europe |
1136+-----------------+--------------------------------+--------------------------------+
1137| iso8859_3 | iso-8859-3, latin3, L3 | Esperanto, Maltese |
1138+-----------------+--------------------------------+--------------------------------+
Christian Heimesc3f30c42008-02-22 16:37:40 +00001139| iso8859_4 | iso-8859-4, latin4, L4 | Baltic languages |
Georg Brandl116aa622007-08-15 14:28:22 +00001140+-----------------+--------------------------------+--------------------------------+
1141| iso8859_5 | iso-8859-5, cyrillic | Bulgarian, Byelorussian, |
1142| | | Macedonian, Russian, Serbian |
1143+-----------------+--------------------------------+--------------------------------+
1144| iso8859_6 | iso-8859-6, arabic | Arabic |
1145+-----------------+--------------------------------+--------------------------------+
1146| iso8859_7 | iso-8859-7, greek, greek8 | Greek |
1147+-----------------+--------------------------------+--------------------------------+
1148| iso8859_8 | iso-8859-8, hebrew | Hebrew |
1149+-----------------+--------------------------------+--------------------------------+
1150| iso8859_9 | iso-8859-9, latin5, L5 | Turkish |
1151+-----------------+--------------------------------+--------------------------------+
1152| iso8859_10 | iso-8859-10, latin6, L6 | Nordic languages |
1153+-----------------+--------------------------------+--------------------------------+
Victor Stinnerbfd97672015-09-24 09:04:05 +02001154| iso8859_11 | iso-8859-11, thai | Thai languages |
1155+-----------------+--------------------------------+--------------------------------+
Georg Brandl93dc9eb2010-03-14 10:56:14 +00001156| iso8859_13 | iso-8859-13, latin7, L7 | Baltic languages |
Georg Brandl116aa622007-08-15 14:28:22 +00001157+-----------------+--------------------------------+--------------------------------+
1158| iso8859_14 | iso-8859-14, latin8, L8 | Celtic languages |
1159+-----------------+--------------------------------+--------------------------------+
Georg Brandl93dc9eb2010-03-14 10:56:14 +00001160| iso8859_15 | iso-8859-15, latin9, L9 | Western Europe |
1161+-----------------+--------------------------------+--------------------------------+
1162| iso8859_16 | iso-8859-16, latin10, L10 | South-Eastern Europe |
Georg Brandl116aa622007-08-15 14:28:22 +00001163+-----------------+--------------------------------+--------------------------------+
1164| johab | cp1361, ms1361 | Korean |
1165+-----------------+--------------------------------+--------------------------------+
1166| koi8_r | | Russian |
1167+-----------------+--------------------------------+--------------------------------+
Serhiy Storchakaf0eeedf2015-05-12 23:24:19 +03001168| koi8_t | | Tajik |
1169| | | |
1170| | | .. versionadded:: 3.5 |
1171+-----------------+--------------------------------+--------------------------------+
Georg Brandl116aa622007-08-15 14:28:22 +00001172| koi8_u | | Ukrainian |
1173+-----------------+--------------------------------+--------------------------------+
Serhiy Storchakaad8a1c32015-05-12 23:16:55 +03001174| kz1048 | kz_1048, strk1048_2002, rk1048 | Kazakh |
1175| | | |
1176| | | .. versionadded:: 3.5 |
1177+-----------------+--------------------------------+--------------------------------+
Georg Brandl116aa622007-08-15 14:28:22 +00001178| mac_cyrillic | maccyrillic | Bulgarian, Byelorussian, |
1179| | | Macedonian, Russian, Serbian |
1180+-----------------+--------------------------------+--------------------------------+
1181| mac_greek | macgreek | Greek |
1182+-----------------+--------------------------------+--------------------------------+
1183| mac_iceland | maciceland | Icelandic |
1184+-----------------+--------------------------------+--------------------------------+
1185| mac_latin2 | maclatin2, maccentraleurope | Central and Eastern Europe |
1186+-----------------+--------------------------------+--------------------------------+
Benjamin Peterson23110e72010-08-21 02:54:44 +00001187| mac_roman | macroman, macintosh | Western Europe |
Georg Brandl116aa622007-08-15 14:28:22 +00001188+-----------------+--------------------------------+--------------------------------+
1189| mac_turkish | macturkish | Turkish |
1190+-----------------+--------------------------------+--------------------------------+
1191| ptcp154 | csptcp154, pt154, cp154, | Kazakh |
1192| | cyrillic-asian | |
1193+-----------------+--------------------------------+--------------------------------+
1194| shift_jis | csshiftjis, shiftjis, sjis, | Japanese |
1195| | s_jis | |
1196+-----------------+--------------------------------+--------------------------------+
1197| shift_jis_2004 | shiftjis2004, sjis_2004, | Japanese |
1198| | sjis2004 | |
1199+-----------------+--------------------------------+--------------------------------+
1200| shift_jisx0213 | shiftjisx0213, sjisx0213, | Japanese |
1201| | s_jisx0213 | |
1202+-----------------+--------------------------------+--------------------------------+
Walter Dörwald41980ca2007-08-16 21:55:45 +00001203| utf_32 | U32, utf32 | all languages |
1204+-----------------+--------------------------------+--------------------------------+
1205| utf_32_be | UTF-32BE | all languages |
1206+-----------------+--------------------------------+--------------------------------+
1207| utf_32_le | UTF-32LE | all languages |
1208+-----------------+--------------------------------+--------------------------------+
Georg Brandl116aa622007-08-15 14:28:22 +00001209| utf_16 | U16, utf16 | all languages |
1210+-----------------+--------------------------------+--------------------------------+
Victor Stinner53a9dd72010-12-08 22:25:45 +00001211| utf_16_be | UTF-16BE | all languages |
Georg Brandl116aa622007-08-15 14:28:22 +00001212+-----------------+--------------------------------+--------------------------------+
Victor Stinner53a9dd72010-12-08 22:25:45 +00001213| utf_16_le | UTF-16LE | all languages |
Georg Brandl116aa622007-08-15 14:28:22 +00001214+-----------------+--------------------------------+--------------------------------+
1215| utf_7 | U7, unicode-1-1-utf-7 | all languages |
1216+-----------------+--------------------------------+--------------------------------+
1217| utf_8 | U8, UTF, utf8 | all languages |
1218+-----------------+--------------------------------+--------------------------------+
1219| utf_8_sig | | all languages |
1220+-----------------+--------------------------------+--------------------------------+
1221
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02001222.. versionchanged:: 3.4
1223 The utf-16\* and utf-32\* encoders no longer allow surrogate code points
Nick Coghlanb9fdb7a2015-01-07 00:22:00 +10001224 (``U+D800``--``U+DFFF``) to be encoded.
1225 The utf-32\* decoders no longer decode
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02001226 byte sequences that correspond to surrogate code points.
1227
1228
Nick Coghlan650e3222013-05-23 20:24:02 +10001229Python Specific Encodings
1230-------------------------
1231
1232A number of predefined codecs are specific to Python, so their codec names have
1233no meaning outside Python. These are listed in the tables below based on the
1234expected input and output types (note that while text encodings are the most
1235common use case for codecs, the underlying codec infrastructure supports
1236arbitrary data transforms rather than just text encodings). For asymmetric
1237codecs, the stated purpose describes the encoding direction.
1238
Nick Coghlan9c1aed82013-11-23 11:13:36 +10001239Text Encodings
1240^^^^^^^^^^^^^^
1241
Nick Coghlan650e3222013-05-23 20:24:02 +10001242The following codecs provide :class:`str` to :class:`bytes` encoding and
1243:term:`bytes-like object` to :class:`str` decoding, similar to the Unicode text
1244encodings.
Georg Brandl226878c2007-08-31 10:15:37 +00001245
Georg Brandl44ea77b2013-03-28 13:28:44 +01001246.. tabularcolumns:: |l|p{0.3\linewidth}|p{0.3\linewidth}|
1247
Georg Brandl30c78d62008-05-11 14:52:00 +00001248+--------------------+---------+---------------------------+
1249| Codec | Aliases | Purpose |
1250+====================+=========+===========================+
1251| idna | | Implements :rfc:`3490`, |
1252| | | see also |
Nick Coghlanb9fdb7a2015-01-07 00:22:00 +10001253| | | :mod:`encodings.idna`. |
1254| | | Only ``errors='strict'`` |
1255| | | is supported. |
Georg Brandl30c78d62008-05-11 14:52:00 +00001256+--------------------+---------+---------------------------+
Steve Dower5a713272016-09-06 19:46:42 -07001257| mbcs | ansi, | Windows only: Encode |
1258| | dbcs | operand according to the |
Georg Brandl30c78d62008-05-11 14:52:00 +00001259| | | ANSI codepage (CP_ACP) |
1260+--------------------+---------+---------------------------+
Steve Dower5a713272016-09-06 19:46:42 -07001261| oem | | Windows only: Encode |
1262| | | operand according to the |
1263| | | OEM codepage (CP_OEMCP) |
1264| | | |
1265| | | .. versionadded:: 3.6 |
1266+--------------------+---------+---------------------------+
Georg Brandl30c78d62008-05-11 14:52:00 +00001267| palmos | | Encoding of PalmOS 3.5 |
1268+--------------------+---------+---------------------------+
Nick Coghlanb9fdb7a2015-01-07 00:22:00 +10001269| punycode | | Implements :rfc:`3492`. |
1270| | | Stateful codecs are not |
1271| | | supported. |
Georg Brandl30c78d62008-05-11 14:52:00 +00001272+--------------------+---------+---------------------------+
Nick Coghlanb9fdb7a2015-01-07 00:22:00 +10001273| raw_unicode_escape | | Latin-1 encoding with |
1274| | | ``\uXXXX`` and |
1275| | | ``\UXXXXXXXX`` for other |
1276| | | code points. Existing |
1277| | | backslashes are not |
1278| | | escaped in any way. |
1279| | | It is used in the Python |
1280| | | pickle protocol. |
Georg Brandl30c78d62008-05-11 14:52:00 +00001281+--------------------+---------+---------------------------+
1282| undefined | | Raise an exception for |
Nick Coghlanb9fdb7a2015-01-07 00:22:00 +10001283| | | all conversions, even |
1284| | | empty strings. The error |
1285| | | handler is ignored. |
Georg Brandl30c78d62008-05-11 14:52:00 +00001286+--------------------+---------+---------------------------+
Nick Coghlanb9fdb7a2015-01-07 00:22:00 +10001287| unicode_escape | | Encoding suitable as the |
1288| | | contents of a Unicode |
1289| | | literal in ASCII-encoded |
1290| | | Python source code, |
1291| | | except that quotes are |
1292| | | not escaped. Decodes from |
1293| | | Latin-1 source code. |
1294| | | Beware that Python source |
1295| | | code actually uses UTF-8 |
1296| | | by default. |
Georg Brandl30c78d62008-05-11 14:52:00 +00001297+--------------------+---------+---------------------------+
1298| unicode_internal | | Return the internal |
1299| | | representation of the |
Nick Coghlanb9fdb7a2015-01-07 00:22:00 +10001300| | | operand. Stateful codecs |
1301| | | are not supported. |
Victor Stinner9f4b1e92011-11-10 20:56:30 +01001302| | | |
1303| | | .. deprecated:: 3.3 |
Nick Coghlanb9fdb7a2015-01-07 00:22:00 +10001304| | | This representation is |
1305| | | obsoleted by |
1306| | | :pep:`393`. |
Georg Brandl30c78d62008-05-11 14:52:00 +00001307+--------------------+---------+---------------------------+
Georg Brandl116aa622007-08-15 14:28:22 +00001308
Nick Coghlan9c1aed82013-11-23 11:13:36 +10001309.. _binary-transforms:
1310
1311Binary Transforms
1312^^^^^^^^^^^^^^^^^
1313
1314The following codecs provide binary transforms: :term:`bytes-like object`
Nick Coghlanb9fdb7a2015-01-07 00:22:00 +10001315to :class:`bytes` mappings. They are not supported by :meth:`bytes.decode`
1316(which only produces :class:`str` output).
Nick Coghlan650e3222013-05-23 20:24:02 +10001317
Georg Brandl02524622010-12-02 18:06:51 +00001318
Nick Coghlan9c1aed82013-11-23 11:13:36 +10001319.. tabularcolumns:: |l|L|L|L|
Georg Brandl44ea77b2013-03-28 13:28:44 +01001320
Nick Coghlan9c1aed82013-11-23 11:13:36 +10001321+----------------------+------------------+------------------------------+------------------------------+
1322| Codec | Aliases | Purpose | Encoder / decoder |
1323+======================+==================+==============================+==============================+
Martin Panter06171bd2015-09-12 00:34:28 +00001324| base64_codec [#b64]_ | base64, base_64 | Convert operand to multiline | :meth:`base64.encodebytes` / |
1325| | | MIME base64 (the result | :meth:`base64.decodebytes` |
1326| | | always includes a trailing | |
Nick Coghlan9c1aed82013-11-23 11:13:36 +10001327| | | ``'\n'``) | |
1328| | | | |
1329| | | .. versionchanged:: 3.4 | |
1330| | | accepts any | |
1331| | | :term:`bytes-like object` | |
1332| | | as input for encoding and | |
1333| | | decoding | |
1334+----------------------+------------------+------------------------------+------------------------------+
1335| bz2_codec | bz2 | Compress the operand | :meth:`bz2.compress` / |
1336| | | using bz2 | :meth:`bz2.decompress` |
1337+----------------------+------------------+------------------------------+------------------------------+
Martin Panter06171bd2015-09-12 00:34:28 +00001338| hex_codec | hex | Convert operand to | :meth:`binascii.b2a_hex` / |
1339| | | hexadecimal | :meth:`binascii.a2b_hex` |
Nick Coghlan9c1aed82013-11-23 11:13:36 +10001340| | | representation, with two | |
1341| | | digits per byte | |
1342+----------------------+------------------+------------------------------+------------------------------+
Martin Panter06171bd2015-09-12 00:34:28 +00001343| quopri_codec | quopri, | Convert operand to MIME | :meth:`quopri.encode` with |
1344| | quotedprintable, | quoted printable | ``quotetabs=True`` / |
1345| | quoted_printable | | :meth:`quopri.decode` |
Nick Coghlan9c1aed82013-11-23 11:13:36 +10001346+----------------------+------------------+------------------------------+------------------------------+
1347| uu_codec | uu | Convert the operand using | :meth:`uu.encode` / |
1348| | | uuencode | :meth:`uu.decode` |
1349+----------------------+------------------+------------------------------+------------------------------+
1350| zlib_codec | zip, zlib | Compress the operand | :meth:`zlib.compress` / |
1351| | | using gzip | :meth:`zlib.decompress` |
1352+----------------------+------------------+------------------------------+------------------------------+
Georg Brandl02524622010-12-02 18:06:51 +00001353
Nick Coghlanfdf239a2013-10-03 00:43:22 +10001354.. [#b64] In addition to :term:`bytes-like objects <bytes-like object>`,
1355 ``'base64_codec'`` also accepts ASCII-only instances of :class:`str` for
1356 decoding
Nick Coghlan650e3222013-05-23 20:24:02 +10001357
Nick Coghlan9c1aed82013-11-23 11:13:36 +10001358.. versionadded:: 3.2
1359 Restoration of the binary transforms.
Nick Coghlan650e3222013-05-23 20:24:02 +10001360
Nick Coghlan9c1aed82013-11-23 11:13:36 +10001361.. versionchanged:: 3.4
1362 Restoration of the aliases for the binary transforms.
Georg Brandl02524622010-12-02 18:06:51 +00001363
Georg Brandl44ea77b2013-03-28 13:28:44 +01001364
Nick Coghlan9c1aed82013-11-23 11:13:36 +10001365.. _text-transforms:
1366
1367Text Transforms
1368^^^^^^^^^^^^^^^
1369
1370The following codec provides a text transform: a :class:`str` to :class:`str`
Nick Coghlanb9fdb7a2015-01-07 00:22:00 +10001371mapping. It is not supported by :meth:`str.encode` (which only produces
1372:class:`bytes` output).
Nick Coghlan9c1aed82013-11-23 11:13:36 +10001373
1374.. tabularcolumns:: |l|l|L|
1375
1376+--------------------+---------+---------------------------+
1377| Codec | Aliases | Purpose |
1378+====================+=========+===========================+
1379| rot_13 | rot13 | Returns the Caesar-cypher |
1380| | | encryption of the operand |
1381+--------------------+---------+---------------------------+
Georg Brandl02524622010-12-02 18:06:51 +00001382
1383.. versionadded:: 3.2
Nick Coghlan9c1aed82013-11-23 11:13:36 +10001384 Restoration of the ``rot_13`` text transform.
1385
1386.. versionchanged:: 3.4
1387 Restoration of the ``rot13`` alias.
Georg Brandl02524622010-12-02 18:06:51 +00001388
Georg Brandl116aa622007-08-15 14:28:22 +00001389
1390:mod:`encodings.idna` --- Internationalized Domain Names in Applications
1391------------------------------------------------------------------------
1392
1393.. module:: encodings.idna
1394 :synopsis: Internationalized Domain Names implementation
1395.. moduleauthor:: Martin v. Löwis
1396
Georg Brandl116aa622007-08-15 14:28:22 +00001397This module implements :rfc:`3490` (Internationalized Domain Names in
1398Applications) and :rfc:`3492` (Nameprep: A Stringprep Profile for
1399Internationalized Domain Names (IDN)). It builds upon the ``punycode`` encoding
1400and :mod:`stringprep`.
1401
1402These RFCs together define a protocol to support non-ASCII characters in domain
1403names. A domain name containing non-ASCII characters (such as
1404``www.Alliancefrançaise.nu``) is converted into an ASCII-compatible encoding
1405(ACE, such as ``www.xn--alliancefranaise-npb.nu``). The ACE form of the domain
1406name is then used in all places where arbitrary characters are not allowed by
1407the protocol, such as DNS queries, HTTP :mailheader:`Host` fields, and so
1408on. This conversion is carried out in the application; if possible invisible to
1409the user: The application should transparently convert Unicode domain labels to
1410IDNA on the wire, and convert back ACE labels to Unicode before presenting them
1411to the user.
1412
R David Murraye0fd2f82011-04-13 14:12:18 -04001413Python supports this conversion in several ways: the ``idna`` codec performs
1414conversion between Unicode and ACE, separating an input string into labels
1415based on the separator characters defined in `section 3.1`_ (1) of :rfc:`3490`
1416and converting each label to ACE as required, and conversely separating an input
1417byte string into labels based on the ``.`` separator and converting any ACE
1418labels found into unicode. Furthermore, the :mod:`socket` module
Georg Brandl116aa622007-08-15 14:28:22 +00001419transparently converts Unicode host names to ACE, so that applications need not
1420be concerned about converting host names themselves when they pass them to the
1421socket module. On top of that, modules that have host names as function
Georg Brandl24420152008-05-26 16:32:26 +00001422parameters, such as :mod:`http.client` and :mod:`ftplib`, accept Unicode host
1423names (:mod:`http.client` then also transparently sends an IDNA hostname in the
Georg Brandl116aa622007-08-15 14:28:22 +00001424:mailheader:`Host` field if it sends that field at all).
1425
Serhiy Storchaka6dff0202016-05-07 10:49:07 +03001426.. _section 3.1: https://tools.ietf.org/html/rfc3490#section-3.1
R David Murraye0fd2f82011-04-13 14:12:18 -04001427
Georg Brandl116aa622007-08-15 14:28:22 +00001428When receiving host names from the wire (such as in reverse name lookup), no
1429automatic conversion to Unicode is performed: Applications wishing to present
1430such host names to the user should decode them to Unicode.
1431
1432The module :mod:`encodings.idna` also implements the nameprep procedure, which
1433performs certain normalizations on host names, to achieve case-insensitivity of
1434international domain names, and to unify similar characters. The nameprep
1435functions can be used directly if desired.
1436
1437
1438.. function:: nameprep(label)
1439
1440 Return the nameprepped version of *label*. The implementation currently assumes
1441 query strings, so ``AllowUnassigned`` is true.
1442
1443
1444.. function:: ToASCII(label)
1445
1446 Convert a label to ASCII, as specified in :rfc:`3490`. ``UseSTD3ASCIIRules`` is
1447 assumed to be false.
1448
1449
1450.. function:: ToUnicode(label)
1451
1452 Convert a label to Unicode, as specified in :rfc:`3490`.
1453
1454
Victor Stinner554f3f02010-06-16 23:33:54 +00001455:mod:`encodings.mbcs` --- Windows ANSI codepage
1456-----------------------------------------------
1457
1458.. module:: encodings.mbcs
1459 :synopsis: Windows ANSI codepage
1460
Victor Stinner3a50e702011-10-18 21:21:00 +02001461Encode operand according to the ANSI codepage (CP_ACP).
Victor Stinner554f3f02010-06-16 23:33:54 +00001462
1463Availability: Windows only.
1464
Victor Stinner3a50e702011-10-18 21:21:00 +02001465.. versionchanged:: 3.3
1466 Support any error handler.
1467
Victor Stinner554f3f02010-06-16 23:33:54 +00001468.. versionchanged:: 3.2
1469 Before 3.2, the *errors* argument was ignored; ``'replace'`` was always used
1470 to encode, and ``'ignore'`` to decode.
1471
1472
Georg Brandl116aa622007-08-15 14:28:22 +00001473:mod:`encodings.utf_8_sig` --- UTF-8 codec with BOM signature
1474-------------------------------------------------------------
1475
1476.. module:: encodings.utf_8_sig
1477 :synopsis: UTF-8 codec with BOM signature
1478.. moduleauthor:: Walter Dörwald
1479
Georg Brandl116aa622007-08-15 14:28:22 +00001480This module implements a variant of the UTF-8 codec: On encoding a UTF-8 encoded
1481BOM will be prepended to the UTF-8 encoded bytes. For the stateful encoder this
1482is only done once (on the first write to the byte stream). For decoding an
1483optional UTF-8 encoded BOM at the start of the data will be skipped.