blob: e80fc3a33d2503855307768e4b704e5aef914ec3 [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.
Antoine Pitroufbd4f802012-08-11 16:51:50 +02006.. moduleauthor:: Marc-André Lemburg <mal@lemburg.com>
7.. sectionauthor:: Marc-André Lemburg <mal@lemburg.com>
Georg Brandl116aa622007-08-15 14:28:22 +00008.. sectionauthor:: Martin v. Löwis <martin@v.loewis.de>
9
10
11.. index::
12 single: Unicode
13 single: Codecs
14 pair: Codecs; encode
15 pair: Codecs; decode
16 single: streams
17 pair: stackable; streams
18
19This module defines base classes for standard Python codecs (encoders and
20decoders) and provides access to the internal Python codec registry which
21manages the codec and error handling lookup process.
22
23It defines the following functions:
24
25
26.. function:: register(search_function)
27
28 Register a codec search function. Search functions are expected to take one
29 argument, the encoding name in all lower case letters, and return a
30 :class:`CodecInfo` object having the following attributes:
31
32 * ``name`` The name of the encoding;
33
Walter Dörwald62073e02008-10-23 13:21:33 +000034 * ``encode`` The stateless encoding function;
Georg Brandl116aa622007-08-15 14:28:22 +000035
Walter Dörwald62073e02008-10-23 13:21:33 +000036 * ``decode`` The stateless decoding function;
Georg Brandl116aa622007-08-15 14:28:22 +000037
38 * ``incrementalencoder`` An incremental encoder class or factory function;
39
40 * ``incrementaldecoder`` An incremental decoder class or factory function;
41
42 * ``streamwriter`` A stream writer class or factory function;
43
44 * ``streamreader`` A stream reader class or factory function.
45
46 The various functions or classes take the following arguments:
47
Walter Dörwald62073e02008-10-23 13:21:33 +000048 *encode* and *decode*: These must be functions or methods which have the same
Georg Brandl116aa622007-08-15 14:28:22 +000049 interface as the :meth:`encode`/:meth:`decode` methods of Codec instances (see
50 Codec Interface). The functions/methods are expected to work in a stateless
51 mode.
52
Benjamin Peterson3e4f0552008-09-02 00:31:15 +000053 *incrementalencoder* and *incrementaldecoder*: These have to be factory
Georg Brandl116aa622007-08-15 14:28:22 +000054 functions providing the following interface:
55
Georg Brandl495f7b52009-10-27 15:28:25 +000056 ``factory(errors='strict')``
Georg Brandl116aa622007-08-15 14:28:22 +000057
58 The factory functions must return objects providing the interfaces defined by
Benjamin Peterson3e4f0552008-09-02 00:31:15 +000059 the base classes :class:`IncrementalEncoder` and :class:`IncrementalDecoder`,
Georg Brandl116aa622007-08-15 14:28:22 +000060 respectively. Incremental codecs can maintain state.
61
62 *streamreader* and *streamwriter*: These have to be factory functions providing
63 the following interface:
64
Georg Brandl495f7b52009-10-27 15:28:25 +000065 ``factory(stream, errors='strict')``
Georg Brandl116aa622007-08-15 14:28:22 +000066
67 The factory functions must return objects providing the interfaces defined by
68 the base classes :class:`StreamWriter` and :class:`StreamReader`, respectively.
69 Stream codecs can maintain state.
70
Georg Brandl495f7b52009-10-27 15:28:25 +000071 Possible values for errors are
72
73 * ``'strict'``: raise an exception in case of an encoding error
74 * ``'replace'``: replace malformed data with a suitable replacement marker,
75 such as ``'?'`` or ``'\ufffd'``
76 * ``'ignore'``: ignore malformed data and continue without further notice
77 * ``'xmlcharrefreplace'``: replace with the appropriate XML character
78 reference (for encoding only)
79 * ``'backslashreplace'``: replace with backslashed escape sequences (for
Ezio Melottie33721e2010-02-27 13:54:27 +000080 encoding only)
Andrew Kuchlingc7b6c502013-06-16 12:58:48 -040081 * ``'surrogateescape'``: on decoding, replace with code points in the Unicode
82 Private Use Area ranging from U+DC80 to U+DCFF. These private code
83 points will then be turned back into the same bytes when the
84 ``surrogateescape`` error handler is used when encoding the data.
85 (See :pep:`383` for more.)
Georg Brandl495f7b52009-10-27 15:28:25 +000086
87 as well as any other error handling name defined via :func:`register_error`.
Georg Brandl116aa622007-08-15 14:28:22 +000088
89 In case a search function cannot find a given encoding, it should return
90 ``None``.
91
92
93.. function:: lookup(encoding)
94
95 Looks up the codec info in the Python codec registry and returns a
96 :class:`CodecInfo` object as defined above.
97
98 Encodings are first looked up in the registry's cache. If not found, the list of
99 registered search functions is scanned. If no :class:`CodecInfo` object is
100 found, a :exc:`LookupError` is raised. Otherwise, the :class:`CodecInfo` object
101 is stored in the cache and returned to the caller.
102
103To simplify access to the various codecs, the module provides these additional
104functions which use :func:`lookup` for the codec lookup:
105
106
107.. function:: getencoder(encoding)
108
109 Look up the codec for the given encoding and return its encoder function.
110
111 Raises a :exc:`LookupError` in case the encoding cannot be found.
112
113
114.. function:: getdecoder(encoding)
115
116 Look up the codec for the given encoding and return its decoder function.
117
118 Raises a :exc:`LookupError` in case the encoding cannot be found.
119
120
121.. function:: getincrementalencoder(encoding)
122
123 Look up the codec for the given encoding and return its incremental encoder
124 class or factory function.
125
126 Raises a :exc:`LookupError` in case the encoding cannot be found or the codec
127 doesn't support an incremental encoder.
128
Georg Brandl116aa622007-08-15 14:28:22 +0000129
130.. function:: getincrementaldecoder(encoding)
131
132 Look up the codec for the given encoding and return its incremental decoder
133 class or factory function.
134
135 Raises a :exc:`LookupError` in case the encoding cannot be found or the codec
136 doesn't support an incremental decoder.
137
Georg Brandl116aa622007-08-15 14:28:22 +0000138
139.. function:: getreader(encoding)
140
141 Look up the codec for the given encoding and return its StreamReader class or
142 factory function.
143
144 Raises a :exc:`LookupError` in case the encoding cannot be found.
145
146
147.. function:: getwriter(encoding)
148
149 Look up the codec for the given encoding and return its StreamWriter class or
150 factory function.
151
152 Raises a :exc:`LookupError` in case the encoding cannot be found.
153
154
155.. function:: register_error(name, error_handler)
156
157 Register the error handling function *error_handler* under the name *name*.
158 *error_handler* will be called during encoding and decoding in case of an error,
159 when *name* is specified as the errors parameter.
160
161 For encoding *error_handler* will be called with a :exc:`UnicodeEncodeError`
Benjamin Peterson19603552012-12-02 11:26:10 -0500162 instance, which contains information about the location of the error. The
163 error handler must either raise this or a different exception or return a
164 tuple with a replacement for the unencodable part of the input and a position
165 where encoding should continue. The replacement may be either :class:`str` or
166 :class:`bytes`. If the replacement is bytes, the encoder will simply copy
167 them into the output buffer. If the replacement is a string, the encoder will
168 encode the replacement. Encoding continues on original input at the
169 specified position. Negative position values will be treated as being
170 relative to the end of the input string. If the resulting position is out of
171 bound an :exc:`IndexError` will be raised.
Georg Brandl116aa622007-08-15 14:28:22 +0000172
173 Decoding and translating works similar, except :exc:`UnicodeDecodeError` or
174 :exc:`UnicodeTranslateError` will be passed to the handler and that the
175 replacement from the error handler will be put into the output directly.
176
177
178.. function:: lookup_error(name)
179
180 Return the error handler previously registered under the name *name*.
181
182 Raises a :exc:`LookupError` in case the handler cannot be found.
183
184
185.. function:: strict_errors(exception)
186
Georg Brandl495f7b52009-10-27 15:28:25 +0000187 Implements the ``strict`` error handling: each encoding or decoding error
188 raises a :exc:`UnicodeError`.
Georg Brandl116aa622007-08-15 14:28:22 +0000189
190
191.. function:: replace_errors(exception)
192
Georg Brandl495f7b52009-10-27 15:28:25 +0000193 Implements the ``replace`` error handling: malformed data is replaced with a
194 suitable replacement character such as ``'?'`` in bytestrings and
195 ``'\ufffd'`` in Unicode strings.
Georg Brandl116aa622007-08-15 14:28:22 +0000196
197
198.. function:: ignore_errors(exception)
199
Georg Brandl495f7b52009-10-27 15:28:25 +0000200 Implements the ``ignore`` error handling: malformed data is ignored and
201 encoding or decoding is continued without further notice.
Georg Brandl116aa622007-08-15 14:28:22 +0000202
203
Thomas Wouters89d996e2007-09-08 17:39:28 +0000204.. function:: xmlcharrefreplace_errors(exception)
Georg Brandl116aa622007-08-15 14:28:22 +0000205
Georg Brandl495f7b52009-10-27 15:28:25 +0000206 Implements the ``xmlcharrefreplace`` error handling (for encoding only): the
207 unencodable character is replaced by an appropriate XML character reference.
Georg Brandl116aa622007-08-15 14:28:22 +0000208
209
Thomas Wouters89d996e2007-09-08 17:39:28 +0000210.. function:: backslashreplace_errors(exception)
Georg Brandl116aa622007-08-15 14:28:22 +0000211
Georg Brandl495f7b52009-10-27 15:28:25 +0000212 Implements the ``backslashreplace`` error handling (for encoding only): the
213 unencodable character is replaced by a backslashed escape sequence.
Georg Brandl116aa622007-08-15 14:28:22 +0000214
215To simplify working with encoded files or stream, the module also defines these
216utility functions:
217
218
219.. function:: open(filename, mode[, encoding[, errors[, buffering]]])
220
221 Open an encoded file using the given *mode* and return a wrapped version
Christian Heimes18c66892008-02-17 13:31:39 +0000222 providing transparent encoding/decoding. The default file mode is ``'r'``
223 meaning to open the file in read mode.
Georg Brandl116aa622007-08-15 14:28:22 +0000224
225 .. note::
226
Georg Brandl30c78d62008-05-11 14:52:00 +0000227 The wrapped version's methods will accept and return strings only. Bytes
228 arguments will be rejected.
Georg Brandl116aa622007-08-15 14:28:22 +0000229
Christian Heimes18c66892008-02-17 13:31:39 +0000230 .. note::
231
232 Files are always opened in binary mode, even if no binary mode was
233 specified. This is done to avoid data loss due to encodings using 8-bit
Georg Brandl30c78d62008-05-11 14:52:00 +0000234 values. This means that no automatic conversion of ``b'\n'`` is done
Christian Heimes18c66892008-02-17 13:31:39 +0000235 on reading and writing.
236
Georg Brandl116aa622007-08-15 14:28:22 +0000237 *encoding* specifies the encoding which is to be used for the file.
238
239 *errors* may be given to define the error handling. It defaults to ``'strict'``
240 which causes a :exc:`ValueError` to be raised in case an encoding error occurs.
241
242 *buffering* has the same meaning as for the built-in :func:`open` function. It
243 defaults to line buffered.
244
245
Georg Brandl0d8f0732009-04-05 22:20:44 +0000246.. function:: EncodedFile(file, data_encoding, file_encoding=None, errors='strict')
Georg Brandl116aa622007-08-15 14:28:22 +0000247
248 Return a wrapped version of file which provides transparent encoding
249 translation.
250
Georg Brandl30c78d62008-05-11 14:52:00 +0000251 Bytes written to the wrapped file are interpreted according to the given
Georg Brandl0d8f0732009-04-05 22:20:44 +0000252 *data_encoding* and then written to the original file as bytes using the
253 *file_encoding*.
Georg Brandl116aa622007-08-15 14:28:22 +0000254
Georg Brandl0d8f0732009-04-05 22:20:44 +0000255 If *file_encoding* is not given, it defaults to *data_encoding*.
Georg Brandl116aa622007-08-15 14:28:22 +0000256
Georg Brandl0d8f0732009-04-05 22:20:44 +0000257 *errors* may be given to define the error handling. It defaults to
258 ``'strict'``, which causes :exc:`ValueError` to be raised in case an encoding
259 error occurs.
Georg Brandl116aa622007-08-15 14:28:22 +0000260
261
Georg Brandl0d8f0732009-04-05 22:20:44 +0000262.. function:: iterencode(iterator, encoding, errors='strict', **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +0000263
264 Uses an incremental encoder to iteratively encode the input provided by
Georg Brandl0d8f0732009-04-05 22:20:44 +0000265 *iterator*. This function is a :term:`generator`. *errors* (as well as any
Georg Brandl9afde1c2007-11-01 20:32:30 +0000266 other keyword argument) is passed through to the incremental encoder.
Georg Brandl116aa622007-08-15 14:28:22 +0000267
Georg Brandl116aa622007-08-15 14:28:22 +0000268
Georg Brandl0d8f0732009-04-05 22:20:44 +0000269.. function:: iterdecode(iterator, encoding, errors='strict', **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +0000270
271 Uses an incremental decoder to iteratively decode the input provided by
Georg Brandl0d8f0732009-04-05 22:20:44 +0000272 *iterator*. This function is a :term:`generator`. *errors* (as well as any
Georg Brandl9afde1c2007-11-01 20:32:30 +0000273 other keyword argument) is passed through to the incremental decoder.
Georg Brandl116aa622007-08-15 14:28:22 +0000274
Georg Brandl0d8f0732009-04-05 22:20:44 +0000275
Georg Brandl116aa622007-08-15 14:28:22 +0000276The module also provides the following constants which are useful for reading
277and writing to platform dependent files:
278
279
280.. data:: BOM
281 BOM_BE
282 BOM_LE
283 BOM_UTF8
284 BOM_UTF16
285 BOM_UTF16_BE
286 BOM_UTF16_LE
287 BOM_UTF32
288 BOM_UTF32_BE
289 BOM_UTF32_LE
290
291 These constants define various encodings of the Unicode byte order mark (BOM)
292 used in UTF-16 and UTF-32 data streams to indicate the byte order used in the
293 stream or file and in UTF-8 as a Unicode signature. :const:`BOM_UTF16` is either
294 :const:`BOM_UTF16_BE` or :const:`BOM_UTF16_LE` depending on the platform's
295 native byte order, :const:`BOM` is an alias for :const:`BOM_UTF16`,
296 :const:`BOM_LE` for :const:`BOM_UTF16_LE` and :const:`BOM_BE` for
297 :const:`BOM_UTF16_BE`. The others represent the BOM in UTF-8 and UTF-32
298 encodings.
299
300
301.. _codec-base-classes:
302
303Codec Base Classes
304------------------
305
306The :mod:`codecs` module defines a set of base classes which define the
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000307interface and can also be used to easily write your own codecs for use in
308Python.
Georg Brandl116aa622007-08-15 14:28:22 +0000309
310Each codec has to define four interfaces to make it usable as codec in Python:
311stateless encoder, stateless decoder, stream reader and stream writer. The
312stream reader and writers typically reuse the stateless encoder/decoder to
313implement the file protocols.
314
315The :class:`Codec` class defines the interface for stateless encoders/decoders.
316
317To simplify and standardize error handling, the :meth:`encode` and
318:meth:`decode` methods may implement different error handling schemes by
319providing the *errors* string argument. The following string values are defined
320and implemented by all standard Python codecs:
321
Georg Brandl44ea77b2013-03-28 13:28:44 +0100322.. tabularcolumns:: |l|L|
323
Georg Brandl116aa622007-08-15 14:28:22 +0000324+-------------------------+-----------------------------------------------+
325| Value | Meaning |
326+=========================+===============================================+
327| ``'strict'`` | Raise :exc:`UnicodeError` (or a subclass); |
328| | this is the default. |
329+-------------------------+-----------------------------------------------+
330| ``'ignore'`` | Ignore the character and continue with the |
331| | next. |
332+-------------------------+-----------------------------------------------+
333| ``'replace'`` | Replace with a suitable replacement |
334| | character; Python will use the official |
335| | U+FFFD REPLACEMENT CHARACTER for the built-in |
336| | Unicode codecs on decoding and '?' on |
337| | encoding. |
338+-------------------------+-----------------------------------------------+
339| ``'xmlcharrefreplace'`` | Replace with the appropriate XML character |
340| | reference (only for encoding). |
341+-------------------------+-----------------------------------------------+
342| ``'backslashreplace'`` | Replace with backslashed escape sequences |
343| | (only for encoding). |
344+-------------------------+-----------------------------------------------+
Martin v. Löwis3d2eca02009-06-29 06:35:26 +0000345| ``'surrogateescape'`` | Replace byte with surrogate U+DCxx, as defined|
346| | in :pep:`383`. |
Martin v. Löwis011e8422009-05-05 04:43:17 +0000347+-------------------------+-----------------------------------------------+
Georg Brandl116aa622007-08-15 14:28:22 +0000348
Martin v. Löwisdb12d452009-05-02 18:52:14 +0000349In addition, the following error handlers are specific to a single codec:
350
Martin v. Löwise0a2b722009-05-10 08:08:56 +0000351+-------------------+---------+-------------------------------------------+
352| Value | Codec | Meaning |
353+===================+=========+===========================================+
354|``'surrogatepass'``| utf-8 | Allow encoding and decoding of surrogate |
355| | | codes in UTF-8. |
356+-------------------+---------+-------------------------------------------+
Martin v. Löwisdb12d452009-05-02 18:52:14 +0000357
358.. versionadded:: 3.1
Martin v. Löwis43c57782009-05-10 08:15:24 +0000359 The ``'surrogateescape'`` and ``'surrogatepass'`` error handlers.
Martin v. Löwisdb12d452009-05-02 18:52:14 +0000360
Georg Brandl116aa622007-08-15 14:28:22 +0000361The set of allowed values can be extended via :meth:`register_error`.
362
363
364.. _codec-objects:
365
366Codec Objects
367^^^^^^^^^^^^^
368
369The :class:`Codec` class defines these methods which also define the function
370interfaces of the stateless encoder and decoder:
371
372
373.. method:: Codec.encode(input[, errors])
374
375 Encodes the object *input* and returns a tuple (output object, length consumed).
Georg Brandl30c78d62008-05-11 14:52:00 +0000376 Encoding converts a string object to a bytes object using a particular
Georg Brandl116aa622007-08-15 14:28:22 +0000377 character set encoding (e.g., ``cp1252`` or ``iso-8859-1``).
378
379 *errors* defines the error handling to apply. It defaults to ``'strict'``
380 handling.
381
382 The method may not store state in the :class:`Codec` instance. Use
383 :class:`StreamCodec` for codecs which have to keep state in order to make
384 encoding/decoding efficient.
385
386 The encoder must be able to handle zero length input and return an empty object
387 of the output object type in this situation.
388
389
390.. method:: Codec.decode(input[, errors])
391
Georg Brandl30c78d62008-05-11 14:52:00 +0000392 Decodes the object *input* and returns a tuple (output object, length
393 consumed). Decoding converts a bytes object encoded using a particular
394 character set encoding to a string object.
Georg Brandl116aa622007-08-15 14:28:22 +0000395
Georg Brandl30c78d62008-05-11 14:52:00 +0000396 *input* must be a bytes object or one which provides the read-only character
397 buffer interface -- for example, buffer objects and memory mapped files.
Georg Brandl116aa622007-08-15 14:28:22 +0000398
399 *errors* defines the error handling to apply. It defaults to ``'strict'``
400 handling.
401
402 The method may not store state in the :class:`Codec` instance. Use
403 :class:`StreamCodec` for codecs which have to keep state in order to make
404 encoding/decoding efficient.
405
406 The decoder must be able to handle zero length input and return an empty object
407 of the output object type in this situation.
408
409The :class:`IncrementalEncoder` and :class:`IncrementalDecoder` classes provide
410the basic interface for incremental encoding and decoding. Encoding/decoding the
411input isn't done with one call to the stateless encoder/decoder function, but
412with multiple calls to the :meth:`encode`/:meth:`decode` method of the
413incremental encoder/decoder. The incremental encoder/decoder keeps track of the
414encoding/decoding process during method calls.
415
416The joined output of calls to the :meth:`encode`/:meth:`decode` method is the
417same as if all the single inputs were joined into one, and this input was
418encoded/decoded with the stateless encoder/decoder.
419
420
421.. _incremental-encoder-objects:
422
423IncrementalEncoder Objects
424^^^^^^^^^^^^^^^^^^^^^^^^^^
425
Georg Brandl116aa622007-08-15 14:28:22 +0000426The :class:`IncrementalEncoder` class is used for encoding an input in multiple
427steps. It defines the following methods which every incremental encoder must
428define in order to be compatible with the Python codec registry.
429
430
431.. class:: IncrementalEncoder([errors])
432
433 Constructor for an :class:`IncrementalEncoder` instance.
434
435 All incremental encoders must provide this constructor interface. They are free
436 to add additional keyword arguments, but only the ones defined here are used by
437 the Python codec registry.
438
439 The :class:`IncrementalEncoder` may implement different error handling schemes
440 by providing the *errors* keyword argument. These parameters are predefined:
441
442 * ``'strict'`` Raise :exc:`ValueError` (or a subclass); this is the default.
443
444 * ``'ignore'`` Ignore the character and continue with the next.
445
446 * ``'replace'`` Replace with a suitable replacement character
447
448 * ``'xmlcharrefreplace'`` Replace with the appropriate XML character reference
449
450 * ``'backslashreplace'`` Replace with backslashed escape sequences.
451
452 The *errors* argument will be assigned to an attribute of the same name.
453 Assigning to this attribute makes it possible to switch between different error
454 handling strategies during the lifetime of the :class:`IncrementalEncoder`
455 object.
456
457 The set of allowed values for the *errors* argument can be extended with
458 :func:`register_error`.
459
460
Benjamin Petersone41251e2008-04-25 01:59:09 +0000461 .. method:: encode(object[, final])
Georg Brandl116aa622007-08-15 14:28:22 +0000462
Benjamin Petersone41251e2008-04-25 01:59:09 +0000463 Encodes *object* (taking the current state of the encoder into account)
464 and returns the resulting encoded object. If this is the last call to
465 :meth:`encode` *final* must be true (the default is false).
Georg Brandl116aa622007-08-15 14:28:22 +0000466
467
Benjamin Petersone41251e2008-04-25 01:59:09 +0000468 .. method:: reset()
Georg Brandl116aa622007-08-15 14:28:22 +0000469
Victor Stinnere15dce32011-05-30 22:56:00 +0200470 Reset the encoder to the initial state. The output is discarded: call
471 ``.encode('', final=True)`` to reset the encoder and to get the output.
Georg Brandl116aa622007-08-15 14:28:22 +0000472
473
474.. method:: IncrementalEncoder.getstate()
475
476 Return the current state of the encoder which must be an integer. The
477 implementation should make sure that ``0`` is the most common state. (States
478 that are more complicated than integers can be converted into an integer by
479 marshaling/pickling the state and encoding the bytes of the resulting string
480 into an integer).
481
Georg Brandl116aa622007-08-15 14:28:22 +0000482
483.. method:: IncrementalEncoder.setstate(state)
484
485 Set the state of the encoder to *state*. *state* must be an encoder state
486 returned by :meth:`getstate`.
487
Georg Brandl116aa622007-08-15 14:28:22 +0000488
489.. _incremental-decoder-objects:
490
491IncrementalDecoder Objects
492^^^^^^^^^^^^^^^^^^^^^^^^^^
493
494The :class:`IncrementalDecoder` class is used for decoding an input in multiple
495steps. It defines the following methods which every incremental decoder must
496define in order to be compatible with the Python codec registry.
497
498
499.. class:: IncrementalDecoder([errors])
500
501 Constructor for an :class:`IncrementalDecoder` instance.
502
503 All incremental decoders must provide this constructor interface. They are free
504 to add additional keyword arguments, but only the ones defined here are used by
505 the Python codec registry.
506
507 The :class:`IncrementalDecoder` may implement different error handling schemes
508 by providing the *errors* keyword argument. These parameters are predefined:
509
510 * ``'strict'`` Raise :exc:`ValueError` (or a subclass); this is the default.
511
512 * ``'ignore'`` Ignore the character and continue with the next.
513
514 * ``'replace'`` Replace with a suitable replacement character.
515
516 The *errors* argument will be assigned to an attribute of the same name.
517 Assigning to this attribute makes it possible to switch between different error
Benjamin Peterson3e4f0552008-09-02 00:31:15 +0000518 handling strategies during the lifetime of the :class:`IncrementalDecoder`
Georg Brandl116aa622007-08-15 14:28:22 +0000519 object.
520
521 The set of allowed values for the *errors* argument can be extended with
522 :func:`register_error`.
523
524
Benjamin Petersone41251e2008-04-25 01:59:09 +0000525 .. method:: decode(object[, final])
Georg Brandl116aa622007-08-15 14:28:22 +0000526
Benjamin Petersone41251e2008-04-25 01:59:09 +0000527 Decodes *object* (taking the current state of the decoder into account)
528 and returns the resulting decoded object. If this is the last call to
529 :meth:`decode` *final* must be true (the default is false). If *final* is
530 true the decoder must decode the input completely and must flush all
531 buffers. If this isn't possible (e.g. because of incomplete byte sequences
532 at the end of the input) it must initiate error handling just like in the
533 stateless case (which might raise an exception).
Georg Brandl116aa622007-08-15 14:28:22 +0000534
535
Benjamin Petersone41251e2008-04-25 01:59:09 +0000536 .. method:: reset()
Georg Brandl116aa622007-08-15 14:28:22 +0000537
Benjamin Petersone41251e2008-04-25 01:59:09 +0000538 Reset the decoder to the initial state.
Georg Brandl116aa622007-08-15 14:28:22 +0000539
540
Benjamin Petersone41251e2008-04-25 01:59:09 +0000541 .. method:: getstate()
Georg Brandl116aa622007-08-15 14:28:22 +0000542
Benjamin Petersone41251e2008-04-25 01:59:09 +0000543 Return the current state of the decoder. This must be a tuple with two
544 items, the first must be the buffer containing the still undecoded
545 input. The second must be an integer and can be additional state
546 info. (The implementation should make sure that ``0`` is the most common
547 additional state info.) If this additional state info is ``0`` it must be
548 possible to set the decoder to the state which has no input buffered and
549 ``0`` as the additional state info, so that feeding the previously
550 buffered input to the decoder returns it to the previous state without
551 producing any output. (Additional state info that is more complicated than
552 integers can be converted into an integer by marshaling/pickling the info
553 and encoding the bytes of the resulting string into an integer.)
Georg Brandl116aa622007-08-15 14:28:22 +0000554
Georg Brandl116aa622007-08-15 14:28:22 +0000555
Benjamin Petersone41251e2008-04-25 01:59:09 +0000556 .. method:: setstate(state)
Georg Brandl116aa622007-08-15 14:28:22 +0000557
Benjamin Petersone41251e2008-04-25 01:59:09 +0000558 Set the state of the encoder to *state*. *state* must be a decoder state
559 returned by :meth:`getstate`.
560
Georg Brandl116aa622007-08-15 14:28:22 +0000561
Georg Brandl116aa622007-08-15 14:28:22 +0000562The :class:`StreamWriter` and :class:`StreamReader` classes provide generic
563working interfaces which can be used to implement new encoding submodules very
564easily. See :mod:`encodings.utf_8` for an example of how this is done.
565
566
567.. _stream-writer-objects:
568
569StreamWriter Objects
570^^^^^^^^^^^^^^^^^^^^
571
572The :class:`StreamWriter` class is a subclass of :class:`Codec` and defines the
573following methods which every stream writer must define in order to be
574compatible with the Python codec registry.
575
576
577.. class:: StreamWriter(stream[, errors])
578
579 Constructor for a :class:`StreamWriter` instance.
580
581 All stream writers must provide this constructor interface. They are free to add
582 additional keyword arguments, but only the ones defined here are used by the
583 Python codec registry.
584
585 *stream* must be a file-like object open for writing binary data.
586
587 The :class:`StreamWriter` may implement different error handling schemes by
588 providing the *errors* keyword argument. These parameters are predefined:
589
590 * ``'strict'`` Raise :exc:`ValueError` (or a subclass); this is the default.
591
592 * ``'ignore'`` Ignore the character and continue with the next.
593
594 * ``'replace'`` Replace with a suitable replacement character
595
596 * ``'xmlcharrefreplace'`` Replace with the appropriate XML character reference
597
598 * ``'backslashreplace'`` Replace with backslashed escape sequences.
599
600 The *errors* argument will be assigned to an attribute of the same name.
601 Assigning to this attribute makes it possible to switch between different error
602 handling strategies during the lifetime of the :class:`StreamWriter` object.
603
604 The set of allowed values for the *errors* argument can be extended with
605 :func:`register_error`.
606
607
Benjamin Petersone41251e2008-04-25 01:59:09 +0000608 .. method:: write(object)
Georg Brandl116aa622007-08-15 14:28:22 +0000609
Benjamin Petersone41251e2008-04-25 01:59:09 +0000610 Writes the object's contents encoded to the stream.
Georg Brandl116aa622007-08-15 14:28:22 +0000611
612
Benjamin Petersone41251e2008-04-25 01:59:09 +0000613 .. method:: writelines(list)
Georg Brandl116aa622007-08-15 14:28:22 +0000614
Benjamin Petersone41251e2008-04-25 01:59:09 +0000615 Writes the concatenated list of strings to the stream (possibly by reusing
616 the :meth:`write` method).
Georg Brandl116aa622007-08-15 14:28:22 +0000617
618
Benjamin Petersone41251e2008-04-25 01:59:09 +0000619 .. method:: reset()
Georg Brandl116aa622007-08-15 14:28:22 +0000620
Benjamin Petersone41251e2008-04-25 01:59:09 +0000621 Flushes and resets the codec buffers used for keeping state.
Georg Brandl116aa622007-08-15 14:28:22 +0000622
Benjamin Petersone41251e2008-04-25 01:59:09 +0000623 Calling this method should ensure that the data on the output is put into
624 a clean state that allows appending of new fresh data without having to
625 rescan the whole stream to recover state.
626
Georg Brandl116aa622007-08-15 14:28:22 +0000627
628In addition to the above methods, the :class:`StreamWriter` must also inherit
629all other methods and attributes from the underlying stream.
630
631
632.. _stream-reader-objects:
633
634StreamReader Objects
635^^^^^^^^^^^^^^^^^^^^
636
637The :class:`StreamReader` class is a subclass of :class:`Codec` and defines the
638following methods which every stream reader must define in order to be
639compatible with the Python codec registry.
640
641
642.. class:: StreamReader(stream[, errors])
643
644 Constructor for a :class:`StreamReader` instance.
645
646 All stream readers must provide this constructor interface. They are free to add
647 additional keyword arguments, but only the ones defined here are used by the
648 Python codec registry.
649
650 *stream* must be a file-like object open for reading (binary) data.
651
652 The :class:`StreamReader` may implement different error handling schemes by
653 providing the *errors* keyword argument. These parameters are defined:
654
655 * ``'strict'`` Raise :exc:`ValueError` (or a subclass); this is the default.
656
657 * ``'ignore'`` Ignore the character and continue with the next.
658
659 * ``'replace'`` Replace with a suitable replacement character.
660
661 The *errors* argument will be assigned to an attribute of the same name.
662 Assigning to this attribute makes it possible to switch between different error
663 handling strategies during the lifetime of the :class:`StreamReader` object.
664
665 The set of allowed values for the *errors* argument can be extended with
666 :func:`register_error`.
667
668
Benjamin Petersone41251e2008-04-25 01:59:09 +0000669 .. method:: read([size[, chars, [firstline]]])
Georg Brandl116aa622007-08-15 14:28:22 +0000670
Benjamin Petersone41251e2008-04-25 01:59:09 +0000671 Decodes data from the stream and returns the resulting object.
Georg Brandl116aa622007-08-15 14:28:22 +0000672
Benjamin Petersone41251e2008-04-25 01:59:09 +0000673 *chars* indicates the number of characters to read from the
674 stream. :func:`read` will never return more than *chars* characters, but
675 it might return less, if there are not enough characters available.
Georg Brandl116aa622007-08-15 14:28:22 +0000676
Benjamin Petersone41251e2008-04-25 01:59:09 +0000677 *size* indicates the approximate maximum number of bytes to read from the
678 stream for decoding purposes. The decoder can modify this setting as
679 appropriate. The default value -1 indicates to read and decode as much as
680 possible. *size* is intended to prevent having to decode huge files in
681 one step.
Georg Brandl116aa622007-08-15 14:28:22 +0000682
Benjamin Petersone41251e2008-04-25 01:59:09 +0000683 *firstline* indicates that it would be sufficient to only return the first
684 line, if there are decoding errors on later lines.
Georg Brandl116aa622007-08-15 14:28:22 +0000685
Benjamin Petersone41251e2008-04-25 01:59:09 +0000686 The method should use a greedy read strategy meaning that it should read
687 as much data as is allowed within the definition of the encoding and the
688 given size, e.g. if optional encoding endings or state markers are
689 available on the stream, these should be read too.
Georg Brandl116aa622007-08-15 14:28:22 +0000690
Georg Brandl116aa622007-08-15 14:28:22 +0000691
Benjamin Petersone41251e2008-04-25 01:59:09 +0000692 .. method:: readline([size[, keepends]])
Georg Brandl116aa622007-08-15 14:28:22 +0000693
Benjamin Petersone41251e2008-04-25 01:59:09 +0000694 Read one line from the input stream and return the decoded data.
Georg Brandl116aa622007-08-15 14:28:22 +0000695
Benjamin Petersone41251e2008-04-25 01:59:09 +0000696 *size*, if given, is passed as size argument to the stream's
697 :meth:`readline` method.
Georg Brandl116aa622007-08-15 14:28:22 +0000698
Benjamin Petersone41251e2008-04-25 01:59:09 +0000699 If *keepends* is false line-endings will be stripped from the lines
700 returned.
Georg Brandl116aa622007-08-15 14:28:22 +0000701
Georg Brandl116aa622007-08-15 14:28:22 +0000702
Benjamin Petersone41251e2008-04-25 01:59:09 +0000703 .. method:: readlines([sizehint[, keepends]])
Georg Brandl116aa622007-08-15 14:28:22 +0000704
Benjamin Petersone41251e2008-04-25 01:59:09 +0000705 Read all lines available on the input stream and return them as a list of
706 lines.
Georg Brandl116aa622007-08-15 14:28:22 +0000707
Benjamin Petersone41251e2008-04-25 01:59:09 +0000708 Line-endings are implemented using the codec's decoder method and are
709 included in the list entries if *keepends* is true.
Georg Brandl116aa622007-08-15 14:28:22 +0000710
Benjamin Petersone41251e2008-04-25 01:59:09 +0000711 *sizehint*, if given, is passed as the *size* argument to the stream's
712 :meth:`read` method.
Georg Brandl116aa622007-08-15 14:28:22 +0000713
714
Benjamin Petersone41251e2008-04-25 01:59:09 +0000715 .. method:: reset()
Georg Brandl116aa622007-08-15 14:28:22 +0000716
Benjamin Petersone41251e2008-04-25 01:59:09 +0000717 Resets the codec buffers used for keeping state.
Georg Brandl116aa622007-08-15 14:28:22 +0000718
Benjamin Petersone41251e2008-04-25 01:59:09 +0000719 Note that no stream repositioning should take place. This method is
720 primarily intended to be able to recover from decoding errors.
721
Georg Brandl116aa622007-08-15 14:28:22 +0000722
723In addition to the above methods, the :class:`StreamReader` must also inherit
724all other methods and attributes from the underlying stream.
725
726The next two base classes are included for convenience. They are not needed by
727the codec registry, but may provide useful in practice.
728
729
730.. _stream-reader-writer:
731
732StreamReaderWriter Objects
733^^^^^^^^^^^^^^^^^^^^^^^^^^
734
735The :class:`StreamReaderWriter` allows wrapping streams which work in both read
736and write modes.
737
738The design is such that one can use the factory functions returned by the
739:func:`lookup` function to construct the instance.
740
741
742.. class:: StreamReaderWriter(stream, Reader, Writer, errors)
743
744 Creates a :class:`StreamReaderWriter` instance. *stream* must be a file-like
745 object. *Reader* and *Writer* must be factory functions or classes providing the
746 :class:`StreamReader` and :class:`StreamWriter` interface resp. Error handling
747 is done in the same way as defined for the stream readers and writers.
748
749:class:`StreamReaderWriter` instances define the combined interfaces of
750:class:`StreamReader` and :class:`StreamWriter` classes. They inherit all other
751methods and attributes from the underlying stream.
752
753
754.. _stream-recoder-objects:
755
756StreamRecoder Objects
757^^^^^^^^^^^^^^^^^^^^^
758
759The :class:`StreamRecoder` provide a frontend - backend view of encoding data
760which is sometimes useful when dealing with different encoding environments.
761
762The design is such that one can use the factory functions returned by the
763:func:`lookup` function to construct the instance.
764
765
766.. class:: StreamRecoder(stream, encode, decode, Reader, Writer, errors)
767
768 Creates a :class:`StreamRecoder` instance which implements a two-way conversion:
769 *encode* and *decode* work on the frontend (the input to :meth:`read` and output
770 of :meth:`write`) while *Reader* and *Writer* work on the backend (reading and
771 writing to the stream).
772
773 You can use these objects to do transparent direct recodings from e.g. Latin-1
774 to UTF-8 and back.
775
776 *stream* must be a file-like object.
777
778 *encode*, *decode* must adhere to the :class:`Codec` interface. *Reader*,
779 *Writer* must be factory functions or classes providing objects of the
780 :class:`StreamReader` and :class:`StreamWriter` interface respectively.
781
782 *encode* and *decode* are needed for the frontend translation, *Reader* and
Georg Brandl30c78d62008-05-11 14:52:00 +0000783 *Writer* for the backend translation.
Georg Brandl116aa622007-08-15 14:28:22 +0000784
785 Error handling is done in the same way as defined for the stream readers and
786 writers.
787
Benjamin Petersone41251e2008-04-25 01:59:09 +0000788
Georg Brandl116aa622007-08-15 14:28:22 +0000789:class:`StreamRecoder` instances define the combined interfaces of
790:class:`StreamReader` and :class:`StreamWriter` classes. They inherit all other
791methods and attributes from the underlying stream.
792
793
794.. _encodings-overview:
795
796Encodings and Unicode
797---------------------
798
Ezio Melotti7a03f642011-10-25 10:30:19 +0300799Strings are stored internally as sequences of codepoints in range ``0 - 10FFFF``
800(see :pep:`393` for more details about the implementation).
801Once a string object is used outside of CPU and memory, CPU endianness
Georg Brandl116aa622007-08-15 14:28:22 +0000802and how these arrays are stored as bytes become an issue. Transforming a
Georg Brandl30c78d62008-05-11 14:52:00 +0000803string object into a sequence of bytes is called encoding and recreating the
804string object from the sequence of bytes is known as decoding. There are many
Georg Brandl116aa622007-08-15 14:28:22 +0000805different methods for how this transformation can be done (these methods are
806also called encodings). The simplest method is to map the codepoints 0-255 to
Georg Brandl30c78d62008-05-11 14:52:00 +0000807the bytes ``0x0``-``0xff``. This means that a string object that contains
Georg Brandl116aa622007-08-15 14:28:22 +0000808codepoints above ``U+00FF`` can't be encoded with this method (which is called
Georg Brandl30c78d62008-05-11 14:52:00 +0000809``'latin-1'`` or ``'iso-8859-1'``). :func:`str.encode` will raise a
Georg Brandl116aa622007-08-15 14:28:22 +0000810:exc:`UnicodeEncodeError` that looks like this: ``UnicodeEncodeError: 'latin-1'
Georg Brandl30c78d62008-05-11 14:52:00 +0000811codec can't encode character '\u1234' in position 3: ordinal not in
Georg Brandl116aa622007-08-15 14:28:22 +0000812range(256)``.
813
814There's another group of encodings (the so called charmap encodings) that choose
Georg Brandl30c78d62008-05-11 14:52:00 +0000815a different subset of all Unicode code points and how these codepoints are
Georg Brandl116aa622007-08-15 14:28:22 +0000816mapped to the bytes ``0x0``-``0xff``. To see how this is done simply open
817e.g. :file:`encodings/cp1252.py` (which is an encoding that is used primarily on
818Windows). There's a string constant with 256 characters that shows you which
819character is mapped to which byte value.
820
Ezio Melottifbb39812011-10-25 10:40:38 +0300821All of these encodings can only encode 256 of the 1114112 codepoints
Georg Brandl30c78d62008-05-11 14:52:00 +0000822defined in Unicode. A simple and straightforward way that can store each Unicode
Ezio Melottifbb39812011-10-25 10:40:38 +0300823code point, is to store each codepoint as four consecutive bytes. There are two
824possibilities: store the bytes in big endian or in little endian order. These
825two encodings are called ``UTF-32-BE`` and ``UTF-32-LE`` respectively. Their
826disadvantage is that if e.g. you use ``UTF-32-BE`` on a little endian machine you
827will always have to swap bytes on encoding and decoding. ``UTF-32`` avoids this
828problem: bytes will always be in natural endianness. When these bytes are read
Georg Brandl116aa622007-08-15 14:28:22 +0000829by a CPU with a different endianness, then bytes have to be swapped though. To
Ezio Melottifbb39812011-10-25 10:40:38 +0300830be able to detect the endianness of a ``UTF-16`` or ``UTF-32`` byte sequence,
831there's the so called BOM ("Byte Order Mark"). This is the Unicode character
832``U+FEFF``. This character can be prepended to every ``UTF-16`` or ``UTF-32``
833byte sequence. The byte swapped version of this character (``0xFFFE``) is an
834illegal character that may not appear in a Unicode text. So when the
835first character in an ``UTF-16`` or ``UTF-32`` byte sequence
Georg Brandl116aa622007-08-15 14:28:22 +0000836appears to be a ``U+FFFE`` the bytes have to be swapped on decoding.
Ezio Melottifbb39812011-10-25 10:40:38 +0300837Unfortunately the character ``U+FEFF`` had a second purpose as
838a ``ZERO WIDTH NO-BREAK SPACE``: a character that has no width and doesn't allow
Georg Brandl116aa622007-08-15 14:28:22 +0000839a word to be split. It can e.g. be used to give hints to a ligature algorithm.
840With Unicode 4.0 using ``U+FEFF`` as a ``ZERO WIDTH NO-BREAK SPACE`` has been
841deprecated (with ``U+2060`` (``WORD JOINER``) assuming this role). Nevertheless
Ezio Melottifbb39812011-10-25 10:40:38 +0300842Unicode software still must be able to handle ``U+FEFF`` in both roles: as a BOM
Georg Brandl116aa622007-08-15 14:28:22 +0000843it's a device to determine the storage layout of the encoded bytes, and vanishes
Georg Brandl30c78d62008-05-11 14:52:00 +0000844once the byte sequence has been decoded into a string; as a ``ZERO WIDTH
Georg Brandl116aa622007-08-15 14:28:22 +0000845NO-BREAK SPACE`` it's a normal character that will be decoded like any other.
846
847There's another encoding that is able to encoding the full range of Unicode
848characters: UTF-8. UTF-8 is an 8-bit encoding, which means there are no issues
849with byte order in UTF-8. Each byte in a UTF-8 byte sequence consists of two
Ezio Melottifbb39812011-10-25 10:40:38 +0300850parts: marker bits (the most significant bits) and payload bits. The marker bits
Ezio Melotti222b2082011-09-01 08:11:28 +0300851are a sequence of zero to four ``1`` bits followed by a ``0`` bit. Unicode characters are
Georg Brandl116aa622007-08-15 14:28:22 +0000852encoded like this (with x being payload bits, which when concatenated give the
853Unicode character):
854
855+-----------------------------------+----------------------------------------------+
856| Range | Encoding |
857+===================================+==============================================+
858| ``U-00000000`` ... ``U-0000007F`` | 0xxxxxxx |
859+-----------------------------------+----------------------------------------------+
860| ``U-00000080`` ... ``U-000007FF`` | 110xxxxx 10xxxxxx |
861+-----------------------------------+----------------------------------------------+
862| ``U-00000800`` ... ``U-0000FFFF`` | 1110xxxx 10xxxxxx 10xxxxxx |
863+-----------------------------------+----------------------------------------------+
Ezio Melotti222b2082011-09-01 08:11:28 +0300864| ``U-00010000`` ... ``U-0010FFFF`` | 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx |
Georg Brandl116aa622007-08-15 14:28:22 +0000865+-----------------------------------+----------------------------------------------+
866
867The least significant bit of the Unicode character is the rightmost x bit.
868
869As UTF-8 is an 8-bit encoding no BOM is required and any ``U+FEFF`` character in
Georg Brandl30c78d62008-05-11 14:52:00 +0000870the decoded string (even if it's the first character) is treated as a ``ZERO
871WIDTH NO-BREAK SPACE``.
Georg Brandl116aa622007-08-15 14:28:22 +0000872
873Without external information it's impossible to reliably determine which
Georg Brandl30c78d62008-05-11 14:52:00 +0000874encoding was used for encoding a string. Each charmap encoding can
Georg Brandl116aa622007-08-15 14:28:22 +0000875decode any random byte sequence. However that's not possible with UTF-8, as
876UTF-8 byte sequences have a structure that doesn't allow arbitrary byte
Thomas Wouters89d996e2007-09-08 17:39:28 +0000877sequences. To increase the reliability with which a UTF-8 encoding can be
Georg Brandl116aa622007-08-15 14:28:22 +0000878detected, Microsoft invented a variant of UTF-8 (that Python 2.5 calls
879``"utf-8-sig"``) for its Notepad program: Before any of the Unicode characters
880is written to the file, a UTF-8 encoded BOM (which looks like this as a byte
881sequence: ``0xef``, ``0xbb``, ``0xbf``) is written. As it's rather improbable
882that any charmap encoded file starts with these byte values (which would e.g.
883map to
884
885 | LATIN SMALL LETTER I WITH DIAERESIS
886 | RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK
887 | INVERTED QUESTION MARK
888
Ezio Melottifbb39812011-10-25 10:40:38 +0300889in iso-8859-1), this increases the probability that a ``utf-8-sig`` encoding can be
Georg Brandl116aa622007-08-15 14:28:22 +0000890correctly guessed from the byte sequence. So here the BOM is not used to be able
891to determine the byte order used for generating the byte sequence, but as a
892signature that helps in guessing the encoding. On encoding the utf-8-sig codec
893will write ``0xef``, ``0xbb``, ``0xbf`` as the first three bytes to the file. On
Ezio Melottifbb39812011-10-25 10:40:38 +0300894decoding ``utf-8-sig`` will skip those three bytes if they appear as the first
895three bytes in the file. In UTF-8, the use of the BOM is discouraged and
896should generally be avoided.
Georg Brandl116aa622007-08-15 14:28:22 +0000897
898
899.. _standard-encodings:
900
901Standard Encodings
902------------------
903
904Python comes with a number of codecs built-in, either implemented as C functions
905or with dictionaries as mapping tables. The following table lists the codecs by
906name, together with a few common aliases, and the languages for which the
907encoding is likely used. Neither the list of aliases nor the list of languages
908is meant to be exhaustive. Notice that spelling alternatives that only differ in
Georg Brandla6053b42009-09-01 08:11:14 +0000909case or use a hyphen instead of an underscore are also valid aliases; therefore,
910e.g. ``'utf-8'`` is a valid alias for the ``'utf_8'`` codec.
Georg Brandl116aa622007-08-15 14:28:22 +0000911
Alexander Belopolsky1d521462011-02-25 19:19:57 +0000912.. impl-detail::
913
914 Some common encodings can bypass the codecs lookup machinery to
915 improve performance. These optimization opportunities are only
916 recognized by CPython for a limited set of aliases: utf-8, utf8,
917 latin-1, latin1, iso-8859-1, mbcs (Windows only), ascii, utf-16,
918 and utf-32. Using alternative spellings for these encodings may
919 result in slower execution.
920
Georg Brandl116aa622007-08-15 14:28:22 +0000921Many of the character sets support the same languages. They vary in individual
922characters (e.g. whether the EURO SIGN is supported or not), and in the
923assignment of characters to code positions. For the European languages in
924particular, the following variants typically exist:
925
926* an ISO 8859 codeset
927
928* a Microsoft Windows code page, which is typically derived from a 8859 codeset,
929 but replaces control characters with additional graphic characters
930
931* an IBM EBCDIC code page
932
933* an IBM PC code page, which is ASCII compatible
934
Georg Brandl44ea77b2013-03-28 13:28:44 +0100935.. tabularcolumns:: |l|p{0.3\linewidth}|p{0.3\linewidth}|
936
Georg Brandl116aa622007-08-15 14:28:22 +0000937+-----------------+--------------------------------+--------------------------------+
938| Codec | Aliases | Languages |
939+=================+================================+================================+
940| ascii | 646, us-ascii | English |
941+-----------------+--------------------------------+--------------------------------+
942| big5 | big5-tw, csbig5 | Traditional Chinese |
943+-----------------+--------------------------------+--------------------------------+
944| big5hkscs | big5-hkscs, hkscs | Traditional Chinese |
945+-----------------+--------------------------------+--------------------------------+
946| cp037 | IBM037, IBM039 | English |
947+-----------------+--------------------------------+--------------------------------+
948| cp424 | EBCDIC-CP-HE, IBM424 | Hebrew |
949+-----------------+--------------------------------+--------------------------------+
950| cp437 | 437, IBM437 | English |
951+-----------------+--------------------------------+--------------------------------+
952| cp500 | EBCDIC-CP-BE, EBCDIC-CP-CH, | Western Europe |
953| | IBM500 | |
954+-----------------+--------------------------------+--------------------------------+
Amaury Forgeot d'Arcae6388d2009-07-15 19:21:18 +0000955| cp720 | | Arabic |
956+-----------------+--------------------------------+--------------------------------+
Georg Brandl116aa622007-08-15 14:28:22 +0000957| cp737 | | Greek |
958+-----------------+--------------------------------+--------------------------------+
959| cp775 | IBM775 | Baltic languages |
960+-----------------+--------------------------------+--------------------------------+
961| cp850 | 850, IBM850 | Western Europe |
962+-----------------+--------------------------------+--------------------------------+
963| cp852 | 852, IBM852 | Central and Eastern Europe |
964+-----------------+--------------------------------+--------------------------------+
965| cp855 | 855, IBM855 | Bulgarian, Byelorussian, |
966| | | Macedonian, Russian, Serbian |
967+-----------------+--------------------------------+--------------------------------+
968| cp856 | | Hebrew |
969+-----------------+--------------------------------+--------------------------------+
970| cp857 | 857, IBM857 | Turkish |
971+-----------------+--------------------------------+--------------------------------+
Benjamin Peterson5a6214a2010-06-27 22:41:29 +0000972| cp858 | 858, IBM858 | Western Europe |
973+-----------------+--------------------------------+--------------------------------+
Georg Brandl116aa622007-08-15 14:28:22 +0000974| cp860 | 860, IBM860 | Portuguese |
975+-----------------+--------------------------------+--------------------------------+
976| cp861 | 861, CP-IS, IBM861 | Icelandic |
977+-----------------+--------------------------------+--------------------------------+
978| cp862 | 862, IBM862 | Hebrew |
979+-----------------+--------------------------------+--------------------------------+
980| cp863 | 863, IBM863 | Canadian |
981+-----------------+--------------------------------+--------------------------------+
982| cp864 | IBM864 | Arabic |
983+-----------------+--------------------------------+--------------------------------+
984| cp865 | 865, IBM865 | Danish, Norwegian |
985+-----------------+--------------------------------+--------------------------------+
986| cp866 | 866, IBM866 | Russian |
987+-----------------+--------------------------------+--------------------------------+
988| cp869 | 869, CP-GR, IBM869 | Greek |
989+-----------------+--------------------------------+--------------------------------+
990| cp874 | | Thai |
991+-----------------+--------------------------------+--------------------------------+
992| cp875 | | Greek |
993+-----------------+--------------------------------+--------------------------------+
994| cp932 | 932, ms932, mskanji, ms-kanji | Japanese |
995+-----------------+--------------------------------+--------------------------------+
996| cp949 | 949, ms949, uhc | Korean |
997+-----------------+--------------------------------+--------------------------------+
998| cp950 | 950, ms950 | Traditional Chinese |
999+-----------------+--------------------------------+--------------------------------+
1000| cp1006 | | Urdu |
1001+-----------------+--------------------------------+--------------------------------+
1002| cp1026 | ibm1026 | Turkish |
1003+-----------------+--------------------------------+--------------------------------+
1004| cp1140 | ibm1140 | Western Europe |
1005+-----------------+--------------------------------+--------------------------------+
1006| cp1250 | windows-1250 | Central and Eastern Europe |
1007+-----------------+--------------------------------+--------------------------------+
1008| cp1251 | windows-1251 | Bulgarian, Byelorussian, |
1009| | | Macedonian, Russian, Serbian |
1010+-----------------+--------------------------------+--------------------------------+
1011| cp1252 | windows-1252 | Western Europe |
1012+-----------------+--------------------------------+--------------------------------+
1013| cp1253 | windows-1253 | Greek |
1014+-----------------+--------------------------------+--------------------------------+
1015| cp1254 | windows-1254 | Turkish |
1016+-----------------+--------------------------------+--------------------------------+
1017| cp1255 | windows-1255 | Hebrew |
1018+-----------------+--------------------------------+--------------------------------+
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00001019| cp1256 | windows-1256 | Arabic |
Georg Brandl116aa622007-08-15 14:28:22 +00001020+-----------------+--------------------------------+--------------------------------+
1021| cp1257 | windows-1257 | Baltic languages |
1022+-----------------+--------------------------------+--------------------------------+
1023| cp1258 | windows-1258 | Vietnamese |
1024+-----------------+--------------------------------+--------------------------------+
Victor Stinner2f3ca9f2011-10-27 01:38:56 +02001025| cp65001 | | Windows only: Windows UTF-8 |
1026| | | (``CP_UTF8``) |
1027| | | |
1028| | | .. versionadded:: 3.3 |
1029+-----------------+--------------------------------+--------------------------------+
Georg Brandl116aa622007-08-15 14:28:22 +00001030| euc_jp | eucjp, ujis, u-jis | Japanese |
1031+-----------------+--------------------------------+--------------------------------+
1032| euc_jis_2004 | jisx0213, eucjis2004 | Japanese |
1033+-----------------+--------------------------------+--------------------------------+
1034| euc_jisx0213 | eucjisx0213 | Japanese |
1035+-----------------+--------------------------------+--------------------------------+
1036| euc_kr | euckr, korean, ksc5601, | Korean |
1037| | ks_c-5601, ks_c-5601-1987, | |
1038| | ksx1001, ks_x-1001 | |
1039+-----------------+--------------------------------+--------------------------------+
1040| gb2312 | chinese, csiso58gb231280, euc- | Simplified Chinese |
1041| | cn, euccn, eucgb2312-cn, | |
1042| | gb2312-1980, gb2312-80, iso- | |
1043| | ir-58 | |
1044+-----------------+--------------------------------+--------------------------------+
1045| gbk | 936, cp936, ms936 | Unified Chinese |
1046+-----------------+--------------------------------+--------------------------------+
1047| gb18030 | gb18030-2000 | Unified Chinese |
1048+-----------------+--------------------------------+--------------------------------+
1049| hz | hzgb, hz-gb, hz-gb-2312 | Simplified Chinese |
1050+-----------------+--------------------------------+--------------------------------+
1051| iso2022_jp | csiso2022jp, iso2022jp, | Japanese |
1052| | iso-2022-jp | |
1053+-----------------+--------------------------------+--------------------------------+
1054| iso2022_jp_1 | iso2022jp-1, iso-2022-jp-1 | Japanese |
1055+-----------------+--------------------------------+--------------------------------+
1056| iso2022_jp_2 | iso2022jp-2, iso-2022-jp-2 | Japanese, Korean, Simplified |
1057| | | Chinese, Western Europe, Greek |
1058+-----------------+--------------------------------+--------------------------------+
1059| iso2022_jp_2004 | iso2022jp-2004, | Japanese |
1060| | iso-2022-jp-2004 | |
1061+-----------------+--------------------------------+--------------------------------+
1062| iso2022_jp_3 | iso2022jp-3, iso-2022-jp-3 | Japanese |
1063+-----------------+--------------------------------+--------------------------------+
1064| iso2022_jp_ext | iso2022jp-ext, iso-2022-jp-ext | Japanese |
1065+-----------------+--------------------------------+--------------------------------+
1066| iso2022_kr | csiso2022kr, iso2022kr, | Korean |
1067| | iso-2022-kr | |
1068+-----------------+--------------------------------+--------------------------------+
1069| latin_1 | iso-8859-1, iso8859-1, 8859, | West Europe |
1070| | cp819, latin, latin1, L1 | |
1071+-----------------+--------------------------------+--------------------------------+
1072| iso8859_2 | iso-8859-2, latin2, L2 | Central and Eastern Europe |
1073+-----------------+--------------------------------+--------------------------------+
1074| iso8859_3 | iso-8859-3, latin3, L3 | Esperanto, Maltese |
1075+-----------------+--------------------------------+--------------------------------+
Christian Heimesc3f30c42008-02-22 16:37:40 +00001076| iso8859_4 | iso-8859-4, latin4, L4 | Baltic languages |
Georg Brandl116aa622007-08-15 14:28:22 +00001077+-----------------+--------------------------------+--------------------------------+
1078| iso8859_5 | iso-8859-5, cyrillic | Bulgarian, Byelorussian, |
1079| | | Macedonian, Russian, Serbian |
1080+-----------------+--------------------------------+--------------------------------+
1081| iso8859_6 | iso-8859-6, arabic | Arabic |
1082+-----------------+--------------------------------+--------------------------------+
1083| iso8859_7 | iso-8859-7, greek, greek8 | Greek |
1084+-----------------+--------------------------------+--------------------------------+
1085| iso8859_8 | iso-8859-8, hebrew | Hebrew |
1086+-----------------+--------------------------------+--------------------------------+
1087| iso8859_9 | iso-8859-9, latin5, L5 | Turkish |
1088+-----------------+--------------------------------+--------------------------------+
1089| iso8859_10 | iso-8859-10, latin6, L6 | Nordic languages |
1090+-----------------+--------------------------------+--------------------------------+
Georg Brandl93dc9eb2010-03-14 10:56:14 +00001091| iso8859_13 | iso-8859-13, latin7, L7 | Baltic languages |
Georg Brandl116aa622007-08-15 14:28:22 +00001092+-----------------+--------------------------------+--------------------------------+
1093| iso8859_14 | iso-8859-14, latin8, L8 | Celtic languages |
1094+-----------------+--------------------------------+--------------------------------+
Georg Brandl93dc9eb2010-03-14 10:56:14 +00001095| iso8859_15 | iso-8859-15, latin9, L9 | Western Europe |
1096+-----------------+--------------------------------+--------------------------------+
1097| iso8859_16 | iso-8859-16, latin10, L10 | South-Eastern Europe |
Georg Brandl116aa622007-08-15 14:28:22 +00001098+-----------------+--------------------------------+--------------------------------+
1099| johab | cp1361, ms1361 | Korean |
1100+-----------------+--------------------------------+--------------------------------+
1101| koi8_r | | Russian |
1102+-----------------+--------------------------------+--------------------------------+
1103| koi8_u | | Ukrainian |
1104+-----------------+--------------------------------+--------------------------------+
1105| mac_cyrillic | maccyrillic | Bulgarian, Byelorussian, |
1106| | | Macedonian, Russian, Serbian |
1107+-----------------+--------------------------------+--------------------------------+
1108| mac_greek | macgreek | Greek |
1109+-----------------+--------------------------------+--------------------------------+
1110| mac_iceland | maciceland | Icelandic |
1111+-----------------+--------------------------------+--------------------------------+
1112| mac_latin2 | maclatin2, maccentraleurope | Central and Eastern Europe |
1113+-----------------+--------------------------------+--------------------------------+
Benjamin Peterson23110e72010-08-21 02:54:44 +00001114| mac_roman | macroman, macintosh | Western Europe |
Georg Brandl116aa622007-08-15 14:28:22 +00001115+-----------------+--------------------------------+--------------------------------+
1116| mac_turkish | macturkish | Turkish |
1117+-----------------+--------------------------------+--------------------------------+
1118| ptcp154 | csptcp154, pt154, cp154, | Kazakh |
1119| | cyrillic-asian | |
1120+-----------------+--------------------------------+--------------------------------+
1121| shift_jis | csshiftjis, shiftjis, sjis, | Japanese |
1122| | s_jis | |
1123+-----------------+--------------------------------+--------------------------------+
1124| shift_jis_2004 | shiftjis2004, sjis_2004, | Japanese |
1125| | sjis2004 | |
1126+-----------------+--------------------------------+--------------------------------+
1127| shift_jisx0213 | shiftjisx0213, sjisx0213, | Japanese |
1128| | s_jisx0213 | |
1129+-----------------+--------------------------------+--------------------------------+
Walter Dörwald41980ca2007-08-16 21:55:45 +00001130| utf_32 | U32, utf32 | all languages |
1131+-----------------+--------------------------------+--------------------------------+
1132| utf_32_be | UTF-32BE | all languages |
1133+-----------------+--------------------------------+--------------------------------+
1134| utf_32_le | UTF-32LE | all languages |
1135+-----------------+--------------------------------+--------------------------------+
Georg Brandl116aa622007-08-15 14:28:22 +00001136| utf_16 | U16, utf16 | all languages |
1137+-----------------+--------------------------------+--------------------------------+
Victor Stinner53a9dd72010-12-08 22:25:45 +00001138| utf_16_be | UTF-16BE | all languages |
Georg Brandl116aa622007-08-15 14:28:22 +00001139+-----------------+--------------------------------+--------------------------------+
Victor Stinner53a9dd72010-12-08 22:25:45 +00001140| utf_16_le | UTF-16LE | all languages |
Georg Brandl116aa622007-08-15 14:28:22 +00001141+-----------------+--------------------------------+--------------------------------+
1142| utf_7 | U7, unicode-1-1-utf-7 | all languages |
1143+-----------------+--------------------------------+--------------------------------+
1144| utf_8 | U8, UTF, utf8 | all languages |
1145+-----------------+--------------------------------+--------------------------------+
1146| utf_8_sig | | all languages |
1147+-----------------+--------------------------------+--------------------------------+
1148
Nick Coghlan650e3222013-05-23 20:24:02 +10001149Python Specific Encodings
1150-------------------------
1151
1152A number of predefined codecs are specific to Python, so their codec names have
1153no meaning outside Python. These are listed in the tables below based on the
1154expected input and output types (note that while text encodings are the most
1155common use case for codecs, the underlying codec infrastructure supports
1156arbitrary data transforms rather than just text encodings). For asymmetric
1157codecs, the stated purpose describes the encoding direction.
1158
1159The following codecs provide :class:`str` to :class:`bytes` encoding and
1160:term:`bytes-like object` to :class:`str` decoding, similar to the Unicode text
1161encodings.
Georg Brandl226878c2007-08-31 10:15:37 +00001162
Georg Brandl44ea77b2013-03-28 13:28:44 +01001163.. tabularcolumns:: |l|p{0.3\linewidth}|p{0.3\linewidth}|
1164
Georg Brandl30c78d62008-05-11 14:52:00 +00001165+--------------------+---------+---------------------------+
1166| Codec | Aliases | Purpose |
1167+====================+=========+===========================+
1168| idna | | Implements :rfc:`3490`, |
1169| | | see also |
1170| | | :mod:`encodings.idna` |
1171+--------------------+---------+---------------------------+
1172| mbcs | dbcs | Windows only: Encode |
1173| | | operand according to the |
1174| | | ANSI codepage (CP_ACP) |
1175+--------------------+---------+---------------------------+
1176| palmos | | Encoding of PalmOS 3.5 |
1177+--------------------+---------+---------------------------+
1178| punycode | | Implements :rfc:`3492` |
1179+--------------------+---------+---------------------------+
1180| raw_unicode_escape | | Produce a string that is |
1181| | | suitable as raw Unicode |
1182| | | literal in Python source |
1183| | | code |
1184+--------------------+---------+---------------------------+
1185| undefined | | Raise an exception for |
1186| | | all conversions. Can be |
1187| | | used as the system |
1188| | | encoding if no automatic |
1189| | | coercion between byte and |
1190| | | Unicode strings is |
1191| | | desired. |
1192+--------------------+---------+---------------------------+
1193| unicode_escape | | Produce a string that is |
1194| | | suitable as Unicode |
1195| | | literal in Python source |
1196| | | code |
1197+--------------------+---------+---------------------------+
1198| unicode_internal | | Return the internal |
1199| | | representation of the |
1200| | | operand |
Victor Stinner9f4b1e92011-11-10 20:56:30 +01001201| | | |
1202| | | .. deprecated:: 3.3 |
Georg Brandl30c78d62008-05-11 14:52:00 +00001203+--------------------+---------+---------------------------+
Georg Brandl116aa622007-08-15 14:28:22 +00001204
Nick Coghlan650e3222013-05-23 20:24:02 +10001205The following codecs provide :term:`bytes-like object` to :class:`bytes`
1206mappings.
1207
Georg Brandl02524622010-12-02 18:06:51 +00001208
Serhiy Storchaka9e62d352013-05-22 15:33:09 +03001209.. tabularcolumns:: |l|L|L|
Georg Brandl44ea77b2013-03-28 13:28:44 +01001210
Nick Coghlan650e3222013-05-23 20:24:02 +10001211+----------------------+---------------------------+------------------------------+
1212| Codec | Purpose | Encoder/decoder |
1213+======================+===========================+==============================+
1214| base64_codec [#b64]_ | Convert operand to MIME | :meth:`base64.b64encode`, |
1215| | base64 (the result always | :meth:`base64.b64decode` |
1216| | includes a trailing | |
1217| | ``'\n'``) | |
1218+----------------------+---------------------------+------------------------------+
1219| bz2_codec | Compress the operand | :meth:`bz2.compress`, |
1220| | using bz2 | :meth:`bz2.decompress` |
1221+----------------------+---------------------------+------------------------------+
1222| hex_codec | Convert operand to | :meth:`base64.b16encode`, |
1223| | hexadecimal | :meth:`base64.b16decode` |
1224| | representation, with two | |
1225| | digits per byte | |
1226+----------------------+---------------------------+------------------------------+
1227| quopri_codec | Convert operand to MIME | :meth:`quopri.encodestring`, |
1228| | quoted printable | :meth:`quopri.decodestring` |
1229+----------------------+---------------------------+------------------------------+
1230| uu_codec | Convert the operand using | :meth:`uu.encode`, |
1231| | uuencode | :meth:`uu.decode` |
1232+----------------------+---------------------------+------------------------------+
1233| zlib_codec | Compress the operand | :meth:`zlib.compress`, |
1234| | using gzip | :meth:`zlib.decompress` |
1235+----------------------+---------------------------+------------------------------+
Georg Brandl02524622010-12-02 18:06:51 +00001236
Nick Coghlan650e3222013-05-23 20:24:02 +10001237.. [#b64] Rather than accepting any :term:`bytes-like object`,
1238 ``'base64_codec'`` accepts only :class:`bytes` and :class:`bytearray` for
1239 encoding and only :class:`bytes`, :class:`bytearray`, and ASCII-only
1240 instances of :class:`str` for decoding
1241
1242
1243The following codecs provide :class:`str` to :class:`str` mappings.
Georg Brandl02524622010-12-02 18:06:51 +00001244
Ezio Melotti173d4102013-05-10 05:21:35 +03001245.. tabularcolumns:: |l|L|
Georg Brandl44ea77b2013-03-28 13:28:44 +01001246
Ezio Melotti173d4102013-05-10 05:21:35 +03001247+--------------------+---------------------------+
1248| Codec | Purpose |
1249+====================+===========================+
1250| rot_13 | Returns the Caesar-cypher |
1251| | encryption of the operand |
1252+--------------------+---------------------------+
Georg Brandl02524622010-12-02 18:06:51 +00001253
1254.. versionadded:: 3.2
Nick Coghlan650e3222013-05-23 20:24:02 +10001255 bytes-to-bytes and str-to-str codecs.
Georg Brandl02524622010-12-02 18:06:51 +00001256
Georg Brandl116aa622007-08-15 14:28:22 +00001257
1258:mod:`encodings.idna` --- Internationalized Domain Names in Applications
1259------------------------------------------------------------------------
1260
1261.. module:: encodings.idna
1262 :synopsis: Internationalized Domain Names implementation
1263.. moduleauthor:: Martin v. Löwis
1264
Georg Brandl116aa622007-08-15 14:28:22 +00001265This module implements :rfc:`3490` (Internationalized Domain Names in
1266Applications) and :rfc:`3492` (Nameprep: A Stringprep Profile for
1267Internationalized Domain Names (IDN)). It builds upon the ``punycode`` encoding
1268and :mod:`stringprep`.
1269
1270These RFCs together define a protocol to support non-ASCII characters in domain
1271names. A domain name containing non-ASCII characters (such as
1272``www.Alliancefrançaise.nu``) is converted into an ASCII-compatible encoding
1273(ACE, such as ``www.xn--alliancefranaise-npb.nu``). The ACE form of the domain
1274name is then used in all places where arbitrary characters are not allowed by
1275the protocol, such as DNS queries, HTTP :mailheader:`Host` fields, and so
1276on. This conversion is carried out in the application; if possible invisible to
1277the user: The application should transparently convert Unicode domain labels to
1278IDNA on the wire, and convert back ACE labels to Unicode before presenting them
1279to the user.
1280
R David Murraye0fd2f82011-04-13 14:12:18 -04001281Python supports this conversion in several ways: the ``idna`` codec performs
1282conversion between Unicode and ACE, separating an input string into labels
1283based on the separator characters defined in `section 3.1`_ (1) of :rfc:`3490`
1284and converting each label to ACE as required, and conversely separating an input
1285byte string into labels based on the ``.`` separator and converting any ACE
1286labels found into unicode. Furthermore, the :mod:`socket` module
Georg Brandl116aa622007-08-15 14:28:22 +00001287transparently converts Unicode host names to ACE, so that applications need not
1288be concerned about converting host names themselves when they pass them to the
1289socket module. On top of that, modules that have host names as function
Georg Brandl24420152008-05-26 16:32:26 +00001290parameters, such as :mod:`http.client` and :mod:`ftplib`, accept Unicode host
1291names (:mod:`http.client` then also transparently sends an IDNA hostname in the
Georg Brandl116aa622007-08-15 14:28:22 +00001292:mailheader:`Host` field if it sends that field at all).
1293
R David Murraye0fd2f82011-04-13 14:12:18 -04001294.. _section 3.1: http://tools.ietf.org/html/rfc3490#section-3.1
1295
Georg Brandl116aa622007-08-15 14:28:22 +00001296When receiving host names from the wire (such as in reverse name lookup), no
1297automatic conversion to Unicode is performed: Applications wishing to present
1298such host names to the user should decode them to Unicode.
1299
1300The module :mod:`encodings.idna` also implements the nameprep procedure, which
1301performs certain normalizations on host names, to achieve case-insensitivity of
1302international domain names, and to unify similar characters. The nameprep
1303functions can be used directly if desired.
1304
1305
1306.. function:: nameprep(label)
1307
1308 Return the nameprepped version of *label*. The implementation currently assumes
1309 query strings, so ``AllowUnassigned`` is true.
1310
1311
1312.. function:: ToASCII(label)
1313
1314 Convert a label to ASCII, as specified in :rfc:`3490`. ``UseSTD3ASCIIRules`` is
1315 assumed to be false.
1316
1317
1318.. function:: ToUnicode(label)
1319
1320 Convert a label to Unicode, as specified in :rfc:`3490`.
1321
1322
Victor Stinner554f3f02010-06-16 23:33:54 +00001323:mod:`encodings.mbcs` --- Windows ANSI codepage
1324-----------------------------------------------
1325
1326.. module:: encodings.mbcs
1327 :synopsis: Windows ANSI codepage
1328
Victor Stinner3a50e702011-10-18 21:21:00 +02001329Encode operand according to the ANSI codepage (CP_ACP).
Victor Stinner554f3f02010-06-16 23:33:54 +00001330
1331Availability: Windows only.
1332
Victor Stinner3a50e702011-10-18 21:21:00 +02001333.. versionchanged:: 3.3
1334 Support any error handler.
1335
Victor Stinner554f3f02010-06-16 23:33:54 +00001336.. versionchanged:: 3.2
1337 Before 3.2, the *errors* argument was ignored; ``'replace'`` was always used
1338 to encode, and ``'ignore'`` to decode.
1339
1340
Georg Brandl116aa622007-08-15 14:28:22 +00001341:mod:`encodings.utf_8_sig` --- UTF-8 codec with BOM signature
1342-------------------------------------------------------------
1343
1344.. module:: encodings.utf_8_sig
1345 :synopsis: UTF-8 codec with BOM signature
1346.. moduleauthor:: Walter Dörwald
1347
Georg Brandl116aa622007-08-15 14:28:22 +00001348This module implements a variant of the UTF-8 codec: On encoding a UTF-8 encoded
1349BOM will be prepended to the UTF-8 encoded bytes. For the stateful encoder this
1350is only done once (on the first write to the byte stream). For decoding an
1351optional UTF-8 encoded BOM at the start of the data will be skipped.
1352