blob: 0dcd88f9fd5b7fd1fdec8b9eb0c99a7c5b696213 [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
Inada Naoki5c84bb52021-04-28 09:37:02 +0900162 argument, being the encoding name in all lower case letters with hyphens
163 and spaces converted to underscores, and return a :class:`CodecInfo` object.
164 In case a search function cannot find a given encoding, it should return
165 ``None``.
166
167 .. versionchanged:: 3.9
168 Hyphens and spaces are converted to underscore.
Georg Brandl116aa622007-08-15 14:28:22 +0000169
Georg Brandl116aa622007-08-15 14:28:22 +0000170
Hai Shid332e7b2020-09-29 05:41:11 +0800171.. function:: unregister(search_function)
172
173 Unregister a codec search function and clear the registry's cache.
174 If the search function is not registered, do nothing.
175
176 .. versionadded:: 3.10
177
Nick Coghlanb9fdb7a2015-01-07 00:22:00 +1000178
179While the builtin :func:`open` and the associated :mod:`io` module are the
180recommended approach for working with encoded text files, this module
181provides additional utility functions and classes that allow the use of a
182wider range of codecs when working with binary files:
183
Alexey Izbysheva2670562018-10-20 03:22:31 +0300184.. function:: open(filename, mode='r', encoding=None, errors='strict', buffering=-1)
Nick Coghlanb9fdb7a2015-01-07 00:22:00 +1000185
186 Open an encoded file using the given *mode* and return an instance of
187 :class:`StreamReaderWriter`, providing transparent encoding/decoding.
188 The default file mode is ``'r'``, meaning to open the file in read mode.
Georg Brandl116aa622007-08-15 14:28:22 +0000189
Christian Heimes18c66892008-02-17 13:31:39 +0000190 .. note::
191
Nick Coghlanb9fdb7a2015-01-07 00:22:00 +1000192 Underlying encoded files are always opened in binary mode.
193 No automatic conversion of ``'\n'`` is done on reading and writing.
194 The *mode* argument may be any binary mode acceptable to the built-in
195 :func:`open` function; the ``'b'`` is automatically added.
Christian Heimes18c66892008-02-17 13:31:39 +0000196
Georg Brandl116aa622007-08-15 14:28:22 +0000197 *encoding* specifies the encoding which is to be used for the file.
Nick Coghlanb9fdb7a2015-01-07 00:22:00 +1000198 Any encoding that encodes to and decodes from bytes is allowed, and
199 the data types supported by the file methods depend on the codec used.
Georg Brandl116aa622007-08-15 14:28:22 +0000200
201 *errors* may be given to define the error handling. It defaults to ``'strict'``
202 which causes a :exc:`ValueError` to be raised in case an encoding error occurs.
203
Alexey Izbysheva2670562018-10-20 03:22:31 +0300204 *buffering* has the same meaning as for the built-in :func:`open` function.
205 It defaults to -1 which means that the default buffer size will be used.
Georg Brandl116aa622007-08-15 14:28:22 +0000206
207
Georg Brandl0d8f0732009-04-05 22:20:44 +0000208.. function:: EncodedFile(file, data_encoding, file_encoding=None, errors='strict')
Georg Brandl116aa622007-08-15 14:28:22 +0000209
Nick Coghlanb9fdb7a2015-01-07 00:22:00 +1000210 Return a :class:`StreamRecoder` instance, a wrapped version of *file*
211 which provides transparent transcoding. The original file is closed
212 when the wrapped version is closed.
Georg Brandl116aa622007-08-15 14:28:22 +0000213
Nick Coghlanb9fdb7a2015-01-07 00:22:00 +1000214 Data written to the wrapped file is decoded according to the given
215 *data_encoding* and then written to the original file as bytes using
216 *file_encoding*. Bytes read from the original file are decoded
217 according to *file_encoding*, and the result is encoded
218 using *data_encoding*.
Georg Brandl116aa622007-08-15 14:28:22 +0000219
Georg Brandl0d8f0732009-04-05 22:20:44 +0000220 If *file_encoding* is not given, it defaults to *data_encoding*.
Georg Brandl116aa622007-08-15 14:28:22 +0000221
Georg Brandl0d8f0732009-04-05 22:20:44 +0000222 *errors* may be given to define the error handling. It defaults to
223 ``'strict'``, which causes :exc:`ValueError` to be raised in case an encoding
224 error occurs.
Georg Brandl116aa622007-08-15 14:28:22 +0000225
226
Georg Brandl0d8f0732009-04-05 22:20:44 +0000227.. function:: iterencode(iterator, encoding, errors='strict', **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +0000228
229 Uses an incremental encoder to iteratively encode the input provided by
Nick Coghlanb9fdb7a2015-01-07 00:22:00 +1000230 *iterator*. This function is a :term:`generator`.
231 The *errors* argument (as well as any
Georg Brandl9afde1c2007-11-01 20:32:30 +0000232 other keyword argument) is passed through to the incremental encoder.
Georg Brandl116aa622007-08-15 14:28:22 +0000233
Martin Panterc73e9d82016-10-15 00:56:47 +0000234 This function requires that the codec accept text :class:`str` objects
235 to encode. Therefore it does not support bytes-to-bytes encoders such as
236 ``base64_codec``.
237
Georg Brandl116aa622007-08-15 14:28:22 +0000238
Georg Brandl0d8f0732009-04-05 22:20:44 +0000239.. function:: iterdecode(iterator, encoding, errors='strict', **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +0000240
241 Uses an incremental decoder to iteratively decode the input provided by
Nick Coghlanb9fdb7a2015-01-07 00:22:00 +1000242 *iterator*. This function is a :term:`generator`.
243 The *errors* argument (as well as any
Georg Brandl9afde1c2007-11-01 20:32:30 +0000244 other keyword argument) is passed through to the incremental decoder.
Georg Brandl116aa622007-08-15 14:28:22 +0000245
Martin Panterc73e9d82016-10-15 00:56:47 +0000246 This function requires that the codec accept :class:`bytes` objects
247 to decode. Therefore it does not support text-to-text encoders such as
248 ``rot_13``, although ``rot_13`` may be used equivalently with
249 :func:`iterencode`.
250
Georg Brandl0d8f0732009-04-05 22:20:44 +0000251
Georg Brandl116aa622007-08-15 14:28:22 +0000252The module also provides the following constants which are useful for reading
253and writing to platform dependent files:
254
255
256.. data:: BOM
257 BOM_BE
258 BOM_LE
259 BOM_UTF8
260 BOM_UTF16
261 BOM_UTF16_BE
262 BOM_UTF16_LE
263 BOM_UTF32
264 BOM_UTF32_BE
265 BOM_UTF32_LE
266
Nick Coghlanb9fdb7a2015-01-07 00:22:00 +1000267 These constants define various byte sequences,
268 being Unicode byte order marks (BOMs) for several encodings. They are
269 used in UTF-16 and UTF-32 data streams to indicate the byte order used,
270 and in UTF-8 as a Unicode signature. :const:`BOM_UTF16` is either
Georg Brandl116aa622007-08-15 14:28:22 +0000271 :const:`BOM_UTF16_BE` or :const:`BOM_UTF16_LE` depending on the platform's
272 native byte order, :const:`BOM` is an alias for :const:`BOM_UTF16`,
273 :const:`BOM_LE` for :const:`BOM_UTF16_LE` and :const:`BOM_BE` for
274 :const:`BOM_UTF16_BE`. The others represent the BOM in UTF-8 and UTF-32
275 encodings.
276
277
278.. _codec-base-classes:
279
280Codec Base Classes
281------------------
282
283The :mod:`codecs` module defines a set of base classes which define the
Nick Coghlanb9fdb7a2015-01-07 00:22:00 +1000284interfaces for working with codec objects, and can also be used as the basis
285for custom codec implementations.
Georg Brandl116aa622007-08-15 14:28:22 +0000286
287Each codec has to define four interfaces to make it usable as codec in Python:
288stateless encoder, stateless decoder, stream reader and stream writer. The
289stream reader and writers typically reuse the stateless encoder/decoder to
Nick Coghlanb9fdb7a2015-01-07 00:22:00 +1000290implement the file protocols. Codec authors also need to define how the
291codec will handle encoding and decoding errors.
Georg Brandl116aa622007-08-15 14:28:22 +0000292
Georg Brandl116aa622007-08-15 14:28:22 +0000293
Nick Coghlanf2126362015-01-07 13:14:47 +1000294.. _surrogateescape:
Nick Coghlanb9fdb7a2015-01-07 00:22:00 +1000295.. _error-handlers:
296
297Error Handlers
298^^^^^^^^^^^^^^
299
300To simplify and standardize error handling,
301codecs may implement different error handling schemes by
Géry Ogam891e9e32019-09-12 09:41:32 +0200302accepting the *errors* string argument. The following string values are
Nick Coghlanb9fdb7a2015-01-07 00:22:00 +1000303defined and implemented by all standard Python codecs:
Georg Brandl116aa622007-08-15 14:28:22 +0000304
Georg Brandl44ea77b2013-03-28 13:28:44 +0100305.. tabularcolumns:: |l|L|
306
Georg Brandl116aa622007-08-15 14:28:22 +0000307+-------------------------+-----------------------------------------------+
308| Value | Meaning |
309+=========================+===============================================+
310| ``'strict'`` | Raise :exc:`UnicodeError` (or a subclass); |
Géry Ogam891e9e32019-09-12 09:41:32 +0200311| | this is the default. Implemented in |
Nick Coghlanb9fdb7a2015-01-07 00:22:00 +1000312| | :func:`strict_errors`. |
Georg Brandl116aa622007-08-15 14:28:22 +0000313+-------------------------+-----------------------------------------------+
Nick Coghlanb9fdb7a2015-01-07 00:22:00 +1000314| ``'ignore'`` | Ignore the malformed data and continue |
Géry Ogam891e9e32019-09-12 09:41:32 +0200315| | without further notice. Implemented in |
Nick Coghlanb9fdb7a2015-01-07 00:22:00 +1000316| | :func:`ignore_errors`. |
Georg Brandl116aa622007-08-15 14:28:22 +0000317+-------------------------+-----------------------------------------------+
Nick Coghlanb9fdb7a2015-01-07 00:22:00 +1000318
319The following error handlers are only applicable to
320:term:`text encodings <text encoding>`:
321
Serhiy Storchaka913876d2018-10-28 13:41:26 +0200322.. index::
323 single: ? (question mark); replacement character
324 single: \ (backslash); escape sequence
325 single: \x; escape sequence
326 single: \u; escape sequence
327 single: \U; escape sequence
328 single: \N; escape sequence
329
Nick Coghlanb9fdb7a2015-01-07 00:22:00 +1000330+-------------------------+-----------------------------------------------+
331| Value | Meaning |
332+=========================+===============================================+
Georg Brandl116aa622007-08-15 14:28:22 +0000333| ``'replace'`` | Replace with a suitable replacement |
Nick Coghlanb9fdb7a2015-01-07 00:22:00 +1000334| | marker; Python will use the official |
335| | ``U+FFFD`` REPLACEMENT CHARACTER for the |
336| | built-in codecs on decoding, and '?' on |
Géry Ogam891e9e32019-09-12 09:41:32 +0200337| | encoding. Implemented in |
Nick Coghlanb9fdb7a2015-01-07 00:22:00 +1000338| | :func:`replace_errors`. |
Georg Brandl116aa622007-08-15 14:28:22 +0000339+-------------------------+-----------------------------------------------+
340| ``'xmlcharrefreplace'`` | Replace with the appropriate XML character |
Géry Ogam891e9e32019-09-12 09:41:32 +0200341| | reference (only for encoding). Implemented |
Nick Coghlanb9fdb7a2015-01-07 00:22:00 +1000342| | in :func:`xmlcharrefreplace_errors`. |
Georg Brandl116aa622007-08-15 14:28:22 +0000343+-------------------------+-----------------------------------------------+
Serhiy Storchaka07985ef2015-01-25 22:56:57 +0200344| ``'backslashreplace'`` | Replace with backslashed escape sequences. |
345| | Implemented in |
Nick Coghlanb9fdb7a2015-01-07 00:22:00 +1000346| | :func:`backslashreplace_errors`. |
Georg Brandl116aa622007-08-15 14:28:22 +0000347+-------------------------+-----------------------------------------------+
Serhiy Storchaka166ebc42014-11-25 13:57:17 +0200348| ``'namereplace'`` | Replace with ``\N{...}`` escape sequences |
Géry Ogam891e9e32019-09-12 09:41:32 +0200349| | (only for encoding). Implemented in |
Nick Coghlanf2126362015-01-07 13:14:47 +1000350| | :func:`namereplace_errors`. |
Serhiy Storchaka166ebc42014-11-25 13:57:17 +0200351+-------------------------+-----------------------------------------------+
Nick Coghlanb9fdb7a2015-01-07 00:22:00 +1000352| ``'surrogateescape'`` | On decoding, replace byte with individual |
353| | surrogate code ranging from ``U+DC80`` to |
Géry Ogam891e9e32019-09-12 09:41:32 +0200354| | ``U+DCFF``. This code will then be turned |
Nick Coghlanb9fdb7a2015-01-07 00:22:00 +1000355| | back into the same byte when the |
356| | ``'surrogateescape'`` error handler is used |
Géry Ogam891e9e32019-09-12 09:41:32 +0200357| | when encoding the data. (See :pep:`383` for |
Nick Coghlanb9fdb7a2015-01-07 00:22:00 +1000358| | more.) |
Martin v. Löwis011e8422009-05-05 04:43:17 +0000359+-------------------------+-----------------------------------------------+
Georg Brandl116aa622007-08-15 14:28:22 +0000360
Nick Coghlanb9fdb7a2015-01-07 00:22:00 +1000361In addition, the following error handler is specific to the given codecs:
Martin v. Löwisdb12d452009-05-02 18:52:14 +0000362
Serhiy Storchaka58cf6072013-11-19 11:32:41 +0200363+-------------------+------------------------+-------------------------------------------+
Nick Coghlanb9fdb7a2015-01-07 00:22:00 +1000364| Value | Codecs | Meaning |
Serhiy Storchaka58cf6072013-11-19 11:32:41 +0200365+===================+========================+===========================================+
366|``'surrogatepass'``| utf-8, utf-16, utf-32, | Allow encoding and decoding of surrogate |
Géry Ogam891e9e32019-09-12 09:41:32 +0200367| | utf-16-be, utf-16-le, | codes. These codecs normally treat the |
Nick Coghlanb9fdb7a2015-01-07 00:22:00 +1000368| | utf-32-be, utf-32-le | presence of surrogates as an error. |
Serhiy Storchaka58cf6072013-11-19 11:32:41 +0200369+-------------------+------------------------+-------------------------------------------+
Martin v. Löwisdb12d452009-05-02 18:52:14 +0000370
371.. versionadded:: 3.1
Martin v. Löwis43c57782009-05-10 08:15:24 +0000372 The ``'surrogateescape'`` and ``'surrogatepass'`` error handlers.
Martin v. Löwisdb12d452009-05-02 18:52:14 +0000373
Serhiy Storchaka58cf6072013-11-19 11:32:41 +0200374.. versionchanged:: 3.4
375 The ``'surrogatepass'`` error handlers now works with utf-16\* and utf-32\* codecs.
376
Berker Peksag87f6c222014-11-25 18:59:20 +0200377.. versionadded:: 3.5
Serhiy Storchaka166ebc42014-11-25 13:57:17 +0200378 The ``'namereplace'`` error handler.
379
Serhiy Storchaka07985ef2015-01-25 22:56:57 +0200380.. versionchanged:: 3.5
381 The ``'backslashreplace'`` error handlers now works with decoding and
382 translating.
383
Nick Coghlanb9fdb7a2015-01-07 00:22:00 +1000384The set of allowed values can be extended by registering a new named error
385handler:
386
387.. function:: register_error(name, error_handler)
388
389 Register the error handling function *error_handler* under the name *name*.
390 The *error_handler* argument will be called during encoding and decoding
391 in case of an error, when *name* is specified as the errors parameter.
392
393 For encoding, *error_handler* will be called with a :exc:`UnicodeEncodeError`
394 instance, which contains information about the location of the error. The
395 error handler must either raise this or a different exception, or return a
396 tuple with a replacement for the unencodable part of the input and a position
397 where encoding should continue. The replacement may be either :class:`str` or
Géry Ogam891e9e32019-09-12 09:41:32 +0200398 :class:`bytes`. If the replacement is bytes, the encoder will simply copy
Nick Coghlanb9fdb7a2015-01-07 00:22:00 +1000399 them into the output buffer. If the replacement is a string, the encoder will
Géry Ogam891e9e32019-09-12 09:41:32 +0200400 encode the replacement. Encoding continues on original input at the
Nick Coghlanb9fdb7a2015-01-07 00:22:00 +1000401 specified position. Negative position values will be treated as being
402 relative to the end of the input string. If the resulting position is out of
403 bound an :exc:`IndexError` will be raised.
404
405 Decoding and translating works similarly, except :exc:`UnicodeDecodeError` or
406 :exc:`UnicodeTranslateError` will be passed to the handler and that the
407 replacement from the error handler will be put into the output directly.
408
409
410Previously registered error handlers (including the standard error handlers)
411can be looked up by name:
412
413.. function:: lookup_error(name)
414
415 Return the error handler previously registered under the name *name*.
416
417 Raises a :exc:`LookupError` in case the handler cannot be found.
418
419The following standard error handlers are also made available as module level
420functions:
421
422.. function:: strict_errors(exception)
423
424 Implements the ``'strict'`` error handling: each encoding or
425 decoding error raises a :exc:`UnicodeError`.
426
427
428.. function:: replace_errors(exception)
429
430 Implements the ``'replace'`` error handling (for :term:`text encodings
431 <text encoding>` only): substitutes ``'?'`` for encoding errors
432 (to be encoded by the codec), and ``'\ufffd'`` (the Unicode replacement
Georg Brandl7e91af32015-02-25 13:05:53 +0100433 character) for decoding errors.
Nick Coghlanb9fdb7a2015-01-07 00:22:00 +1000434
435
436.. function:: ignore_errors(exception)
437
438 Implements the ``'ignore'`` error handling: malformed data is ignored and
439 encoding or decoding is continued without further notice.
440
441
442.. function:: xmlcharrefreplace_errors(exception)
443
444 Implements the ``'xmlcharrefreplace'`` error handling (for encoding with
445 :term:`text encodings <text encoding>` only): the
446 unencodable character is replaced by an appropriate XML character reference.
447
448
449.. function:: backslashreplace_errors(exception)
450
Serhiy Storchaka07985ef2015-01-25 22:56:57 +0200451 Implements the ``'backslashreplace'`` error handling (for
452 :term:`text encodings <text encoding>` only): malformed data is
453 replaced by a backslashed escape sequence.
Georg Brandl116aa622007-08-15 14:28:22 +0000454
Nick Coghlan582acb72015-01-07 00:37:01 +1000455.. function:: namereplace_errors(exception)
456
Nick Coghlanf2126362015-01-07 13:14:47 +1000457 Implements the ``'namereplace'`` error handling (for encoding with
458 :term:`text encodings <text encoding>` only): the
Nick Coghlan582acb72015-01-07 00:37:01 +1000459 unencodable character is replaced by a ``\N{...}`` escape sequence.
460
461 .. versionadded:: 3.5
Georg Brandl116aa622007-08-15 14:28:22 +0000462
463
464.. _codec-objects:
465
Nick Coghlanb9fdb7a2015-01-07 00:22:00 +1000466Stateless Encoding and Decoding
467^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Georg Brandl116aa622007-08-15 14:28:22 +0000468
Nick Coghlanb9fdb7a2015-01-07 00:22:00 +1000469The base :class:`Codec` class defines these methods which also define the
470function interfaces of the stateless encoder and decoder:
Georg Brandl116aa622007-08-15 14:28:22 +0000471
472
473.. method:: Codec.encode(input[, errors])
474
475 Encodes the object *input* and returns a tuple (output object, length consumed).
Nick Coghlanb9fdb7a2015-01-07 00:22:00 +1000476 For instance, :term:`text encoding` converts
477 a string object to a bytes object using a particular
Georg Brandl116aa622007-08-15 14:28:22 +0000478 character set encoding (e.g., ``cp1252`` or ``iso-8859-1``).
479
Nick Coghlanb9fdb7a2015-01-07 00:22:00 +1000480 The *errors* argument defines the error handling to apply.
481 It defaults to ``'strict'`` handling.
Georg Brandl116aa622007-08-15 14:28:22 +0000482
483 The method may not store state in the :class:`Codec` instance. Use
Berker Peksag41ca8282015-07-30 18:26:10 +0300484 :class:`StreamWriter` for codecs which have to keep state in order to make
485 encoding efficient.
Georg Brandl116aa622007-08-15 14:28:22 +0000486
487 The encoder must be able to handle zero length input and return an empty object
488 of the output object type in this situation.
489
490
491.. method:: Codec.decode(input[, errors])
492
Georg Brandl30c78d62008-05-11 14:52:00 +0000493 Decodes the object *input* and returns a tuple (output object, length
Géry Ogam891e9e32019-09-12 09:41:32 +0200494 consumed). For instance, for a :term:`text encoding`, decoding converts
Nick Coghlanb9fdb7a2015-01-07 00:22:00 +1000495 a bytes object encoded using a particular
Georg Brandl30c78d62008-05-11 14:52:00 +0000496 character set encoding to a string object.
Georg Brandl116aa622007-08-15 14:28:22 +0000497
Nick Coghlanb9fdb7a2015-01-07 00:22:00 +1000498 For text encodings and bytes-to-bytes codecs,
499 *input* must be a bytes object or one which provides the read-only
Georg Brandl30c78d62008-05-11 14:52:00 +0000500 buffer interface -- for example, buffer objects and memory mapped files.
Georg Brandl116aa622007-08-15 14:28:22 +0000501
Nick Coghlanb9fdb7a2015-01-07 00:22:00 +1000502 The *errors* argument defines the error handling to apply.
503 It defaults to ``'strict'`` handling.
Georg Brandl116aa622007-08-15 14:28:22 +0000504
505 The method may not store state in the :class:`Codec` instance. Use
Berker Peksag41ca8282015-07-30 18:26:10 +0300506 :class:`StreamReader` for codecs which have to keep state in order to make
507 decoding efficient.
Georg Brandl116aa622007-08-15 14:28:22 +0000508
509 The decoder must be able to handle zero length input and return an empty object
510 of the output object type in this situation.
511
Nick Coghlanb9fdb7a2015-01-07 00:22:00 +1000512
513Incremental Encoding and Decoding
514^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
515
Georg Brandl116aa622007-08-15 14:28:22 +0000516The :class:`IncrementalEncoder` and :class:`IncrementalDecoder` classes provide
517the basic interface for incremental encoding and decoding. Encoding/decoding the
518input isn't done with one call to the stateless encoder/decoder function, but
Serhiy Storchakabfdcd432013-10-13 23:09:14 +0300519with multiple calls to the
520:meth:`~IncrementalEncoder.encode`/:meth:`~IncrementalDecoder.decode` method of
521the incremental encoder/decoder. The incremental encoder/decoder keeps track of
522the encoding/decoding process during method calls.
Georg Brandl116aa622007-08-15 14:28:22 +0000523
Serhiy Storchakabfdcd432013-10-13 23:09:14 +0300524The joined output of calls to the
525:meth:`~IncrementalEncoder.encode`/:meth:`~IncrementalDecoder.decode` method is
526the same as if all the single inputs were joined into one, and this input was
Georg Brandl116aa622007-08-15 14:28:22 +0000527encoded/decoded with the stateless encoder/decoder.
528
529
530.. _incremental-encoder-objects:
531
532IncrementalEncoder Objects
Nick Coghlanb9fdb7a2015-01-07 00:22:00 +1000533~~~~~~~~~~~~~~~~~~~~~~~~~~
Georg Brandl116aa622007-08-15 14:28:22 +0000534
Georg Brandl116aa622007-08-15 14:28:22 +0000535The :class:`IncrementalEncoder` class is used for encoding an input in multiple
536steps. It defines the following methods which every incremental encoder must
537define in order to be compatible with the Python codec registry.
538
539
Nick Coghlanb9fdb7a2015-01-07 00:22:00 +1000540.. class:: IncrementalEncoder(errors='strict')
Georg Brandl116aa622007-08-15 14:28:22 +0000541
542 Constructor for an :class:`IncrementalEncoder` instance.
543
544 All incremental encoders must provide this constructor interface. They are free
545 to add additional keyword arguments, but only the ones defined here are used by
546 the Python codec registry.
547
548 The :class:`IncrementalEncoder` may implement different error handling schemes
Nick Coghlanb9fdb7a2015-01-07 00:22:00 +1000549 by providing the *errors* keyword argument. See :ref:`error-handlers` for
550 possible values.
Serhiy Storchaka166ebc42014-11-25 13:57:17 +0200551
Georg Brandl116aa622007-08-15 14:28:22 +0000552 The *errors* argument will be assigned to an attribute of the same name.
553 Assigning to this attribute makes it possible to switch between different error
554 handling strategies during the lifetime of the :class:`IncrementalEncoder`
555 object.
556
Georg Brandl116aa622007-08-15 14:28:22 +0000557
Benjamin Petersone41251e2008-04-25 01:59:09 +0000558 .. method:: encode(object[, final])
Georg Brandl116aa622007-08-15 14:28:22 +0000559
Benjamin Petersone41251e2008-04-25 01:59:09 +0000560 Encodes *object* (taking the current state of the encoder into account)
561 and returns the resulting encoded object. If this is the last call to
562 :meth:`encode` *final* must be true (the default is false).
Georg Brandl116aa622007-08-15 14:28:22 +0000563
564
Benjamin Petersone41251e2008-04-25 01:59:09 +0000565 .. method:: reset()
Georg Brandl116aa622007-08-15 14:28:22 +0000566
Victor Stinnere15dce32011-05-30 22:56:00 +0200567 Reset the encoder to the initial state. The output is discarded: call
Nick Coghlanb9fdb7a2015-01-07 00:22:00 +1000568 ``.encode(object, final=True)``, passing an empty byte or text string
569 if necessary, to reset the encoder and to get the output.
Georg Brandl116aa622007-08-15 14:28:22 +0000570
571
Zhiming Wang30644de2017-09-10 02:09:55 -0400572 .. method:: getstate()
Georg Brandl116aa622007-08-15 14:28:22 +0000573
Zhiming Wang30644de2017-09-10 02:09:55 -0400574 Return the current state of the encoder which must be an integer. The
575 implementation should make sure that ``0`` is the most common
576 state. (States that are more complicated than integers can be converted
577 into an integer by marshaling/pickling the state and encoding the bytes
Géry Ogam891e9e32019-09-12 09:41:32 +0200578 of the resulting string into an integer.)
Georg Brandl116aa622007-08-15 14:28:22 +0000579
Georg Brandl116aa622007-08-15 14:28:22 +0000580
Zhiming Wang30644de2017-09-10 02:09:55 -0400581 .. method:: setstate(state)
Georg Brandl116aa622007-08-15 14:28:22 +0000582
Zhiming Wang30644de2017-09-10 02:09:55 -0400583 Set the state of the encoder to *state*. *state* must be an encoder state
584 returned by :meth:`getstate`.
Georg Brandl116aa622007-08-15 14:28:22 +0000585
Georg Brandl116aa622007-08-15 14:28:22 +0000586
587.. _incremental-decoder-objects:
588
589IncrementalDecoder Objects
Nick Coghlanb9fdb7a2015-01-07 00:22:00 +1000590~~~~~~~~~~~~~~~~~~~~~~~~~~
Georg Brandl116aa622007-08-15 14:28:22 +0000591
592The :class:`IncrementalDecoder` class is used for decoding an input in multiple
593steps. It defines the following methods which every incremental decoder must
594define in order to be compatible with the Python codec registry.
595
596
Nick Coghlanb9fdb7a2015-01-07 00:22:00 +1000597.. class:: IncrementalDecoder(errors='strict')
Georg Brandl116aa622007-08-15 14:28:22 +0000598
599 Constructor for an :class:`IncrementalDecoder` instance.
600
601 All incremental decoders must provide this constructor interface. They are free
602 to add additional keyword arguments, but only the ones defined here are used by
603 the Python codec registry.
604
605 The :class:`IncrementalDecoder` may implement different error handling schemes
Nick Coghlanb9fdb7a2015-01-07 00:22:00 +1000606 by providing the *errors* keyword argument. See :ref:`error-handlers` for
607 possible values.
Georg Brandl116aa622007-08-15 14:28:22 +0000608
609 The *errors* argument will be assigned to an attribute of the same name.
610 Assigning to this attribute makes it possible to switch between different error
Benjamin Peterson3e4f0552008-09-02 00:31:15 +0000611 handling strategies during the lifetime of the :class:`IncrementalDecoder`
Georg Brandl116aa622007-08-15 14:28:22 +0000612 object.
613
Georg Brandl116aa622007-08-15 14:28:22 +0000614
Benjamin Petersone41251e2008-04-25 01:59:09 +0000615 .. method:: decode(object[, final])
Georg Brandl116aa622007-08-15 14:28:22 +0000616
Benjamin Petersone41251e2008-04-25 01:59:09 +0000617 Decodes *object* (taking the current state of the decoder into account)
618 and returns the resulting decoded object. If this is the last call to
619 :meth:`decode` *final* must be true (the default is false). If *final* is
620 true the decoder must decode the input completely and must flush all
621 buffers. If this isn't possible (e.g. because of incomplete byte sequences
622 at the end of the input) it must initiate error handling just like in the
623 stateless case (which might raise an exception).
Georg Brandl116aa622007-08-15 14:28:22 +0000624
625
Benjamin Petersone41251e2008-04-25 01:59:09 +0000626 .. method:: reset()
Georg Brandl116aa622007-08-15 14:28:22 +0000627
Benjamin Petersone41251e2008-04-25 01:59:09 +0000628 Reset the decoder to the initial state.
Georg Brandl116aa622007-08-15 14:28:22 +0000629
630
Benjamin Petersone41251e2008-04-25 01:59:09 +0000631 .. method:: getstate()
Georg Brandl116aa622007-08-15 14:28:22 +0000632
Benjamin Petersone41251e2008-04-25 01:59:09 +0000633 Return the current state of the decoder. This must be a tuple with two
634 items, the first must be the buffer containing the still undecoded
635 input. The second must be an integer and can be additional state
636 info. (The implementation should make sure that ``0`` is the most common
637 additional state info.) If this additional state info is ``0`` it must be
638 possible to set the decoder to the state which has no input buffered and
639 ``0`` as the additional state info, so that feeding the previously
640 buffered input to the decoder returns it to the previous state without
641 producing any output. (Additional state info that is more complicated than
642 integers can be converted into an integer by marshaling/pickling the info
643 and encoding the bytes of the resulting string into an integer.)
Georg Brandl116aa622007-08-15 14:28:22 +0000644
Georg Brandl116aa622007-08-15 14:28:22 +0000645
Benjamin Petersone41251e2008-04-25 01:59:09 +0000646 .. method:: setstate(state)
Georg Brandl116aa622007-08-15 14:28:22 +0000647
Christopher Thorneb5e29592019-04-11 07:09:29 +0100648 Set the state of the decoder to *state*. *state* must be a decoder state
Benjamin Petersone41251e2008-04-25 01:59:09 +0000649 returned by :meth:`getstate`.
650
Georg Brandl116aa622007-08-15 14:28:22 +0000651
Nick Coghlanb9fdb7a2015-01-07 00:22:00 +1000652Stream Encoding and Decoding
653^^^^^^^^^^^^^^^^^^^^^^^^^^^^
654
655
Georg Brandl116aa622007-08-15 14:28:22 +0000656The :class:`StreamWriter` and :class:`StreamReader` classes provide generic
657working interfaces which can be used to implement new encoding submodules very
658easily. See :mod:`encodings.utf_8` for an example of how this is done.
659
660
661.. _stream-writer-objects:
662
663StreamWriter Objects
Nick Coghlanb9fdb7a2015-01-07 00:22:00 +1000664~~~~~~~~~~~~~~~~~~~~
Georg Brandl116aa622007-08-15 14:28:22 +0000665
666The :class:`StreamWriter` class is a subclass of :class:`Codec` and defines the
667following methods which every stream writer must define in order to be
668compatible with the Python codec registry.
669
670
Nick Coghlanb9fdb7a2015-01-07 00:22:00 +1000671.. class:: StreamWriter(stream, errors='strict')
Georg Brandl116aa622007-08-15 14:28:22 +0000672
673 Constructor for a :class:`StreamWriter` instance.
674
675 All stream writers must provide this constructor interface. They are free to add
676 additional keyword arguments, but only the ones defined here are used by the
677 Python codec registry.
678
Nick Coghlanb9fdb7a2015-01-07 00:22:00 +1000679 The *stream* argument must be a file-like object open for writing
680 text or binary data, as appropriate for the specific codec.
Georg Brandl116aa622007-08-15 14:28:22 +0000681
682 The :class:`StreamWriter` may implement different error handling schemes by
Nick Coghlanb9fdb7a2015-01-07 00:22:00 +1000683 providing the *errors* keyword argument. See :ref:`error-handlers` for
684 the standard error handlers the underlying stream codec may support.
Serhiy Storchaka166ebc42014-11-25 13:57:17 +0200685
Georg Brandl116aa622007-08-15 14:28:22 +0000686 The *errors* argument will be assigned to an attribute of the same name.
687 Assigning to this attribute makes it possible to switch between different error
688 handling strategies during the lifetime of the :class:`StreamWriter` object.
689
Benjamin Petersone41251e2008-04-25 01:59:09 +0000690 .. method:: write(object)
Georg Brandl116aa622007-08-15 14:28:22 +0000691
Benjamin Petersone41251e2008-04-25 01:59:09 +0000692 Writes the object's contents encoded to the stream.
Georg Brandl116aa622007-08-15 14:28:22 +0000693
694
Benjamin Petersone41251e2008-04-25 01:59:09 +0000695 .. method:: writelines(list)
Georg Brandl116aa622007-08-15 14:28:22 +0000696
Benjamin Petersone41251e2008-04-25 01:59:09 +0000697 Writes the concatenated list of strings to the stream (possibly by reusing
Nick Coghlanb9fdb7a2015-01-07 00:22:00 +1000698 the :meth:`write` method). The standard bytes-to-bytes codecs
699 do not support this method.
Georg Brandl116aa622007-08-15 14:28:22 +0000700
701
Benjamin Petersone41251e2008-04-25 01:59:09 +0000702 .. method:: reset()
Georg Brandl116aa622007-08-15 14:28:22 +0000703
Berker Peksag1a9f51e2021-01-06 04:14:42 +0200704 Resets the codec buffers used for keeping internal state.
Georg Brandl116aa622007-08-15 14:28:22 +0000705
Benjamin Petersone41251e2008-04-25 01:59:09 +0000706 Calling this method should ensure that the data on the output is put into
707 a clean state that allows appending of new fresh data without having to
708 rescan the whole stream to recover state.
709
Georg Brandl116aa622007-08-15 14:28:22 +0000710
711In addition to the above methods, the :class:`StreamWriter` must also inherit
712all other methods and attributes from the underlying stream.
713
714
715.. _stream-reader-objects:
716
717StreamReader Objects
Nick Coghlanb9fdb7a2015-01-07 00:22:00 +1000718~~~~~~~~~~~~~~~~~~~~
Georg Brandl116aa622007-08-15 14:28:22 +0000719
720The :class:`StreamReader` class is a subclass of :class:`Codec` and defines the
721following methods which every stream reader must define in order to be
722compatible with the Python codec registry.
723
724
Nick Coghlanb9fdb7a2015-01-07 00:22:00 +1000725.. class:: StreamReader(stream, errors='strict')
Georg Brandl116aa622007-08-15 14:28:22 +0000726
727 Constructor for a :class:`StreamReader` instance.
728
729 All stream readers must provide this constructor interface. They are free to add
730 additional keyword arguments, but only the ones defined here are used by the
731 Python codec registry.
732
Nick Coghlanb9fdb7a2015-01-07 00:22:00 +1000733 The *stream* argument must be a file-like object open for reading
734 text or binary data, as appropriate for the specific codec.
Georg Brandl116aa622007-08-15 14:28:22 +0000735
736 The :class:`StreamReader` may implement different error handling schemes by
Nick Coghlanb9fdb7a2015-01-07 00:22:00 +1000737 providing the *errors* keyword argument. See :ref:`error-handlers` for
738 the standard error handlers the underlying stream codec may support.
Georg Brandl116aa622007-08-15 14:28:22 +0000739
740 The *errors* argument will be assigned to an attribute of the same name.
741 Assigning to this attribute makes it possible to switch between different error
742 handling strategies during the lifetime of the :class:`StreamReader` object.
743
744 The set of allowed values for the *errors* argument can be extended with
745 :func:`register_error`.
746
747
Benjamin Petersone41251e2008-04-25 01:59:09 +0000748 .. method:: read([size[, chars, [firstline]]])
Georg Brandl116aa622007-08-15 14:28:22 +0000749
Benjamin Petersone41251e2008-04-25 01:59:09 +0000750 Decodes data from the stream and returns the resulting object.
Georg Brandl116aa622007-08-15 14:28:22 +0000751
Nick Coghlanb9fdb7a2015-01-07 00:22:00 +1000752 The *chars* argument indicates the number of decoded
753 code points or bytes to return. The :func:`read` method will
754 never return more data than requested, but it might return less,
755 if there is not enough available.
Georg Brandl116aa622007-08-15 14:28:22 +0000756
Nick Coghlanb9fdb7a2015-01-07 00:22:00 +1000757 The *size* argument indicates the approximate maximum
758 number of encoded bytes or code points to read
759 for decoding. The decoder can modify this setting as
Benjamin Petersone41251e2008-04-25 01:59:09 +0000760 appropriate. The default value -1 indicates to read and decode as much as
Géry Ogam891e9e32019-09-12 09:41:32 +0200761 possible. This parameter is intended to
Nick Coghlanb9fdb7a2015-01-07 00:22:00 +1000762 prevent having to decode huge files in one step.
Georg Brandl116aa622007-08-15 14:28:22 +0000763
Nick Coghlanb9fdb7a2015-01-07 00:22:00 +1000764 The *firstline* flag indicates that
765 it would be sufficient to only return the first
Benjamin Petersone41251e2008-04-25 01:59:09 +0000766 line, if there are decoding errors on later lines.
Georg Brandl116aa622007-08-15 14:28:22 +0000767
Benjamin Petersone41251e2008-04-25 01:59:09 +0000768 The method should use a greedy read strategy meaning that it should read
769 as much data as is allowed within the definition of the encoding and the
770 given size, e.g. if optional encoding endings or state markers are
771 available on the stream, these should be read too.
Georg Brandl116aa622007-08-15 14:28:22 +0000772
Georg Brandl116aa622007-08-15 14:28:22 +0000773
Benjamin Petersone41251e2008-04-25 01:59:09 +0000774 .. method:: readline([size[, keepends]])
Georg Brandl116aa622007-08-15 14:28:22 +0000775
Benjamin Petersone41251e2008-04-25 01:59:09 +0000776 Read one line from the input stream and return the decoded data.
Georg Brandl116aa622007-08-15 14:28:22 +0000777
Benjamin Petersone41251e2008-04-25 01:59:09 +0000778 *size*, if given, is passed as size argument to the stream's
Serhiy Storchakacca40ff2013-07-11 18:26:13 +0300779 :meth:`read` method.
Georg Brandl116aa622007-08-15 14:28:22 +0000780
Benjamin Petersone41251e2008-04-25 01:59:09 +0000781 If *keepends* is false line-endings will be stripped from the lines
782 returned.
Georg Brandl116aa622007-08-15 14:28:22 +0000783
Georg Brandl116aa622007-08-15 14:28:22 +0000784
Benjamin Petersone41251e2008-04-25 01:59:09 +0000785 .. method:: readlines([sizehint[, keepends]])
Georg Brandl116aa622007-08-15 14:28:22 +0000786
Benjamin Petersone41251e2008-04-25 01:59:09 +0000787 Read all lines available on the input stream and return them as a list of
788 lines.
Georg Brandl116aa622007-08-15 14:28:22 +0000789
Géry Ogam891e9e32019-09-12 09:41:32 +0200790 Line-endings are implemented using the codec's :meth:`decode` method and
791 are included in the list entries if *keepends* is true.
Georg Brandl116aa622007-08-15 14:28:22 +0000792
Benjamin Petersone41251e2008-04-25 01:59:09 +0000793 *sizehint*, if given, is passed as the *size* argument to the stream's
794 :meth:`read` method.
Georg Brandl116aa622007-08-15 14:28:22 +0000795
796
Benjamin Petersone41251e2008-04-25 01:59:09 +0000797 .. method:: reset()
Georg Brandl116aa622007-08-15 14:28:22 +0000798
Berker Peksag1a9f51e2021-01-06 04:14:42 +0200799 Resets the codec buffers used for keeping internal state.
Georg Brandl116aa622007-08-15 14:28:22 +0000800
Géry Ogam891e9e32019-09-12 09:41:32 +0200801 Note that no stream repositioning should take place. This method is
Benjamin Petersone41251e2008-04-25 01:59:09 +0000802 primarily intended to be able to recover from decoding errors.
803
Georg Brandl116aa622007-08-15 14:28:22 +0000804
805In addition to the above methods, the :class:`StreamReader` must also inherit
806all other methods and attributes from the underlying stream.
807
Georg Brandl116aa622007-08-15 14:28:22 +0000808.. _stream-reader-writer:
809
810StreamReaderWriter 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:`StreamReaderWriter` is a convenience class that allows wrapping
814streams which work in both read and write modes.
Georg Brandl116aa622007-08-15 14:28:22 +0000815
816The design is such that one can use the factory functions returned by the
817:func:`lookup` function to construct the instance.
818
819
Pablo Galindoe184cfd2017-11-10 23:05:12 +0000820.. class:: StreamReaderWriter(stream, Reader, Writer, errors='strict')
Georg Brandl116aa622007-08-15 14:28:22 +0000821
822 Creates a :class:`StreamReaderWriter` instance. *stream* must be a file-like
823 object. *Reader* and *Writer* must be factory functions or classes providing the
824 :class:`StreamReader` and :class:`StreamWriter` interface resp. Error handling
825 is done in the same way as defined for the stream readers and writers.
826
827:class:`StreamReaderWriter` instances define the combined interfaces of
828:class:`StreamReader` and :class:`StreamWriter` classes. They inherit all other
829methods and attributes from the underlying stream.
830
831
832.. _stream-recoder-objects:
833
834StreamRecoder Objects
Nick Coghlanb9fdb7a2015-01-07 00:22:00 +1000835~~~~~~~~~~~~~~~~~~~~~
Georg Brandl116aa622007-08-15 14:28:22 +0000836
Nick Coghlanb9fdb7a2015-01-07 00:22:00 +1000837The :class:`StreamRecoder` translates data from one encoding to another,
Georg Brandl116aa622007-08-15 14:28:22 +0000838which is sometimes useful when dealing with different encoding environments.
839
840The design is such that one can use the factory functions returned by the
841:func:`lookup` function to construct the instance.
842
843
Pablo Galindoe184cfd2017-11-10 23:05:12 +0000844.. class:: StreamRecoder(stream, encode, decode, Reader, Writer, errors='strict')
Georg Brandl116aa622007-08-15 14:28:22 +0000845
846 Creates a :class:`StreamRecoder` instance which implements a two-way conversion:
Nick Coghlanb9fdb7a2015-01-07 00:22:00 +1000847 *encode* and *decode* work on the frontend — the data visible to
848 code calling :meth:`read` and :meth:`write`, while *Reader* and *Writer*
849 work on the backend — the data in *stream*.
Georg Brandl116aa622007-08-15 14:28:22 +0000850
Géry Ogam891e9e32019-09-12 09:41:32 +0200851 You can use these objects to do transparent transcodings, e.g., from Latin-1
Georg Brandl116aa622007-08-15 14:28:22 +0000852 to UTF-8 and back.
853
Nick Coghlanb9fdb7a2015-01-07 00:22:00 +1000854 The *stream* argument must be a file-like object.
Georg Brandl116aa622007-08-15 14:28:22 +0000855
Nick Coghlanb9fdb7a2015-01-07 00:22:00 +1000856 The *encode* and *decode* arguments must
857 adhere to the :class:`Codec` interface. *Reader* and
Georg Brandl116aa622007-08-15 14:28:22 +0000858 *Writer* must be factory functions or classes providing objects of the
859 :class:`StreamReader` and :class:`StreamWriter` interface respectively.
860
Georg Brandl116aa622007-08-15 14:28:22 +0000861 Error handling is done in the same way as defined for the stream readers and
862 writers.
863
Benjamin Petersone41251e2008-04-25 01:59:09 +0000864
Georg Brandl116aa622007-08-15 14:28:22 +0000865:class:`StreamRecoder` instances define the combined interfaces of
866:class:`StreamReader` and :class:`StreamWriter` classes. They inherit all other
867methods and attributes from the underlying stream.
868
869
870.. _encodings-overview:
871
872Encodings and Unicode
873---------------------
874
Georg Brandl3be472b2015-01-14 08:26:30 +0100875Strings are stored internally as sequences of code points in
Géry Ogam891e9e32019-09-12 09:41:32 +0200876range ``0x0``--``0x10FFFF``. (See :pep:`393` for
Nick Coghlanb9fdb7a2015-01-07 00:22:00 +1000877more details about the implementation.)
878Once a string object is used outside of CPU and memory, endianness
Géry Ogam891e9e32019-09-12 09:41:32 +0200879and how these arrays are stored as bytes become an issue. As with other
Nick Coghlanb9fdb7a2015-01-07 00:22:00 +1000880codecs, serialising a string into a sequence of bytes is known as *encoding*,
881and recreating the string from the sequence of bytes is known as *decoding*.
882There are a variety of different text serialisation codecs, which are
883collectivity referred to as :term:`text encodings <text encoding>`.
884
885The simplest text encoding (called ``'latin-1'`` or ``'iso-8859-1'``) maps
Serhiy Storchakac7b1a0b2016-11-26 13:43:28 +0200886the code points 0--255 to the bytes ``0x0``--``0xff``, which means that a string
Georg Brandl3be472b2015-01-14 08:26:30 +0100887object that contains code points above ``U+00FF`` can't be encoded with this
Nick Coghlanb9fdb7a2015-01-07 00:22:00 +1000888codec. Doing so will raise a :exc:`UnicodeEncodeError` that looks
889like the following (although the details of the error message may differ):
890``UnicodeEncodeError: 'latin-1' codec can't encode character '\u1234' in
891position 3: ordinal not in range(256)``.
Georg Brandl116aa622007-08-15 14:28:22 +0000892
893There's another group of encodings (the so called charmap encodings) that choose
Georg Brandl3be472b2015-01-14 08:26:30 +0100894a different subset of all Unicode code points and how these code points are
Serhiy Storchakac7b1a0b2016-11-26 13:43:28 +0200895mapped to the bytes ``0x0``--``0xff``. To see how this is done simply open
Georg Brandl116aa622007-08-15 14:28:22 +0000896e.g. :file:`encodings/cp1252.py` (which is an encoding that is used primarily on
897Windows). There's a string constant with 256 characters that shows you which
898character is mapped to which byte value.
899
Georg Brandl3be472b2015-01-14 08:26:30 +0100900All of these encodings can only encode 256 of the 1114112 code points
Georg Brandl30c78d62008-05-11 14:52:00 +0000901defined in Unicode. A simple and straightforward way that can store each Unicode
Georg Brandl3be472b2015-01-14 08:26:30 +0100902code point, is to store each code point as four consecutive bytes. There are two
Ezio Melottifbb39812011-10-25 10:40:38 +0300903possibilities: store the bytes in big endian or in little endian order. These
904two encodings are called ``UTF-32-BE`` and ``UTF-32-LE`` respectively. Their
905disadvantage is that if e.g. you use ``UTF-32-BE`` on a little endian machine you
906will always have to swap bytes on encoding and decoding. ``UTF-32`` avoids this
907problem: bytes will always be in natural endianness. When these bytes are read
Georg Brandl116aa622007-08-15 14:28:22 +0000908by a CPU with a different endianness, then bytes have to be swapped though. To
Ezio Melottifbb39812011-10-25 10:40:38 +0300909be able to detect the endianness of a ``UTF-16`` or ``UTF-32`` byte sequence,
910there's the so called BOM ("Byte Order Mark"). This is the Unicode character
911``U+FEFF``. This character can be prepended to every ``UTF-16`` or ``UTF-32``
912byte sequence. The byte swapped version of this character (``0xFFFE``) is an
913illegal character that may not appear in a Unicode text. So when the
914first character in an ``UTF-16`` or ``UTF-32`` byte sequence
Georg Brandl116aa622007-08-15 14:28:22 +0000915appears to be a ``U+FFFE`` the bytes have to be swapped on decoding.
Ezio Melottifbb39812011-10-25 10:40:38 +0300916Unfortunately the character ``U+FEFF`` had a second purpose as
917a ``ZERO WIDTH NO-BREAK SPACE``: a character that has no width and doesn't allow
Georg Brandl116aa622007-08-15 14:28:22 +0000918a word to be split. It can e.g. be used to give hints to a ligature algorithm.
919With Unicode 4.0 using ``U+FEFF`` as a ``ZERO WIDTH NO-BREAK SPACE`` has been
920deprecated (with ``U+2060`` (``WORD JOINER``) assuming this role). Nevertheless
Ezio Melottifbb39812011-10-25 10:40:38 +0300921Unicode software still must be able to handle ``U+FEFF`` in both roles: as a BOM
Georg Brandl116aa622007-08-15 14:28:22 +0000922it's a device to determine the storage layout of the encoded bytes, and vanishes
Georg Brandl30c78d62008-05-11 14:52:00 +0000923once the byte sequence has been decoded into a string; as a ``ZERO WIDTH
Georg Brandl116aa622007-08-15 14:28:22 +0000924NO-BREAK SPACE`` it's a normal character that will be decoded like any other.
925
926There's another encoding that is able to encoding the full range of Unicode
927characters: UTF-8. UTF-8 is an 8-bit encoding, which means there are no issues
928with byte order in UTF-8. Each byte in a UTF-8 byte sequence consists of two
Ezio Melottifbb39812011-10-25 10:40:38 +0300929parts: marker bits (the most significant bits) and payload bits. The marker bits
Ezio Melotti222b2082011-09-01 08:11:28 +0300930are a sequence of zero to four ``1`` bits followed by a ``0`` bit. Unicode characters are
Georg Brandl116aa622007-08-15 14:28:22 +0000931encoded like this (with x being payload bits, which when concatenated give the
932Unicode character):
933
934+-----------------------------------+----------------------------------------------+
935| Range | Encoding |
936+===================================+==============================================+
937| ``U-00000000`` ... ``U-0000007F`` | 0xxxxxxx |
938+-----------------------------------+----------------------------------------------+
939| ``U-00000080`` ... ``U-000007FF`` | 110xxxxx 10xxxxxx |
940+-----------------------------------+----------------------------------------------+
941| ``U-00000800`` ... ``U-0000FFFF`` | 1110xxxx 10xxxxxx 10xxxxxx |
942+-----------------------------------+----------------------------------------------+
Ezio Melotti222b2082011-09-01 08:11:28 +0300943| ``U-00010000`` ... ``U-0010FFFF`` | 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx |
Georg Brandl116aa622007-08-15 14:28:22 +0000944+-----------------------------------+----------------------------------------------+
945
946The least significant bit of the Unicode character is the rightmost x bit.
947
948As UTF-8 is an 8-bit encoding no BOM is required and any ``U+FEFF`` character in
Georg Brandl30c78d62008-05-11 14:52:00 +0000949the decoded string (even if it's the first character) is treated as a ``ZERO
950WIDTH NO-BREAK SPACE``.
Georg Brandl116aa622007-08-15 14:28:22 +0000951
952Without external information it's impossible to reliably determine which
Georg Brandl30c78d62008-05-11 14:52:00 +0000953encoding was used for encoding a string. Each charmap encoding can
Georg Brandl116aa622007-08-15 14:28:22 +0000954decode any random byte sequence. However that's not possible with UTF-8, as
955UTF-8 byte sequences have a structure that doesn't allow arbitrary byte
Thomas Wouters89d996e2007-09-08 17:39:28 +0000956sequences. To increase the reliability with which a UTF-8 encoding can be
Georg Brandl116aa622007-08-15 14:28:22 +0000957detected, Microsoft invented a variant of UTF-8 (that Python 2.5 calls
958``"utf-8-sig"``) for its Notepad program: Before any of the Unicode characters
959is written to the file, a UTF-8 encoded BOM (which looks like this as a byte
960sequence: ``0xef``, ``0xbb``, ``0xbf``) is written. As it's rather improbable
961that any charmap encoded file starts with these byte values (which would e.g.
962map to
963
964 | LATIN SMALL LETTER I WITH DIAERESIS
965 | RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK
966 | INVERTED QUESTION MARK
967
Ezio Melottifbb39812011-10-25 10:40:38 +0300968in iso-8859-1), this increases the probability that a ``utf-8-sig`` encoding can be
Georg Brandl116aa622007-08-15 14:28:22 +0000969correctly guessed from the byte sequence. So here the BOM is not used to be able
970to determine the byte order used for generating the byte sequence, but as a
971signature that helps in guessing the encoding. On encoding the utf-8-sig codec
972will write ``0xef``, ``0xbb``, ``0xbf`` as the first three bytes to the file. On
Ezio Melottifbb39812011-10-25 10:40:38 +0300973decoding ``utf-8-sig`` will skip those three bytes if they appear as the first
Géry Ogam891e9e32019-09-12 09:41:32 +0200974three bytes in the file. In UTF-8, the use of the BOM is discouraged and
Ezio Melottifbb39812011-10-25 10:40:38 +0300975should generally be avoided.
Georg Brandl116aa622007-08-15 14:28:22 +0000976
977
978.. _standard-encodings:
979
980Standard Encodings
981------------------
982
983Python comes with a number of codecs built-in, either implemented as C functions
984or with dictionaries as mapping tables. The following table lists the codecs by
985name, together with a few common aliases, and the languages for which the
986encoding is likely used. Neither the list of aliases nor the list of languages
987is meant to be exhaustive. Notice that spelling alternatives that only differ in
Georg Brandla6053b42009-09-01 08:11:14 +0000988case or use a hyphen instead of an underscore are also valid aliases; therefore,
989e.g. ``'utf-8'`` is a valid alias for the ``'utf_8'`` codec.
Georg Brandl116aa622007-08-15 14:28:22 +0000990
Alexander Belopolsky1d521462011-02-25 19:19:57 +0000991.. impl-detail::
992
993 Some common encodings can bypass the codecs lookup machinery to
Géry Ogam891e9e32019-09-12 09:41:32 +0200994 improve performance. These optimization opportunities are only
Ville Skyttä297fd872017-12-15 12:19:23 +0200995 recognized by CPython for a limited set of (case insensitive)
996 aliases: utf-8, utf8, latin-1, latin1, iso-8859-1, iso8859-1, mbcs
997 (Windows only), ascii, us-ascii, utf-16, utf16, utf-32, utf32, and
998 the same using underscores instead of dashes. Using alternative
999 aliases for these encodings may result in slower execution.
1000
1001 .. versionchanged:: 3.6
1002 Optimization opportunity recognized for us-ascii.
Alexander Belopolsky1d521462011-02-25 19:19:57 +00001003
Georg Brandl116aa622007-08-15 14:28:22 +00001004Many of the character sets support the same languages. They vary in individual
1005characters (e.g. whether the EURO SIGN is supported or not), and in the
1006assignment of characters to code positions. For the European languages in
1007particular, the following variants typically exist:
1008
1009* an ISO 8859 codeset
1010
Martin Panter4c359642016-05-08 13:53:41 +00001011* a Microsoft Windows code page, which is typically derived from an 8859 codeset,
Georg Brandl116aa622007-08-15 14:28:22 +00001012 but replaces control characters with additional graphic characters
1013
1014* an IBM EBCDIC code page
1015
1016* an IBM PC code page, which is ASCII compatible
1017
Georg Brandl44ea77b2013-03-28 13:28:44 +01001018.. tabularcolumns:: |l|p{0.3\linewidth}|p{0.3\linewidth}|
1019
Georg Brandl116aa622007-08-15 14:28:22 +00001020+-----------------+--------------------------------+--------------------------------+
1021| Codec | Aliases | Languages |
1022+=================+================================+================================+
1023| ascii | 646, us-ascii | English |
1024+-----------------+--------------------------------+--------------------------------+
1025| big5 | big5-tw, csbig5 | Traditional Chinese |
1026+-----------------+--------------------------------+--------------------------------+
1027| big5hkscs | big5-hkscs, hkscs | Traditional Chinese |
1028+-----------------+--------------------------------+--------------------------------+
1029| cp037 | IBM037, IBM039 | English |
1030+-----------------+--------------------------------+--------------------------------+
R David Murray47d083c2014-03-07 21:00:34 -05001031| cp273 | 273, IBM273, csIBM273 | German |
1032| | | |
1033| | | .. versionadded:: 3.4 |
1034+-----------------+--------------------------------+--------------------------------+
Georg Brandl116aa622007-08-15 14:28:22 +00001035| cp424 | EBCDIC-CP-HE, IBM424 | Hebrew |
1036+-----------------+--------------------------------+--------------------------------+
1037| cp437 | 437, IBM437 | English |
1038+-----------------+--------------------------------+--------------------------------+
1039| cp500 | EBCDIC-CP-BE, EBCDIC-CP-CH, | Western Europe |
1040| | IBM500 | |
1041+-----------------+--------------------------------+--------------------------------+
Amaury Forgeot d'Arcae6388d2009-07-15 19:21:18 +00001042| cp720 | | Arabic |
1043+-----------------+--------------------------------+--------------------------------+
Georg Brandl116aa622007-08-15 14:28:22 +00001044| cp737 | | Greek |
1045+-----------------+--------------------------------+--------------------------------+
1046| cp775 | IBM775 | Baltic languages |
1047+-----------------+--------------------------------+--------------------------------+
1048| cp850 | 850, IBM850 | Western Europe |
1049+-----------------+--------------------------------+--------------------------------+
1050| cp852 | 852, IBM852 | Central and Eastern Europe |
1051+-----------------+--------------------------------+--------------------------------+
1052| cp855 | 855, IBM855 | Bulgarian, Byelorussian, |
1053| | | Macedonian, Russian, Serbian |
1054+-----------------+--------------------------------+--------------------------------+
1055| cp856 | | Hebrew |
1056+-----------------+--------------------------------+--------------------------------+
1057| cp857 | 857, IBM857 | Turkish |
1058+-----------------+--------------------------------+--------------------------------+
Benjamin Peterson5a6214a2010-06-27 22:41:29 +00001059| cp858 | 858, IBM858 | Western Europe |
1060+-----------------+--------------------------------+--------------------------------+
Georg Brandl116aa622007-08-15 14:28:22 +00001061| cp860 | 860, IBM860 | Portuguese |
1062+-----------------+--------------------------------+--------------------------------+
1063| cp861 | 861, CP-IS, IBM861 | Icelandic |
1064+-----------------+--------------------------------+--------------------------------+
1065| cp862 | 862, IBM862 | Hebrew |
1066+-----------------+--------------------------------+--------------------------------+
1067| cp863 | 863, IBM863 | Canadian |
1068+-----------------+--------------------------------+--------------------------------+
1069| cp864 | IBM864 | Arabic |
1070+-----------------+--------------------------------+--------------------------------+
1071| cp865 | 865, IBM865 | Danish, Norwegian |
1072+-----------------+--------------------------------+--------------------------------+
1073| cp866 | 866, IBM866 | Russian |
1074+-----------------+--------------------------------+--------------------------------+
1075| cp869 | 869, CP-GR, IBM869 | Greek |
1076+-----------------+--------------------------------+--------------------------------+
1077| cp874 | | Thai |
1078+-----------------+--------------------------------+--------------------------------+
1079| cp875 | | Greek |
1080+-----------------+--------------------------------+--------------------------------+
1081| cp932 | 932, ms932, mskanji, ms-kanji | Japanese |
1082+-----------------+--------------------------------+--------------------------------+
1083| cp949 | 949, ms949, uhc | Korean |
1084+-----------------+--------------------------------+--------------------------------+
1085| cp950 | 950, ms950 | Traditional Chinese |
1086+-----------------+--------------------------------+--------------------------------+
1087| cp1006 | | Urdu |
1088+-----------------+--------------------------------+--------------------------------+
1089| cp1026 | ibm1026 | Turkish |
1090+-----------------+--------------------------------+--------------------------------+
Serhiy Storchakabe0c3252013-11-23 18:52:23 +02001091| cp1125 | 1125, ibm1125, cp866u, ruscii | Ukrainian |
1092| | | |
1093| | | .. versionadded:: 3.4 |
1094+-----------------+--------------------------------+--------------------------------+
Georg Brandl116aa622007-08-15 14:28:22 +00001095| cp1140 | ibm1140 | Western Europe |
1096+-----------------+--------------------------------+--------------------------------+
1097| cp1250 | windows-1250 | Central and Eastern Europe |
1098+-----------------+--------------------------------+--------------------------------+
1099| cp1251 | windows-1251 | Bulgarian, Byelorussian, |
1100| | | Macedonian, Russian, Serbian |
1101+-----------------+--------------------------------+--------------------------------+
1102| cp1252 | windows-1252 | Western Europe |
1103+-----------------+--------------------------------+--------------------------------+
1104| cp1253 | windows-1253 | Greek |
1105+-----------------+--------------------------------+--------------------------------+
1106| cp1254 | windows-1254 | Turkish |
1107+-----------------+--------------------------------+--------------------------------+
1108| cp1255 | windows-1255 | Hebrew |
1109+-----------------+--------------------------------+--------------------------------+
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00001110| cp1256 | windows-1256 | Arabic |
Georg Brandl116aa622007-08-15 14:28:22 +00001111+-----------------+--------------------------------+--------------------------------+
1112| cp1257 | windows-1257 | Baltic languages |
1113+-----------------+--------------------------------+--------------------------------+
1114| cp1258 | windows-1258 | Vietnamese |
1115+-----------------+--------------------------------+--------------------------------+
1116| euc_jp | eucjp, ujis, u-jis | Japanese |
1117+-----------------+--------------------------------+--------------------------------+
1118| euc_jis_2004 | jisx0213, eucjis2004 | Japanese |
1119+-----------------+--------------------------------+--------------------------------+
1120| euc_jisx0213 | eucjisx0213 | Japanese |
1121+-----------------+--------------------------------+--------------------------------+
1122| euc_kr | euckr, korean, ksc5601, | Korean |
1123| | ks_c-5601, ks_c-5601-1987, | |
1124| | ksx1001, ks_x-1001 | |
1125+-----------------+--------------------------------+--------------------------------+
Serhiy Storchaka3f819ca2018-10-31 02:26:06 +02001126| gb2312 | chinese, csiso58gb231280, | Simplified Chinese |
1127| | euc-cn, euccn, eucgb2312-cn, | |
1128| | gb2312-1980, gb2312-80, | |
1129| | iso-ir-58 | |
Georg Brandl116aa622007-08-15 14:28:22 +00001130+-----------------+--------------------------------+--------------------------------+
1131| gbk | 936, cp936, ms936 | Unified Chinese |
1132+-----------------+--------------------------------+--------------------------------+
1133| gb18030 | gb18030-2000 | Unified Chinese |
1134+-----------------+--------------------------------+--------------------------------+
1135| hz | hzgb, hz-gb, hz-gb-2312 | Simplified Chinese |
1136+-----------------+--------------------------------+--------------------------------+
1137| iso2022_jp | csiso2022jp, iso2022jp, | Japanese |
1138| | iso-2022-jp | |
1139+-----------------+--------------------------------+--------------------------------+
1140| iso2022_jp_1 | iso2022jp-1, iso-2022-jp-1 | Japanese |
1141+-----------------+--------------------------------+--------------------------------+
1142| iso2022_jp_2 | iso2022jp-2, iso-2022-jp-2 | Japanese, Korean, Simplified |
1143| | | Chinese, Western Europe, Greek |
1144+-----------------+--------------------------------+--------------------------------+
1145| iso2022_jp_2004 | iso2022jp-2004, | Japanese |
1146| | iso-2022-jp-2004 | |
1147+-----------------+--------------------------------+--------------------------------+
1148| iso2022_jp_3 | iso2022jp-3, iso-2022-jp-3 | Japanese |
1149+-----------------+--------------------------------+--------------------------------+
1150| iso2022_jp_ext | iso2022jp-ext, iso-2022-jp-ext | Japanese |
1151+-----------------+--------------------------------+--------------------------------+
1152| iso2022_kr | csiso2022kr, iso2022kr, | Korean |
1153| | iso-2022-kr | |
1154+-----------------+--------------------------------+--------------------------------+
Géry Ogam891e9e32019-09-12 09:41:32 +02001155| latin_1 | iso-8859-1, iso8859-1, 8859, | Western Europe |
Georg Brandl116aa622007-08-15 14:28:22 +00001156| | cp819, latin, latin1, L1 | |
1157+-----------------+--------------------------------+--------------------------------+
1158| iso8859_2 | iso-8859-2, latin2, L2 | Central and Eastern Europe |
1159+-----------------+--------------------------------+--------------------------------+
1160| iso8859_3 | iso-8859-3, latin3, L3 | Esperanto, Maltese |
1161+-----------------+--------------------------------+--------------------------------+
Christian Heimesc3f30c42008-02-22 16:37:40 +00001162| iso8859_4 | iso-8859-4, latin4, L4 | Baltic languages |
Georg Brandl116aa622007-08-15 14:28:22 +00001163+-----------------+--------------------------------+--------------------------------+
1164| iso8859_5 | iso-8859-5, cyrillic | Bulgarian, Byelorussian, |
1165| | | Macedonian, Russian, Serbian |
1166+-----------------+--------------------------------+--------------------------------+
1167| iso8859_6 | iso-8859-6, arabic | Arabic |
1168+-----------------+--------------------------------+--------------------------------+
1169| iso8859_7 | iso-8859-7, greek, greek8 | Greek |
1170+-----------------+--------------------------------+--------------------------------+
1171| iso8859_8 | iso-8859-8, hebrew | Hebrew |
1172+-----------------+--------------------------------+--------------------------------+
1173| iso8859_9 | iso-8859-9, latin5, L5 | Turkish |
1174+-----------------+--------------------------------+--------------------------------+
1175| iso8859_10 | iso-8859-10, latin6, L6 | Nordic languages |
1176+-----------------+--------------------------------+--------------------------------+
Victor Stinnerbfd97672015-09-24 09:04:05 +02001177| iso8859_11 | iso-8859-11, thai | Thai languages |
1178+-----------------+--------------------------------+--------------------------------+
Georg Brandl93dc9eb2010-03-14 10:56:14 +00001179| iso8859_13 | iso-8859-13, latin7, L7 | Baltic languages |
Georg Brandl116aa622007-08-15 14:28:22 +00001180+-----------------+--------------------------------+--------------------------------+
1181| iso8859_14 | iso-8859-14, latin8, L8 | Celtic languages |
1182+-----------------+--------------------------------+--------------------------------+
Georg Brandl93dc9eb2010-03-14 10:56:14 +00001183| iso8859_15 | iso-8859-15, latin9, L9 | Western Europe |
1184+-----------------+--------------------------------+--------------------------------+
1185| iso8859_16 | iso-8859-16, latin10, L10 | South-Eastern Europe |
Georg Brandl116aa622007-08-15 14:28:22 +00001186+-----------------+--------------------------------+--------------------------------+
1187| johab | cp1361, ms1361 | Korean |
1188+-----------------+--------------------------------+--------------------------------+
1189| koi8_r | | Russian |
1190+-----------------+--------------------------------+--------------------------------+
Serhiy Storchakaf0eeedf2015-05-12 23:24:19 +03001191| koi8_t | | Tajik |
1192| | | |
1193| | | .. versionadded:: 3.5 |
1194+-----------------+--------------------------------+--------------------------------+
Georg Brandl116aa622007-08-15 14:28:22 +00001195| koi8_u | | Ukrainian |
1196+-----------------+--------------------------------+--------------------------------+
Serhiy Storchakaad8a1c32015-05-12 23:16:55 +03001197| kz1048 | kz_1048, strk1048_2002, rk1048 | Kazakh |
1198| | | |
1199| | | .. versionadded:: 3.5 |
1200+-----------------+--------------------------------+--------------------------------+
Georg Brandl116aa622007-08-15 14:28:22 +00001201| mac_cyrillic | maccyrillic | Bulgarian, Byelorussian, |
1202| | | Macedonian, Russian, Serbian |
1203+-----------------+--------------------------------+--------------------------------+
1204| mac_greek | macgreek | Greek |
1205+-----------------+--------------------------------+--------------------------------+
1206| mac_iceland | maciceland | Icelandic |
1207+-----------------+--------------------------------+--------------------------------+
Ashwin Ramaswamic4c15ed2019-06-05 15:18:07 -07001208| mac_latin2 | maclatin2, maccentraleurope, | Central and Eastern Europe |
1209| | mac_centeuro | |
Georg Brandl116aa622007-08-15 14:28:22 +00001210+-----------------+--------------------------------+--------------------------------+
Benjamin Peterson23110e72010-08-21 02:54:44 +00001211| mac_roman | macroman, macintosh | Western Europe |
Georg Brandl116aa622007-08-15 14:28:22 +00001212+-----------------+--------------------------------+--------------------------------+
1213| mac_turkish | macturkish | Turkish |
1214+-----------------+--------------------------------+--------------------------------+
1215| ptcp154 | csptcp154, pt154, cp154, | Kazakh |
1216| | cyrillic-asian | |
1217+-----------------+--------------------------------+--------------------------------+
1218| shift_jis | csshiftjis, shiftjis, sjis, | Japanese |
1219| | s_jis | |
1220+-----------------+--------------------------------+--------------------------------+
1221| shift_jis_2004 | shiftjis2004, sjis_2004, | Japanese |
1222| | sjis2004 | |
1223+-----------------+--------------------------------+--------------------------------+
1224| shift_jisx0213 | shiftjisx0213, sjisx0213, | Japanese |
1225| | s_jisx0213 | |
1226+-----------------+--------------------------------+--------------------------------+
Walter Dörwald41980ca2007-08-16 21:55:45 +00001227| utf_32 | U32, utf32 | all languages |
1228+-----------------+--------------------------------+--------------------------------+
1229| utf_32_be | UTF-32BE | all languages |
1230+-----------------+--------------------------------+--------------------------------+
1231| utf_32_le | UTF-32LE | all languages |
1232+-----------------+--------------------------------+--------------------------------+
Georg Brandl116aa622007-08-15 14:28:22 +00001233| utf_16 | U16, utf16 | all languages |
1234+-----------------+--------------------------------+--------------------------------+
Victor Stinner53a9dd72010-12-08 22:25:45 +00001235| utf_16_be | UTF-16BE | all languages |
Georg Brandl116aa622007-08-15 14:28:22 +00001236+-----------------+--------------------------------+--------------------------------+
Victor Stinner53a9dd72010-12-08 22:25:45 +00001237| utf_16_le | UTF-16LE | all languages |
Georg Brandl116aa622007-08-15 14:28:22 +00001238+-----------------+--------------------------------+--------------------------------+
1239| utf_7 | U7, unicode-1-1-utf-7 | all languages |
1240+-----------------+--------------------------------+--------------------------------+
Victor Stinner3aef48e2019-05-13 10:42:31 +02001241| utf_8 | U8, UTF, utf8, cp65001 | all languages |
Georg Brandl116aa622007-08-15 14:28:22 +00001242+-----------------+--------------------------------+--------------------------------+
1243| utf_8_sig | | all languages |
1244+-----------------+--------------------------------+--------------------------------+
1245
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02001246.. versionchanged:: 3.4
1247 The utf-16\* and utf-32\* encoders no longer allow surrogate code points
Nick Coghlanb9fdb7a2015-01-07 00:22:00 +10001248 (``U+D800``--``U+DFFF``) to be encoded.
1249 The utf-32\* decoders no longer decode
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02001250 byte sequences that correspond to surrogate code points.
1251
Victor Stinner3aef48e2019-05-13 10:42:31 +02001252.. versionchanged:: 3.8
1253 ``cp65001`` is now an alias to ``utf_8``.
1254
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02001255
Nick Coghlan650e3222013-05-23 20:24:02 +10001256Python Specific Encodings
1257-------------------------
1258
1259A number of predefined codecs are specific to Python, so their codec names have
Géry Ogam891e9e32019-09-12 09:41:32 +02001260no meaning outside Python. These are listed in the tables below based on the
Nick Coghlan650e3222013-05-23 20:24:02 +10001261expected input and output types (note that while text encodings are the most
1262common use case for codecs, the underlying codec infrastructure supports
Géry Ogam891e9e32019-09-12 09:41:32 +02001263arbitrary data transforms rather than just text encodings). For asymmetric
1264codecs, the stated meaning describes the encoding direction.
Nick Coghlan650e3222013-05-23 20:24:02 +10001265
Nick Coghlan9c1aed82013-11-23 11:13:36 +10001266Text Encodings
1267^^^^^^^^^^^^^^
1268
Nick Coghlan650e3222013-05-23 20:24:02 +10001269The following codecs provide :class:`str` to :class:`bytes` encoding and
1270:term:`bytes-like object` to :class:`str` decoding, similar to the Unicode text
1271encodings.
Georg Brandl226878c2007-08-31 10:15:37 +00001272
Georg Brandl44ea77b2013-03-28 13:28:44 +01001273.. tabularcolumns:: |l|p{0.3\linewidth}|p{0.3\linewidth}|
1274
Georg Brandl30c78d62008-05-11 14:52:00 +00001275+--------------------+---------+---------------------------+
Géry Ogam891e9e32019-09-12 09:41:32 +02001276| Codec | Aliases | Meaning |
Georg Brandl30c78d62008-05-11 14:52:00 +00001277+====================+=========+===========================+
Géry Ogam891e9e32019-09-12 09:41:32 +02001278| idna | | Implement :rfc:`3490`, |
Georg Brandl30c78d62008-05-11 14:52:00 +00001279| | | see also |
Nick Coghlanb9fdb7a2015-01-07 00:22:00 +10001280| | | :mod:`encodings.idna`. |
1281| | | Only ``errors='strict'`` |
1282| | | is supported. |
Georg Brandl30c78d62008-05-11 14:52:00 +00001283+--------------------+---------+---------------------------+
Géry Ogam891e9e32019-09-12 09:41:32 +02001284| mbcs | ansi, | Windows only: Encode the |
Steve Dower5a713272016-09-06 19:46:42 -07001285| | dbcs | operand according to the |
Géry Ogam891e9e32019-09-12 09:41:32 +02001286| | | ANSI codepage (CP_ACP). |
Georg Brandl30c78d62008-05-11 14:52:00 +00001287+--------------------+---------+---------------------------+
Géry Ogam891e9e32019-09-12 09:41:32 +02001288| oem | | Windows only: Encode the |
Steve Dower5a713272016-09-06 19:46:42 -07001289| | | operand according to the |
Géry Ogam891e9e32019-09-12 09:41:32 +02001290| | | OEM codepage (CP_OEMCP). |
Steve Dower5a713272016-09-06 19:46:42 -07001291| | | |
1292| | | .. versionadded:: 3.6 |
1293+--------------------+---------+---------------------------+
Géry Ogam891e9e32019-09-12 09:41:32 +02001294| palmos | | Encoding of PalmOS 3.5. |
Georg Brandl30c78d62008-05-11 14:52:00 +00001295+--------------------+---------+---------------------------+
Géry Ogam891e9e32019-09-12 09:41:32 +02001296| punycode | | Implement :rfc:`3492`. |
Nick Coghlanb9fdb7a2015-01-07 00:22:00 +10001297| | | Stateful codecs are not |
1298| | | supported. |
Georg Brandl30c78d62008-05-11 14:52:00 +00001299+--------------------+---------+---------------------------+
Nick Coghlanb9fdb7a2015-01-07 00:22:00 +10001300| raw_unicode_escape | | Latin-1 encoding with |
1301| | | ``\uXXXX`` and |
1302| | | ``\UXXXXXXXX`` for other |
1303| | | code points. Existing |
1304| | | backslashes are not |
1305| | | escaped in any way. |
1306| | | It is used in the Python |
1307| | | pickle protocol. |
Georg Brandl30c78d62008-05-11 14:52:00 +00001308+--------------------+---------+---------------------------+
1309| undefined | | Raise an exception for |
Nick Coghlanb9fdb7a2015-01-07 00:22:00 +10001310| | | all conversions, even |
1311| | | empty strings. The error |
1312| | | handler is ignored. |
Georg Brandl30c78d62008-05-11 14:52:00 +00001313+--------------------+---------+---------------------------+
Nick Coghlanb9fdb7a2015-01-07 00:22:00 +10001314| unicode_escape | | Encoding suitable as the |
1315| | | contents of a Unicode |
1316| | | literal in ASCII-encoded |
1317| | | Python source code, |
1318| | | except that quotes are |
Géry Ogam891e9e32019-09-12 09:41:32 +02001319| | | not escaped. Decode |
1320| | | from Latin-1 source code. |
Nick Coghlanb9fdb7a2015-01-07 00:22:00 +10001321| | | Beware that Python source |
1322| | | code actually uses UTF-8 |
1323| | | by default. |
Georg Brandl30c78d62008-05-11 14:52:00 +00001324+--------------------+---------+---------------------------+
Inada Naoki6a16b182019-03-18 15:44:11 +09001325
1326.. versionchanged:: 3.8
1327 "unicode_internal" codec is removed.
1328
Georg Brandl116aa622007-08-15 14:28:22 +00001329
Nick Coghlan9c1aed82013-11-23 11:13:36 +10001330.. _binary-transforms:
1331
1332Binary Transforms
1333^^^^^^^^^^^^^^^^^
1334
1335The following codecs provide binary transforms: :term:`bytes-like object`
Géry Ogam891e9e32019-09-12 09:41:32 +02001336to :class:`bytes` mappings. They are not supported by :meth:`bytes.decode`
Nick Coghlanb9fdb7a2015-01-07 00:22:00 +10001337(which only produces :class:`str` output).
Nick Coghlan650e3222013-05-23 20:24:02 +10001338
Georg Brandl02524622010-12-02 18:06:51 +00001339
Nick Coghlan9c1aed82013-11-23 11:13:36 +10001340.. tabularcolumns:: |l|L|L|L|
Georg Brandl44ea77b2013-03-28 13:28:44 +01001341
Nick Coghlan9c1aed82013-11-23 11:13:36 +10001342+----------------------+------------------+------------------------------+------------------------------+
Géry Ogam891e9e32019-09-12 09:41:32 +02001343| Codec | Aliases | Meaning | Encoder / decoder |
Nick Coghlan9c1aed82013-11-23 11:13:36 +10001344+======================+==================+==============================+==============================+
Géry Ogam891e9e32019-09-12 09:41:32 +02001345| base64_codec [#b64]_ | base64, base_64 | Convert the operand to | :meth:`base64.encodebytes` / |
1346| | | multiline MIME base64 (the | :meth:`base64.decodebytes` |
1347| | | result always includes a | |
1348| | | trailing ``'\n'``). | |
Nick Coghlan9c1aed82013-11-23 11:13:36 +10001349| | | | |
1350| | | .. versionchanged:: 3.4 | |
1351| | | accepts any | |
1352| | | :term:`bytes-like object` | |
1353| | | as input for encoding and | |
1354| | | decoding | |
1355+----------------------+------------------+------------------------------+------------------------------+
Géry Ogam891e9e32019-09-12 09:41:32 +02001356| bz2_codec | bz2 | Compress the operand using | :meth:`bz2.compress` / |
1357| | | bz2. | :meth:`bz2.decompress` |
Nick Coghlan9c1aed82013-11-23 11:13:36 +10001358+----------------------+------------------+------------------------------+------------------------------+
Géry Ogam891e9e32019-09-12 09:41:32 +02001359| hex_codec | hex | Convert the operand to | :meth:`binascii.b2a_hex` / |
Martin Panter06171bd2015-09-12 00:34:28 +00001360| | | hexadecimal | :meth:`binascii.a2b_hex` |
Nick Coghlan9c1aed82013-11-23 11:13:36 +10001361| | | representation, with two | |
Géry Ogam891e9e32019-09-12 09:41:32 +02001362| | | digits per byte. | |
Nick Coghlan9c1aed82013-11-23 11:13:36 +10001363+----------------------+------------------+------------------------------+------------------------------+
Géry Ogam891e9e32019-09-12 09:41:32 +02001364| quopri_codec | quopri, | Convert the operand to MIME | :meth:`quopri.encode` with |
1365| | quotedprintable, | quoted printable. | ``quotetabs=True`` / |
Martin Panter06171bd2015-09-12 00:34:28 +00001366| | quoted_printable | | :meth:`quopri.decode` |
Nick Coghlan9c1aed82013-11-23 11:13:36 +10001367+----------------------+------------------+------------------------------+------------------------------+
1368| uu_codec | uu | Convert the operand using | :meth:`uu.encode` / |
Géry Ogam891e9e32019-09-12 09:41:32 +02001369| | | uuencode. | :meth:`uu.decode` |
Nick Coghlan9c1aed82013-11-23 11:13:36 +10001370+----------------------+------------------+------------------------------+------------------------------+
Géry Ogam891e9e32019-09-12 09:41:32 +02001371| zlib_codec | zip, zlib | Compress the operand using | :meth:`zlib.compress` / |
1372| | | gzip. | :meth:`zlib.decompress` |
Nick Coghlan9c1aed82013-11-23 11:13:36 +10001373+----------------------+------------------+------------------------------+------------------------------+
Georg Brandl02524622010-12-02 18:06:51 +00001374
Nick Coghlanfdf239a2013-10-03 00:43:22 +10001375.. [#b64] In addition to :term:`bytes-like objects <bytes-like object>`,
1376 ``'base64_codec'`` also accepts ASCII-only instances of :class:`str` for
1377 decoding
Nick Coghlan650e3222013-05-23 20:24:02 +10001378
Nick Coghlan9c1aed82013-11-23 11:13:36 +10001379.. versionadded:: 3.2
1380 Restoration of the binary transforms.
Nick Coghlan650e3222013-05-23 20:24:02 +10001381
Nick Coghlan9c1aed82013-11-23 11:13:36 +10001382.. versionchanged:: 3.4
1383 Restoration of the aliases for the binary transforms.
Georg Brandl02524622010-12-02 18:06:51 +00001384
Georg Brandl44ea77b2013-03-28 13:28:44 +01001385
Nick Coghlan9c1aed82013-11-23 11:13:36 +10001386.. _text-transforms:
1387
1388Text Transforms
1389^^^^^^^^^^^^^^^
1390
1391The following codec provides a text transform: a :class:`str` to :class:`str`
Géry Ogam891e9e32019-09-12 09:41:32 +02001392mapping. It is not supported by :meth:`str.encode` (which only produces
Nick Coghlanb9fdb7a2015-01-07 00:22:00 +10001393:class:`bytes` output).
Nick Coghlan9c1aed82013-11-23 11:13:36 +10001394
1395.. tabularcolumns:: |l|l|L|
1396
1397+--------------------+---------+---------------------------+
Géry Ogam891e9e32019-09-12 09:41:32 +02001398| Codec | Aliases | Meaning |
Nick Coghlan9c1aed82013-11-23 11:13:36 +10001399+====================+=========+===========================+
Géry Ogam891e9e32019-09-12 09:41:32 +02001400| rot_13 | rot13 | Return the Caesar-cypher |
1401| | | encryption of the |
1402| | | operand. |
Nick Coghlan9c1aed82013-11-23 11:13:36 +10001403+--------------------+---------+---------------------------+
Georg Brandl02524622010-12-02 18:06:51 +00001404
1405.. versionadded:: 3.2
Nick Coghlan9c1aed82013-11-23 11:13:36 +10001406 Restoration of the ``rot_13`` text transform.
1407
1408.. versionchanged:: 3.4
1409 Restoration of the ``rot13`` alias.
Georg Brandl02524622010-12-02 18:06:51 +00001410
Georg Brandl116aa622007-08-15 14:28:22 +00001411
1412:mod:`encodings.idna` --- Internationalized Domain Names in Applications
1413------------------------------------------------------------------------
1414
1415.. module:: encodings.idna
1416 :synopsis: Internationalized Domain Names implementation
1417.. moduleauthor:: Martin v. Löwis
1418
Georg Brandl116aa622007-08-15 14:28:22 +00001419This module implements :rfc:`3490` (Internationalized Domain Names in
1420Applications) and :rfc:`3492` (Nameprep: A Stringprep Profile for
1421Internationalized Domain Names (IDN)). It builds upon the ``punycode`` encoding
1422and :mod:`stringprep`.
1423
Gregory P. Smith1d023e32021-04-06 00:55:45 -07001424If you need the IDNA 2008 standard from :rfc:`5891` and :rfc:`5895`, use the
1425third-party `idna module <https://pypi.org/project/idna/>_`.
1426
Georg Brandl116aa622007-08-15 14:28:22 +00001427These RFCs together define a protocol to support non-ASCII characters in domain
1428names. A domain name containing non-ASCII characters (such as
1429``www.Alliancefrançaise.nu``) is converted into an ASCII-compatible encoding
1430(ACE, such as ``www.xn--alliancefranaise-npb.nu``). The ACE form of the domain
1431name is then used in all places where arbitrary characters are not allowed by
1432the protocol, such as DNS queries, HTTP :mailheader:`Host` fields, and so
1433on. This conversion is carried out in the application; if possible invisible to
1434the user: The application should transparently convert Unicode domain labels to
1435IDNA on the wire, and convert back ACE labels to Unicode before presenting them
1436to the user.
1437
R David Murraye0fd2f82011-04-13 14:12:18 -04001438Python supports this conversion in several ways: the ``idna`` codec performs
1439conversion between Unicode and ACE, separating an input string into labels
Serhiy Storchaka0a36ac12018-05-31 07:39:00 +03001440based on the separator characters defined in :rfc:`section 3.1 of RFC 3490 <3490#section-3.1>`
R David Murraye0fd2f82011-04-13 14:12:18 -04001441and converting each label to ACE as required, and conversely separating an input
1442byte string into labels based on the ``.`` separator and converting any ACE
Géry Ogam891e9e32019-09-12 09:41:32 +02001443labels found into unicode. Furthermore, the :mod:`socket` module
Georg Brandl116aa622007-08-15 14:28:22 +00001444transparently converts Unicode host names to ACE, so that applications need not
1445be concerned about converting host names themselves when they pass them to the
1446socket module. On top of that, modules that have host names as function
Georg Brandl24420152008-05-26 16:32:26 +00001447parameters, such as :mod:`http.client` and :mod:`ftplib`, accept Unicode host
1448names (:mod:`http.client` then also transparently sends an IDNA hostname in the
Georg Brandl116aa622007-08-15 14:28:22 +00001449:mailheader:`Host` field if it sends that field at all).
1450
1451When receiving host names from the wire (such as in reverse name lookup), no
Géry Ogam891e9e32019-09-12 09:41:32 +02001452automatic conversion to Unicode is performed: applications wishing to present
Georg Brandl116aa622007-08-15 14:28:22 +00001453such host names to the user should decode them to Unicode.
1454
1455The module :mod:`encodings.idna` also implements the nameprep procedure, which
1456performs certain normalizations on host names, to achieve case-insensitivity of
1457international domain names, and to unify similar characters. The nameprep
1458functions can be used directly if desired.
1459
1460
1461.. function:: nameprep(label)
1462
1463 Return the nameprepped version of *label*. The implementation currently assumes
1464 query strings, so ``AllowUnassigned`` is true.
1465
1466
1467.. function:: ToASCII(label)
1468
1469 Convert a label to ASCII, as specified in :rfc:`3490`. ``UseSTD3ASCIIRules`` is
1470 assumed to be false.
1471
1472
1473.. function:: ToUnicode(label)
1474
1475 Convert a label to Unicode, as specified in :rfc:`3490`.
1476
1477
Victor Stinner554f3f02010-06-16 23:33:54 +00001478:mod:`encodings.mbcs` --- Windows ANSI codepage
1479-----------------------------------------------
1480
1481.. module:: encodings.mbcs
1482 :synopsis: Windows ANSI codepage
1483
Géry Ogam891e9e32019-09-12 09:41:32 +02001484This module implements the ANSI codepage (CP_ACP).
Victor Stinner554f3f02010-06-16 23:33:54 +00001485
Cheryl Sabella2d6097d2018-10-12 10:55:20 -04001486.. availability:: Windows only.
Victor Stinner554f3f02010-06-16 23:33:54 +00001487
Victor Stinner3a50e702011-10-18 21:21:00 +02001488.. versionchanged:: 3.3
1489 Support any error handler.
1490
Victor Stinner554f3f02010-06-16 23:33:54 +00001491.. versionchanged:: 3.2
1492 Before 3.2, the *errors* argument was ignored; ``'replace'`` was always used
1493 to encode, and ``'ignore'`` to decode.
1494
1495
Georg Brandl116aa622007-08-15 14:28:22 +00001496:mod:`encodings.utf_8_sig` --- UTF-8 codec with BOM signature
1497-------------------------------------------------------------
1498
1499.. module:: encodings.utf_8_sig
1500 :synopsis: UTF-8 codec with BOM signature
1501.. moduleauthor:: Walter Dörwald
1502
Géry Ogam891e9e32019-09-12 09:41:32 +02001503This module implements a variant of the UTF-8 codec. On encoding, a UTF-8 encoded
Georg Brandl116aa622007-08-15 14:28:22 +00001504BOM will be prepended to the UTF-8 encoded bytes. For the stateful encoder this
Géry Ogam891e9e32019-09-12 09:41:32 +02001505is only done once (on the first write to the byte stream). On decoding, an
Georg Brandl116aa622007-08-15 14:28:22 +00001506optional UTF-8 encoded BOM at the start of the data will be skipped.