blob: 9e1a9c744a07b6ae790fe7b486026a49b91e1c1d [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)
Georg Brandl495f7b52009-10-27 15:28:25 +000081 * ``'surrogateescape'``: replace with surrogate U+DCxx, see :pep:`383`
82
83 as well as any other error handling name defined via :func:`register_error`.
Georg Brandl116aa622007-08-15 14:28:22 +000084
85 In case a search function cannot find a given encoding, it should return
86 ``None``.
87
88
89.. function:: lookup(encoding)
90
91 Looks up the codec info in the Python codec registry and returns a
92 :class:`CodecInfo` object as defined above.
93
94 Encodings are first looked up in the registry's cache. If not found, the list of
95 registered search functions is scanned. If no :class:`CodecInfo` object is
96 found, a :exc:`LookupError` is raised. Otherwise, the :class:`CodecInfo` object
97 is stored in the cache and returned to the caller.
98
99To simplify access to the various codecs, the module provides these additional
100functions which use :func:`lookup` for the codec lookup:
101
102
103.. function:: getencoder(encoding)
104
105 Look up the codec for the given encoding and return its encoder function.
106
107 Raises a :exc:`LookupError` in case the encoding cannot be found.
108
109
110.. function:: getdecoder(encoding)
111
112 Look up the codec for the given encoding and return its decoder function.
113
114 Raises a :exc:`LookupError` in case the encoding cannot be found.
115
116
117.. function:: getincrementalencoder(encoding)
118
119 Look up the codec for the given encoding and return its incremental encoder
120 class or factory function.
121
122 Raises a :exc:`LookupError` in case the encoding cannot be found or the codec
123 doesn't support an incremental encoder.
124
Georg Brandl116aa622007-08-15 14:28:22 +0000125
126.. function:: getincrementaldecoder(encoding)
127
128 Look up the codec for the given encoding and return its incremental decoder
129 class or factory function.
130
131 Raises a :exc:`LookupError` in case the encoding cannot be found or the codec
132 doesn't support an incremental decoder.
133
Georg Brandl116aa622007-08-15 14:28:22 +0000134
135.. function:: getreader(encoding)
136
137 Look up the codec for the given encoding and return its StreamReader class or
138 factory function.
139
140 Raises a :exc:`LookupError` in case the encoding cannot be found.
141
142
143.. function:: getwriter(encoding)
144
145 Look up the codec for the given encoding and return its StreamWriter class or
146 factory function.
147
148 Raises a :exc:`LookupError` in case the encoding cannot be found.
149
150
151.. function:: register_error(name, error_handler)
152
153 Register the error handling function *error_handler* under the name *name*.
154 *error_handler* will be called during encoding and decoding in case of an error,
155 when *name* is specified as the errors parameter.
156
157 For encoding *error_handler* will be called with a :exc:`UnicodeEncodeError`
Benjamin Peterson19603552012-12-02 11:26:10 -0500158 instance, which contains information about the location of the error. The
159 error handler must either raise this or a different exception or return a
160 tuple with a replacement for the unencodable part of the input and a position
161 where encoding should continue. The replacement may be either :class:`str` or
162 :class:`bytes`. If the replacement is bytes, the encoder will simply copy
163 them into the output buffer. If the replacement is a string, the encoder will
164 encode the replacement. Encoding continues on original input at the
165 specified position. Negative position values will be treated as being
166 relative to the end of the input string. If the resulting position is out of
167 bound an :exc:`IndexError` will be raised.
Georg Brandl116aa622007-08-15 14:28:22 +0000168
169 Decoding and translating works similar, except :exc:`UnicodeDecodeError` or
170 :exc:`UnicodeTranslateError` will be passed to the handler and that the
171 replacement from the error handler will be put into the output directly.
172
173
174.. function:: lookup_error(name)
175
176 Return the error handler previously registered under the name *name*.
177
178 Raises a :exc:`LookupError` in case the handler cannot be found.
179
180
181.. function:: strict_errors(exception)
182
Georg Brandl495f7b52009-10-27 15:28:25 +0000183 Implements the ``strict`` error handling: each encoding or decoding error
184 raises a :exc:`UnicodeError`.
Georg Brandl116aa622007-08-15 14:28:22 +0000185
186
187.. function:: replace_errors(exception)
188
Georg Brandl495f7b52009-10-27 15:28:25 +0000189 Implements the ``replace`` error handling: malformed data is replaced with a
190 suitable replacement character such as ``'?'`` in bytestrings and
191 ``'\ufffd'`` in Unicode strings.
Georg Brandl116aa622007-08-15 14:28:22 +0000192
193
194.. function:: ignore_errors(exception)
195
Georg Brandl495f7b52009-10-27 15:28:25 +0000196 Implements the ``ignore`` error handling: malformed data is ignored and
197 encoding or decoding is continued without further notice.
Georg Brandl116aa622007-08-15 14:28:22 +0000198
199
Thomas Wouters89d996e2007-09-08 17:39:28 +0000200.. function:: xmlcharrefreplace_errors(exception)
Georg Brandl116aa622007-08-15 14:28:22 +0000201
Georg Brandl495f7b52009-10-27 15:28:25 +0000202 Implements the ``xmlcharrefreplace`` error handling (for encoding only): the
203 unencodable character is replaced by an appropriate XML character reference.
Georg Brandl116aa622007-08-15 14:28:22 +0000204
205
Thomas Wouters89d996e2007-09-08 17:39:28 +0000206.. function:: backslashreplace_errors(exception)
Georg Brandl116aa622007-08-15 14:28:22 +0000207
Georg Brandl495f7b52009-10-27 15:28:25 +0000208 Implements the ``backslashreplace`` error handling (for encoding only): the
209 unencodable character is replaced by a backslashed escape sequence.
Georg Brandl116aa622007-08-15 14:28:22 +0000210
211To simplify working with encoded files or stream, the module also defines these
212utility functions:
213
214
215.. function:: open(filename, mode[, encoding[, errors[, buffering]]])
216
217 Open an encoded file using the given *mode* and return a wrapped version
Christian Heimes18c66892008-02-17 13:31:39 +0000218 providing transparent encoding/decoding. The default file mode is ``'r'``
219 meaning to open the file in read mode.
Georg Brandl116aa622007-08-15 14:28:22 +0000220
221 .. note::
222
Georg Brandl30c78d62008-05-11 14:52:00 +0000223 The wrapped version's methods will accept and return strings only. Bytes
224 arguments will be rejected.
Georg Brandl116aa622007-08-15 14:28:22 +0000225
Christian Heimes18c66892008-02-17 13:31:39 +0000226 .. note::
227
228 Files are always opened in binary mode, even if no binary mode was
229 specified. This is done to avoid data loss due to encodings using 8-bit
Georg Brandl30c78d62008-05-11 14:52:00 +0000230 values. This means that no automatic conversion of ``b'\n'`` is done
Christian Heimes18c66892008-02-17 13:31:39 +0000231 on reading and writing.
232
Georg Brandl116aa622007-08-15 14:28:22 +0000233 *encoding* specifies the encoding which is to be used for the file.
234
235 *errors* may be given to define the error handling. It defaults to ``'strict'``
236 which causes a :exc:`ValueError` to be raised in case an encoding error occurs.
237
238 *buffering* has the same meaning as for the built-in :func:`open` function. It
239 defaults to line buffered.
240
241
Georg Brandl0d8f0732009-04-05 22:20:44 +0000242.. function:: EncodedFile(file, data_encoding, file_encoding=None, errors='strict')
Georg Brandl116aa622007-08-15 14:28:22 +0000243
244 Return a wrapped version of file which provides transparent encoding
245 translation.
246
Georg Brandl30c78d62008-05-11 14:52:00 +0000247 Bytes written to the wrapped file are interpreted according to the given
Georg Brandl0d8f0732009-04-05 22:20:44 +0000248 *data_encoding* and then written to the original file as bytes using the
249 *file_encoding*.
Georg Brandl116aa622007-08-15 14:28:22 +0000250
Georg Brandl0d8f0732009-04-05 22:20:44 +0000251 If *file_encoding* is not given, it defaults to *data_encoding*.
Georg Brandl116aa622007-08-15 14:28:22 +0000252
Georg Brandl0d8f0732009-04-05 22:20:44 +0000253 *errors* may be given to define the error handling. It defaults to
254 ``'strict'``, which causes :exc:`ValueError` to be raised in case an encoding
255 error occurs.
Georg Brandl116aa622007-08-15 14:28:22 +0000256
257
Georg Brandl0d8f0732009-04-05 22:20:44 +0000258.. function:: iterencode(iterator, encoding, errors='strict', **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +0000259
260 Uses an incremental encoder to iteratively encode the input provided by
Georg Brandl0d8f0732009-04-05 22:20:44 +0000261 *iterator*. This function is a :term:`generator`. *errors* (as well as any
Georg Brandl9afde1c2007-11-01 20:32:30 +0000262 other keyword argument) is passed through to the incremental encoder.
Georg Brandl116aa622007-08-15 14:28:22 +0000263
Georg Brandl116aa622007-08-15 14:28:22 +0000264
Georg Brandl0d8f0732009-04-05 22:20:44 +0000265.. function:: iterdecode(iterator, encoding, errors='strict', **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +0000266
267 Uses an incremental decoder to iteratively decode the input provided by
Georg Brandl0d8f0732009-04-05 22:20:44 +0000268 *iterator*. This function is a :term:`generator`. *errors* (as well as any
Georg Brandl9afde1c2007-11-01 20:32:30 +0000269 other keyword argument) is passed through to the incremental decoder.
Georg Brandl116aa622007-08-15 14:28:22 +0000270
Georg Brandl0d8f0732009-04-05 22:20:44 +0000271
Georg Brandl116aa622007-08-15 14:28:22 +0000272The module also provides the following constants which are useful for reading
273and writing to platform dependent files:
274
275
276.. data:: BOM
277 BOM_BE
278 BOM_LE
279 BOM_UTF8
280 BOM_UTF16
281 BOM_UTF16_BE
282 BOM_UTF16_LE
283 BOM_UTF32
284 BOM_UTF32_BE
285 BOM_UTF32_LE
286
287 These constants define various encodings of the Unicode byte order mark (BOM)
288 used in UTF-16 and UTF-32 data streams to indicate the byte order used in the
289 stream or file and in UTF-8 as a Unicode signature. :const:`BOM_UTF16` is either
290 :const:`BOM_UTF16_BE` or :const:`BOM_UTF16_LE` depending on the platform's
291 native byte order, :const:`BOM` is an alias for :const:`BOM_UTF16`,
292 :const:`BOM_LE` for :const:`BOM_UTF16_LE` and :const:`BOM_BE` for
293 :const:`BOM_UTF16_BE`. The others represent the BOM in UTF-8 and UTF-32
294 encodings.
295
296
297.. _codec-base-classes:
298
299Codec Base Classes
300------------------
301
302The :mod:`codecs` module defines a set of base classes which define the
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000303interface and can also be used to easily write your own codecs for use in
304Python.
Georg Brandl116aa622007-08-15 14:28:22 +0000305
306Each codec has to define four interfaces to make it usable as codec in Python:
307stateless encoder, stateless decoder, stream reader and stream writer. The
308stream reader and writers typically reuse the stateless encoder/decoder to
309implement the file protocols.
310
311The :class:`Codec` class defines the interface for stateless encoders/decoders.
312
313To simplify and standardize error handling, the :meth:`encode` and
314:meth:`decode` methods may implement different error handling schemes by
315providing the *errors* string argument. The following string values are defined
316and implemented by all standard Python codecs:
317
Georg Brandl44ea77b2013-03-28 13:28:44 +0100318.. tabularcolumns:: |l|L|
319
Georg Brandl116aa622007-08-15 14:28:22 +0000320+-------------------------+-----------------------------------------------+
321| Value | Meaning |
322+=========================+===============================================+
323| ``'strict'`` | Raise :exc:`UnicodeError` (or a subclass); |
324| | this is the default. |
325+-------------------------+-----------------------------------------------+
326| ``'ignore'`` | Ignore the character and continue with the |
327| | next. |
328+-------------------------+-----------------------------------------------+
329| ``'replace'`` | Replace with a suitable replacement |
330| | character; Python will use the official |
331| | U+FFFD REPLACEMENT CHARACTER for the built-in |
332| | Unicode codecs on decoding and '?' on |
333| | encoding. |
334+-------------------------+-----------------------------------------------+
335| ``'xmlcharrefreplace'`` | Replace with the appropriate XML character |
336| | reference (only for encoding). |
337+-------------------------+-----------------------------------------------+
338| ``'backslashreplace'`` | Replace with backslashed escape sequences |
339| | (only for encoding). |
340+-------------------------+-----------------------------------------------+
Martin v. Löwis3d2eca02009-06-29 06:35:26 +0000341| ``'surrogateescape'`` | Replace byte with surrogate U+DCxx, as defined|
342| | in :pep:`383`. |
Martin v. Löwis011e8422009-05-05 04:43:17 +0000343+-------------------------+-----------------------------------------------+
Georg Brandl116aa622007-08-15 14:28:22 +0000344
Martin v. Löwisdb12d452009-05-02 18:52:14 +0000345In addition, the following error handlers are specific to a single codec:
346
Martin v. Löwise0a2b722009-05-10 08:08:56 +0000347+-------------------+---------+-------------------------------------------+
348| Value | Codec | Meaning |
349+===================+=========+===========================================+
350|``'surrogatepass'``| utf-8 | Allow encoding and decoding of surrogate |
351| | | codes in UTF-8. |
352+-------------------+---------+-------------------------------------------+
Martin v. Löwisdb12d452009-05-02 18:52:14 +0000353
354.. versionadded:: 3.1
Martin v. Löwis43c57782009-05-10 08:15:24 +0000355 The ``'surrogateescape'`` and ``'surrogatepass'`` error handlers.
Martin v. Löwisdb12d452009-05-02 18:52:14 +0000356
Georg Brandl116aa622007-08-15 14:28:22 +0000357The set of allowed values can be extended via :meth:`register_error`.
358
359
360.. _codec-objects:
361
362Codec Objects
363^^^^^^^^^^^^^
364
365The :class:`Codec` class defines these methods which also define the function
366interfaces of the stateless encoder and decoder:
367
368
369.. method:: Codec.encode(input[, errors])
370
371 Encodes the object *input* and returns a tuple (output object, length consumed).
Georg Brandl30c78d62008-05-11 14:52:00 +0000372 Encoding converts a string object to a bytes object using a particular
Georg Brandl116aa622007-08-15 14:28:22 +0000373 character set encoding (e.g., ``cp1252`` or ``iso-8859-1``).
374
375 *errors* defines the error handling to apply. It defaults to ``'strict'``
376 handling.
377
378 The method may not store state in the :class:`Codec` instance. Use
379 :class:`StreamCodec` for codecs which have to keep state in order to make
380 encoding/decoding efficient.
381
382 The encoder must be able to handle zero length input and return an empty object
383 of the output object type in this situation.
384
385
386.. method:: Codec.decode(input[, errors])
387
Georg Brandl30c78d62008-05-11 14:52:00 +0000388 Decodes the object *input* and returns a tuple (output object, length
389 consumed). Decoding converts a bytes object encoded using a particular
390 character set encoding to a string object.
Georg Brandl116aa622007-08-15 14:28:22 +0000391
Georg Brandl30c78d62008-05-11 14:52:00 +0000392 *input* must be a bytes object or one which provides the read-only character
393 buffer interface -- for example, buffer objects and memory mapped files.
Georg Brandl116aa622007-08-15 14:28:22 +0000394
395 *errors* defines the error handling to apply. It defaults to ``'strict'``
396 handling.
397
398 The method may not store state in the :class:`Codec` instance. Use
399 :class:`StreamCodec` for codecs which have to keep state in order to make
400 encoding/decoding efficient.
401
402 The decoder must be able to handle zero length input and return an empty object
403 of the output object type in this situation.
404
405The :class:`IncrementalEncoder` and :class:`IncrementalDecoder` classes provide
406the basic interface for incremental encoding and decoding. Encoding/decoding the
407input isn't done with one call to the stateless encoder/decoder function, but
408with multiple calls to the :meth:`encode`/:meth:`decode` method of the
409incremental encoder/decoder. The incremental encoder/decoder keeps track of the
410encoding/decoding process during method calls.
411
412The joined output of calls to the :meth:`encode`/:meth:`decode` method is the
413same as if all the single inputs were joined into one, and this input was
414encoded/decoded with the stateless encoder/decoder.
415
416
417.. _incremental-encoder-objects:
418
419IncrementalEncoder Objects
420^^^^^^^^^^^^^^^^^^^^^^^^^^
421
Georg Brandl116aa622007-08-15 14:28:22 +0000422The :class:`IncrementalEncoder` class is used for encoding an input in multiple
423steps. It defines the following methods which every incremental encoder must
424define in order to be compatible with the Python codec registry.
425
426
427.. class:: IncrementalEncoder([errors])
428
429 Constructor for an :class:`IncrementalEncoder` instance.
430
431 All incremental encoders must provide this constructor interface. They are free
432 to add additional keyword arguments, but only the ones defined here are used by
433 the Python codec registry.
434
435 The :class:`IncrementalEncoder` may implement different error handling schemes
436 by providing the *errors* keyword argument. These parameters are predefined:
437
438 * ``'strict'`` Raise :exc:`ValueError` (or a subclass); this is the default.
439
440 * ``'ignore'`` Ignore the character and continue with the next.
441
442 * ``'replace'`` Replace with a suitable replacement character
443
444 * ``'xmlcharrefreplace'`` Replace with the appropriate XML character reference
445
446 * ``'backslashreplace'`` Replace with backslashed escape sequences.
447
448 The *errors* argument will be assigned to an attribute of the same name.
449 Assigning to this attribute makes it possible to switch between different error
450 handling strategies during the lifetime of the :class:`IncrementalEncoder`
451 object.
452
453 The set of allowed values for the *errors* argument can be extended with
454 :func:`register_error`.
455
456
Benjamin Petersone41251e2008-04-25 01:59:09 +0000457 .. method:: encode(object[, final])
Georg Brandl116aa622007-08-15 14:28:22 +0000458
Benjamin Petersone41251e2008-04-25 01:59:09 +0000459 Encodes *object* (taking the current state of the encoder into account)
460 and returns the resulting encoded object. If this is the last call to
461 :meth:`encode` *final* must be true (the default is false).
Georg Brandl116aa622007-08-15 14:28:22 +0000462
463
Benjamin Petersone41251e2008-04-25 01:59:09 +0000464 .. method:: reset()
Georg Brandl116aa622007-08-15 14:28:22 +0000465
Victor Stinnere15dce32011-05-30 22:56:00 +0200466 Reset the encoder to the initial state. The output is discarded: call
467 ``.encode('', final=True)`` to reset the encoder and to get the output.
Georg Brandl116aa622007-08-15 14:28:22 +0000468
469
470.. method:: IncrementalEncoder.getstate()
471
472 Return the current state of the encoder which must be an integer. The
473 implementation should make sure that ``0`` is the most common state. (States
474 that are more complicated than integers can be converted into an integer by
475 marshaling/pickling the state and encoding the bytes of the resulting string
476 into an integer).
477
Georg Brandl116aa622007-08-15 14:28:22 +0000478
479.. method:: IncrementalEncoder.setstate(state)
480
481 Set the state of the encoder to *state*. *state* must be an encoder state
482 returned by :meth:`getstate`.
483
Georg Brandl116aa622007-08-15 14:28:22 +0000484
485.. _incremental-decoder-objects:
486
487IncrementalDecoder Objects
488^^^^^^^^^^^^^^^^^^^^^^^^^^
489
490The :class:`IncrementalDecoder` class is used for decoding an input in multiple
491steps. It defines the following methods which every incremental decoder must
492define in order to be compatible with the Python codec registry.
493
494
495.. class:: IncrementalDecoder([errors])
496
497 Constructor for an :class:`IncrementalDecoder` instance.
498
499 All incremental decoders must provide this constructor interface. They are free
500 to add additional keyword arguments, but only the ones defined here are used by
501 the Python codec registry.
502
503 The :class:`IncrementalDecoder` may implement different error handling schemes
504 by providing the *errors* keyword argument. These parameters are predefined:
505
506 * ``'strict'`` Raise :exc:`ValueError` (or a subclass); this is the default.
507
508 * ``'ignore'`` Ignore the character and continue with the next.
509
510 * ``'replace'`` Replace with a suitable replacement character.
511
512 The *errors* argument will be assigned to an attribute of the same name.
513 Assigning to this attribute makes it possible to switch between different error
Benjamin Peterson3e4f0552008-09-02 00:31:15 +0000514 handling strategies during the lifetime of the :class:`IncrementalDecoder`
Georg Brandl116aa622007-08-15 14:28:22 +0000515 object.
516
517 The set of allowed values for the *errors* argument can be extended with
518 :func:`register_error`.
519
520
Benjamin Petersone41251e2008-04-25 01:59:09 +0000521 .. method:: decode(object[, final])
Georg Brandl116aa622007-08-15 14:28:22 +0000522
Benjamin Petersone41251e2008-04-25 01:59:09 +0000523 Decodes *object* (taking the current state of the decoder into account)
524 and returns the resulting decoded object. If this is the last call to
525 :meth:`decode` *final* must be true (the default is false). If *final* is
526 true the decoder must decode the input completely and must flush all
527 buffers. If this isn't possible (e.g. because of incomplete byte sequences
528 at the end of the input) it must initiate error handling just like in the
529 stateless case (which might raise an exception).
Georg Brandl116aa622007-08-15 14:28:22 +0000530
531
Benjamin Petersone41251e2008-04-25 01:59:09 +0000532 .. method:: reset()
Georg Brandl116aa622007-08-15 14:28:22 +0000533
Benjamin Petersone41251e2008-04-25 01:59:09 +0000534 Reset the decoder to the initial state.
Georg Brandl116aa622007-08-15 14:28:22 +0000535
536
Benjamin Petersone41251e2008-04-25 01:59:09 +0000537 .. method:: getstate()
Georg Brandl116aa622007-08-15 14:28:22 +0000538
Benjamin Petersone41251e2008-04-25 01:59:09 +0000539 Return the current state of the decoder. This must be a tuple with two
540 items, the first must be the buffer containing the still undecoded
541 input. The second must be an integer and can be additional state
542 info. (The implementation should make sure that ``0`` is the most common
543 additional state info.) If this additional state info is ``0`` it must be
544 possible to set the decoder to the state which has no input buffered and
545 ``0`` as the additional state info, so that feeding the previously
546 buffered input to the decoder returns it to the previous state without
547 producing any output. (Additional state info that is more complicated than
548 integers can be converted into an integer by marshaling/pickling the info
549 and encoding the bytes of the resulting string into an integer.)
Georg Brandl116aa622007-08-15 14:28:22 +0000550
Georg Brandl116aa622007-08-15 14:28:22 +0000551
Benjamin Petersone41251e2008-04-25 01:59:09 +0000552 .. method:: setstate(state)
Georg Brandl116aa622007-08-15 14:28:22 +0000553
Benjamin Petersone41251e2008-04-25 01:59:09 +0000554 Set the state of the encoder to *state*. *state* must be a decoder state
555 returned by :meth:`getstate`.
556
Georg Brandl116aa622007-08-15 14:28:22 +0000557
Georg Brandl116aa622007-08-15 14:28:22 +0000558The :class:`StreamWriter` and :class:`StreamReader` classes provide generic
559working interfaces which can be used to implement new encoding submodules very
560easily. See :mod:`encodings.utf_8` for an example of how this is done.
561
562
563.. _stream-writer-objects:
564
565StreamWriter Objects
566^^^^^^^^^^^^^^^^^^^^
567
568The :class:`StreamWriter` class is a subclass of :class:`Codec` and defines the
569following methods which every stream writer must define in order to be
570compatible with the Python codec registry.
571
572
573.. class:: StreamWriter(stream[, errors])
574
575 Constructor for a :class:`StreamWriter` instance.
576
577 All stream writers must provide this constructor interface. They are free to add
578 additional keyword arguments, but only the ones defined here are used by the
579 Python codec registry.
580
581 *stream* must be a file-like object open for writing binary data.
582
583 The :class:`StreamWriter` may implement different error handling schemes by
584 providing the *errors* keyword argument. These parameters are predefined:
585
586 * ``'strict'`` Raise :exc:`ValueError` (or a subclass); this is the default.
587
588 * ``'ignore'`` Ignore the character and continue with the next.
589
590 * ``'replace'`` Replace with a suitable replacement character
591
592 * ``'xmlcharrefreplace'`` Replace with the appropriate XML character reference
593
594 * ``'backslashreplace'`` Replace with backslashed escape sequences.
595
596 The *errors* argument will be assigned to an attribute of the same name.
597 Assigning to this attribute makes it possible to switch between different error
598 handling strategies during the lifetime of the :class:`StreamWriter` object.
599
600 The set of allowed values for the *errors* argument can be extended with
601 :func:`register_error`.
602
603
Benjamin Petersone41251e2008-04-25 01:59:09 +0000604 .. method:: write(object)
Georg Brandl116aa622007-08-15 14:28:22 +0000605
Benjamin Petersone41251e2008-04-25 01:59:09 +0000606 Writes the object's contents encoded to the stream.
Georg Brandl116aa622007-08-15 14:28:22 +0000607
608
Benjamin Petersone41251e2008-04-25 01:59:09 +0000609 .. method:: writelines(list)
Georg Brandl116aa622007-08-15 14:28:22 +0000610
Benjamin Petersone41251e2008-04-25 01:59:09 +0000611 Writes the concatenated list of strings to the stream (possibly by reusing
612 the :meth:`write` method).
Georg Brandl116aa622007-08-15 14:28:22 +0000613
614
Benjamin Petersone41251e2008-04-25 01:59:09 +0000615 .. method:: reset()
Georg Brandl116aa622007-08-15 14:28:22 +0000616
Benjamin Petersone41251e2008-04-25 01:59:09 +0000617 Flushes and resets the codec buffers used for keeping state.
Georg Brandl116aa622007-08-15 14:28:22 +0000618
Benjamin Petersone41251e2008-04-25 01:59:09 +0000619 Calling this method should ensure that the data on the output is put into
620 a clean state that allows appending of new fresh data without having to
621 rescan the whole stream to recover state.
622
Georg Brandl116aa622007-08-15 14:28:22 +0000623
624In addition to the above methods, the :class:`StreamWriter` must also inherit
625all other methods and attributes from the underlying stream.
626
627
628.. _stream-reader-objects:
629
630StreamReader Objects
631^^^^^^^^^^^^^^^^^^^^
632
633The :class:`StreamReader` class is a subclass of :class:`Codec` and defines the
634following methods which every stream reader must define in order to be
635compatible with the Python codec registry.
636
637
638.. class:: StreamReader(stream[, errors])
639
640 Constructor for a :class:`StreamReader` instance.
641
642 All stream readers must provide this constructor interface. They are free to add
643 additional keyword arguments, but only the ones defined here are used by the
644 Python codec registry.
645
646 *stream* must be a file-like object open for reading (binary) data.
647
648 The :class:`StreamReader` may implement different error handling schemes by
649 providing the *errors* keyword argument. These parameters are defined:
650
651 * ``'strict'`` Raise :exc:`ValueError` (or a subclass); this is the default.
652
653 * ``'ignore'`` Ignore the character and continue with the next.
654
655 * ``'replace'`` Replace with a suitable replacement character.
656
657 The *errors* argument will be assigned to an attribute of the same name.
658 Assigning to this attribute makes it possible to switch between different error
659 handling strategies during the lifetime of the :class:`StreamReader` object.
660
661 The set of allowed values for the *errors* argument can be extended with
662 :func:`register_error`.
663
664
Benjamin Petersone41251e2008-04-25 01:59:09 +0000665 .. method:: read([size[, chars, [firstline]]])
Georg Brandl116aa622007-08-15 14:28:22 +0000666
Benjamin Petersone41251e2008-04-25 01:59:09 +0000667 Decodes data from the stream and returns the resulting object.
Georg Brandl116aa622007-08-15 14:28:22 +0000668
Benjamin Petersone41251e2008-04-25 01:59:09 +0000669 *chars* indicates the number of characters to read from the
670 stream. :func:`read` will never return more than *chars* characters, but
671 it might return less, if there are not enough characters available.
Georg Brandl116aa622007-08-15 14:28:22 +0000672
Benjamin Petersone41251e2008-04-25 01:59:09 +0000673 *size* indicates the approximate maximum number of bytes to read from the
674 stream for decoding purposes. The decoder can modify this setting as
675 appropriate. The default value -1 indicates to read and decode as much as
676 possible. *size* is intended to prevent having to decode huge files in
677 one step.
Georg Brandl116aa622007-08-15 14:28:22 +0000678
Benjamin Petersone41251e2008-04-25 01:59:09 +0000679 *firstline* indicates that it would be sufficient to only return the first
680 line, if there are decoding errors on later lines.
Georg Brandl116aa622007-08-15 14:28:22 +0000681
Benjamin Petersone41251e2008-04-25 01:59:09 +0000682 The method should use a greedy read strategy meaning that it should read
683 as much data as is allowed within the definition of the encoding and the
684 given size, e.g. if optional encoding endings or state markers are
685 available on the stream, these should be read too.
Georg Brandl116aa622007-08-15 14:28:22 +0000686
Georg Brandl116aa622007-08-15 14:28:22 +0000687
Benjamin Petersone41251e2008-04-25 01:59:09 +0000688 .. method:: readline([size[, keepends]])
Georg Brandl116aa622007-08-15 14:28:22 +0000689
Benjamin Petersone41251e2008-04-25 01:59:09 +0000690 Read one line from the input stream and return the decoded data.
Georg Brandl116aa622007-08-15 14:28:22 +0000691
Benjamin Petersone41251e2008-04-25 01:59:09 +0000692 *size*, if given, is passed as size argument to the stream's
693 :meth:`readline` method.
Georg Brandl116aa622007-08-15 14:28:22 +0000694
Benjamin Petersone41251e2008-04-25 01:59:09 +0000695 If *keepends* is false line-endings will be stripped from the lines
696 returned.
Georg Brandl116aa622007-08-15 14:28:22 +0000697
Georg Brandl116aa622007-08-15 14:28:22 +0000698
Benjamin Petersone41251e2008-04-25 01:59:09 +0000699 .. method:: readlines([sizehint[, keepends]])
Georg Brandl116aa622007-08-15 14:28:22 +0000700
Benjamin Petersone41251e2008-04-25 01:59:09 +0000701 Read all lines available on the input stream and return them as a list of
702 lines.
Georg Brandl116aa622007-08-15 14:28:22 +0000703
Benjamin Petersone41251e2008-04-25 01:59:09 +0000704 Line-endings are implemented using the codec's decoder method and are
705 included in the list entries if *keepends* is true.
Georg Brandl116aa622007-08-15 14:28:22 +0000706
Benjamin Petersone41251e2008-04-25 01:59:09 +0000707 *sizehint*, if given, is passed as the *size* argument to the stream's
708 :meth:`read` method.
Georg Brandl116aa622007-08-15 14:28:22 +0000709
710
Benjamin Petersone41251e2008-04-25 01:59:09 +0000711 .. method:: reset()
Georg Brandl116aa622007-08-15 14:28:22 +0000712
Benjamin Petersone41251e2008-04-25 01:59:09 +0000713 Resets the codec buffers used for keeping state.
Georg Brandl116aa622007-08-15 14:28:22 +0000714
Benjamin Petersone41251e2008-04-25 01:59:09 +0000715 Note that no stream repositioning should take place. This method is
716 primarily intended to be able to recover from decoding errors.
717
Georg Brandl116aa622007-08-15 14:28:22 +0000718
719In addition to the above methods, the :class:`StreamReader` must also inherit
720all other methods and attributes from the underlying stream.
721
722The next two base classes are included for convenience. They are not needed by
723the codec registry, but may provide useful in practice.
724
725
726.. _stream-reader-writer:
727
728StreamReaderWriter Objects
729^^^^^^^^^^^^^^^^^^^^^^^^^^
730
731The :class:`StreamReaderWriter` allows wrapping streams which work in both read
732and write modes.
733
734The design is such that one can use the factory functions returned by the
735:func:`lookup` function to construct the instance.
736
737
738.. class:: StreamReaderWriter(stream, Reader, Writer, errors)
739
740 Creates a :class:`StreamReaderWriter` instance. *stream* must be a file-like
741 object. *Reader* and *Writer* must be factory functions or classes providing the
742 :class:`StreamReader` and :class:`StreamWriter` interface resp. Error handling
743 is done in the same way as defined for the stream readers and writers.
744
745:class:`StreamReaderWriter` instances define the combined interfaces of
746:class:`StreamReader` and :class:`StreamWriter` classes. They inherit all other
747methods and attributes from the underlying stream.
748
749
750.. _stream-recoder-objects:
751
752StreamRecoder Objects
753^^^^^^^^^^^^^^^^^^^^^
754
755The :class:`StreamRecoder` provide a frontend - backend view of encoding data
756which is sometimes useful when dealing with different encoding environments.
757
758The design is such that one can use the factory functions returned by the
759:func:`lookup` function to construct the instance.
760
761
762.. class:: StreamRecoder(stream, encode, decode, Reader, Writer, errors)
763
764 Creates a :class:`StreamRecoder` instance which implements a two-way conversion:
765 *encode* and *decode* work on the frontend (the input to :meth:`read` and output
766 of :meth:`write`) while *Reader* and *Writer* work on the backend (reading and
767 writing to the stream).
768
769 You can use these objects to do transparent direct recodings from e.g. Latin-1
770 to UTF-8 and back.
771
772 *stream* must be a file-like object.
773
774 *encode*, *decode* must adhere to the :class:`Codec` interface. *Reader*,
775 *Writer* must be factory functions or classes providing objects of the
776 :class:`StreamReader` and :class:`StreamWriter` interface respectively.
777
778 *encode* and *decode* are needed for the frontend translation, *Reader* and
Georg Brandl30c78d62008-05-11 14:52:00 +0000779 *Writer* for the backend translation.
Georg Brandl116aa622007-08-15 14:28:22 +0000780
781 Error handling is done in the same way as defined for the stream readers and
782 writers.
783
Benjamin Petersone41251e2008-04-25 01:59:09 +0000784
Georg Brandl116aa622007-08-15 14:28:22 +0000785:class:`StreamRecoder` instances define the combined interfaces of
786:class:`StreamReader` and :class:`StreamWriter` classes. They inherit all other
787methods and attributes from the underlying stream.
788
789
790.. _encodings-overview:
791
792Encodings and Unicode
793---------------------
794
Ezio Melotti7a03f642011-10-25 10:30:19 +0300795Strings are stored internally as sequences of codepoints in range ``0 - 10FFFF``
796(see :pep:`393` for more details about the implementation).
797Once a string object is used outside of CPU and memory, CPU endianness
Georg Brandl116aa622007-08-15 14:28:22 +0000798and how these arrays are stored as bytes become an issue. Transforming a
Georg Brandl30c78d62008-05-11 14:52:00 +0000799string object into a sequence of bytes is called encoding and recreating the
800string object from the sequence of bytes is known as decoding. There are many
Georg Brandl116aa622007-08-15 14:28:22 +0000801different methods for how this transformation can be done (these methods are
802also called encodings). The simplest method is to map the codepoints 0-255 to
Georg Brandl30c78d62008-05-11 14:52:00 +0000803the bytes ``0x0``-``0xff``. This means that a string object that contains
Georg Brandl116aa622007-08-15 14:28:22 +0000804codepoints above ``U+00FF`` can't be encoded with this method (which is called
Georg Brandl30c78d62008-05-11 14:52:00 +0000805``'latin-1'`` or ``'iso-8859-1'``). :func:`str.encode` will raise a
Georg Brandl116aa622007-08-15 14:28:22 +0000806:exc:`UnicodeEncodeError` that looks like this: ``UnicodeEncodeError: 'latin-1'
Georg Brandl30c78d62008-05-11 14:52:00 +0000807codec can't encode character '\u1234' in position 3: ordinal not in
Georg Brandl116aa622007-08-15 14:28:22 +0000808range(256)``.
809
810There's another group of encodings (the so called charmap encodings) that choose
Georg Brandl30c78d62008-05-11 14:52:00 +0000811a different subset of all Unicode code points and how these codepoints are
Georg Brandl116aa622007-08-15 14:28:22 +0000812mapped to the bytes ``0x0``-``0xff``. To see how this is done simply open
813e.g. :file:`encodings/cp1252.py` (which is an encoding that is used primarily on
814Windows). There's a string constant with 256 characters that shows you which
815character is mapped to which byte value.
816
Ezio Melottifbb39812011-10-25 10:40:38 +0300817All of these encodings can only encode 256 of the 1114112 codepoints
Georg Brandl30c78d62008-05-11 14:52:00 +0000818defined in Unicode. A simple and straightforward way that can store each Unicode
Ezio Melottifbb39812011-10-25 10:40:38 +0300819code point, is to store each codepoint as four consecutive bytes. There are two
820possibilities: store the bytes in big endian or in little endian order. These
821two encodings are called ``UTF-32-BE`` and ``UTF-32-LE`` respectively. Their
822disadvantage is that if e.g. you use ``UTF-32-BE`` on a little endian machine you
823will always have to swap bytes on encoding and decoding. ``UTF-32`` avoids this
824problem: bytes will always be in natural endianness. When these bytes are read
Georg Brandl116aa622007-08-15 14:28:22 +0000825by a CPU with a different endianness, then bytes have to be swapped though. To
Ezio Melottifbb39812011-10-25 10:40:38 +0300826be able to detect the endianness of a ``UTF-16`` or ``UTF-32`` byte sequence,
827there's the so called BOM ("Byte Order Mark"). This is the Unicode character
828``U+FEFF``. This character can be prepended to every ``UTF-16`` or ``UTF-32``
829byte sequence. The byte swapped version of this character (``0xFFFE``) is an
830illegal character that may not appear in a Unicode text. So when the
831first character in an ``UTF-16`` or ``UTF-32`` byte sequence
Georg Brandl116aa622007-08-15 14:28:22 +0000832appears to be a ``U+FFFE`` the bytes have to be swapped on decoding.
Ezio Melottifbb39812011-10-25 10:40:38 +0300833Unfortunately the character ``U+FEFF`` had a second purpose as
834a ``ZERO WIDTH NO-BREAK SPACE``: a character that has no width and doesn't allow
Georg Brandl116aa622007-08-15 14:28:22 +0000835a word to be split. It can e.g. be used to give hints to a ligature algorithm.
836With Unicode 4.0 using ``U+FEFF`` as a ``ZERO WIDTH NO-BREAK SPACE`` has been
837deprecated (with ``U+2060`` (``WORD JOINER``) assuming this role). Nevertheless
Ezio Melottifbb39812011-10-25 10:40:38 +0300838Unicode software still must be able to handle ``U+FEFF`` in both roles: as a BOM
Georg Brandl116aa622007-08-15 14:28:22 +0000839it's a device to determine the storage layout of the encoded bytes, and vanishes
Georg Brandl30c78d62008-05-11 14:52:00 +0000840once the byte sequence has been decoded into a string; as a ``ZERO WIDTH
Georg Brandl116aa622007-08-15 14:28:22 +0000841NO-BREAK SPACE`` it's a normal character that will be decoded like any other.
842
843There's another encoding that is able to encoding the full range of Unicode
844characters: UTF-8. UTF-8 is an 8-bit encoding, which means there are no issues
845with byte order in UTF-8. Each byte in a UTF-8 byte sequence consists of two
Ezio Melottifbb39812011-10-25 10:40:38 +0300846parts: marker bits (the most significant bits) and payload bits. The marker bits
Ezio Melotti222b2082011-09-01 08:11:28 +0300847are a sequence of zero to four ``1`` bits followed by a ``0`` bit. Unicode characters are
Georg Brandl116aa622007-08-15 14:28:22 +0000848encoded like this (with x being payload bits, which when concatenated give the
849Unicode character):
850
851+-----------------------------------+----------------------------------------------+
852| Range | Encoding |
853+===================================+==============================================+
854| ``U-00000000`` ... ``U-0000007F`` | 0xxxxxxx |
855+-----------------------------------+----------------------------------------------+
856| ``U-00000080`` ... ``U-000007FF`` | 110xxxxx 10xxxxxx |
857+-----------------------------------+----------------------------------------------+
858| ``U-00000800`` ... ``U-0000FFFF`` | 1110xxxx 10xxxxxx 10xxxxxx |
859+-----------------------------------+----------------------------------------------+
Ezio Melotti222b2082011-09-01 08:11:28 +0300860| ``U-00010000`` ... ``U-0010FFFF`` | 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx |
Georg Brandl116aa622007-08-15 14:28:22 +0000861+-----------------------------------+----------------------------------------------+
862
863The least significant bit of the Unicode character is the rightmost x bit.
864
865As UTF-8 is an 8-bit encoding no BOM is required and any ``U+FEFF`` character in
Georg Brandl30c78d62008-05-11 14:52:00 +0000866the decoded string (even if it's the first character) is treated as a ``ZERO
867WIDTH NO-BREAK SPACE``.
Georg Brandl116aa622007-08-15 14:28:22 +0000868
869Without external information it's impossible to reliably determine which
Georg Brandl30c78d62008-05-11 14:52:00 +0000870encoding was used for encoding a string. Each charmap encoding can
Georg Brandl116aa622007-08-15 14:28:22 +0000871decode any random byte sequence. However that's not possible with UTF-8, as
872UTF-8 byte sequences have a structure that doesn't allow arbitrary byte
Thomas Wouters89d996e2007-09-08 17:39:28 +0000873sequences. To increase the reliability with which a UTF-8 encoding can be
Georg Brandl116aa622007-08-15 14:28:22 +0000874detected, Microsoft invented a variant of UTF-8 (that Python 2.5 calls
875``"utf-8-sig"``) for its Notepad program: Before any of the Unicode characters
876is written to the file, a UTF-8 encoded BOM (which looks like this as a byte
877sequence: ``0xef``, ``0xbb``, ``0xbf``) is written. As it's rather improbable
878that any charmap encoded file starts with these byte values (which would e.g.
879map to
880
881 | LATIN SMALL LETTER I WITH DIAERESIS
882 | RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK
883 | INVERTED QUESTION MARK
884
Ezio Melottifbb39812011-10-25 10:40:38 +0300885in iso-8859-1), this increases the probability that a ``utf-8-sig`` encoding can be
Georg Brandl116aa622007-08-15 14:28:22 +0000886correctly guessed from the byte sequence. So here the BOM is not used to be able
887to determine the byte order used for generating the byte sequence, but as a
888signature that helps in guessing the encoding. On encoding the utf-8-sig codec
889will write ``0xef``, ``0xbb``, ``0xbf`` as the first three bytes to the file. On
Ezio Melottifbb39812011-10-25 10:40:38 +0300890decoding ``utf-8-sig`` will skip those three bytes if they appear as the first
891three bytes in the file. In UTF-8, the use of the BOM is discouraged and
892should generally be avoided.
Georg Brandl116aa622007-08-15 14:28:22 +0000893
894
895.. _standard-encodings:
896
897Standard Encodings
898------------------
899
900Python comes with a number of codecs built-in, either implemented as C functions
901or with dictionaries as mapping tables. The following table lists the codecs by
902name, together with a few common aliases, and the languages for which the
903encoding is likely used. Neither the list of aliases nor the list of languages
904is meant to be exhaustive. Notice that spelling alternatives that only differ in
Georg Brandla6053b42009-09-01 08:11:14 +0000905case or use a hyphen instead of an underscore are also valid aliases; therefore,
906e.g. ``'utf-8'`` is a valid alias for the ``'utf_8'`` codec.
Georg Brandl116aa622007-08-15 14:28:22 +0000907
Alexander Belopolsky1d521462011-02-25 19:19:57 +0000908.. impl-detail::
909
910 Some common encodings can bypass the codecs lookup machinery to
911 improve performance. These optimization opportunities are only
912 recognized by CPython for a limited set of aliases: utf-8, utf8,
913 latin-1, latin1, iso-8859-1, mbcs (Windows only), ascii, utf-16,
914 and utf-32. Using alternative spellings for these encodings may
915 result in slower execution.
916
Georg Brandl116aa622007-08-15 14:28:22 +0000917Many of the character sets support the same languages. They vary in individual
918characters (e.g. whether the EURO SIGN is supported or not), and in the
919assignment of characters to code positions. For the European languages in
920particular, the following variants typically exist:
921
922* an ISO 8859 codeset
923
924* a Microsoft Windows code page, which is typically derived from a 8859 codeset,
925 but replaces control characters with additional graphic characters
926
927* an IBM EBCDIC code page
928
929* an IBM PC code page, which is ASCII compatible
930
Georg Brandl44ea77b2013-03-28 13:28:44 +0100931.. tabularcolumns:: |l|p{0.3\linewidth}|p{0.3\linewidth}|
932
Georg Brandl116aa622007-08-15 14:28:22 +0000933+-----------------+--------------------------------+--------------------------------+
934| Codec | Aliases | Languages |
935+=================+================================+================================+
936| ascii | 646, us-ascii | English |
937+-----------------+--------------------------------+--------------------------------+
938| big5 | big5-tw, csbig5 | Traditional Chinese |
939+-----------------+--------------------------------+--------------------------------+
940| big5hkscs | big5-hkscs, hkscs | Traditional Chinese |
941+-----------------+--------------------------------+--------------------------------+
942| cp037 | IBM037, IBM039 | English |
943+-----------------+--------------------------------+--------------------------------+
944| cp424 | EBCDIC-CP-HE, IBM424 | Hebrew |
945+-----------------+--------------------------------+--------------------------------+
946| cp437 | 437, IBM437 | English |
947+-----------------+--------------------------------+--------------------------------+
948| cp500 | EBCDIC-CP-BE, EBCDIC-CP-CH, | Western Europe |
949| | IBM500 | |
950+-----------------+--------------------------------+--------------------------------+
Amaury Forgeot d'Arcae6388d2009-07-15 19:21:18 +0000951| cp720 | | Arabic |
952+-----------------+--------------------------------+--------------------------------+
Georg Brandl116aa622007-08-15 14:28:22 +0000953| cp737 | | Greek |
954+-----------------+--------------------------------+--------------------------------+
955| cp775 | IBM775 | Baltic languages |
956+-----------------+--------------------------------+--------------------------------+
957| cp850 | 850, IBM850 | Western Europe |
958+-----------------+--------------------------------+--------------------------------+
959| cp852 | 852, IBM852 | Central and Eastern Europe |
960+-----------------+--------------------------------+--------------------------------+
961| cp855 | 855, IBM855 | Bulgarian, Byelorussian, |
962| | | Macedonian, Russian, Serbian |
963+-----------------+--------------------------------+--------------------------------+
964| cp856 | | Hebrew |
965+-----------------+--------------------------------+--------------------------------+
966| cp857 | 857, IBM857 | Turkish |
967+-----------------+--------------------------------+--------------------------------+
Benjamin Peterson5a6214a2010-06-27 22:41:29 +0000968| cp858 | 858, IBM858 | Western Europe |
969+-----------------+--------------------------------+--------------------------------+
Georg Brandl116aa622007-08-15 14:28:22 +0000970| cp860 | 860, IBM860 | Portuguese |
971+-----------------+--------------------------------+--------------------------------+
972| cp861 | 861, CP-IS, IBM861 | Icelandic |
973+-----------------+--------------------------------+--------------------------------+
974| cp862 | 862, IBM862 | Hebrew |
975+-----------------+--------------------------------+--------------------------------+
976| cp863 | 863, IBM863 | Canadian |
977+-----------------+--------------------------------+--------------------------------+
978| cp864 | IBM864 | Arabic |
979+-----------------+--------------------------------+--------------------------------+
980| cp865 | 865, IBM865 | Danish, Norwegian |
981+-----------------+--------------------------------+--------------------------------+
982| cp866 | 866, IBM866 | Russian |
983+-----------------+--------------------------------+--------------------------------+
984| cp869 | 869, CP-GR, IBM869 | Greek |
985+-----------------+--------------------------------+--------------------------------+
986| cp874 | | Thai |
987+-----------------+--------------------------------+--------------------------------+
988| cp875 | | Greek |
989+-----------------+--------------------------------+--------------------------------+
990| cp932 | 932, ms932, mskanji, ms-kanji | Japanese |
991+-----------------+--------------------------------+--------------------------------+
992| cp949 | 949, ms949, uhc | Korean |
993+-----------------+--------------------------------+--------------------------------+
994| cp950 | 950, ms950 | Traditional Chinese |
995+-----------------+--------------------------------+--------------------------------+
996| cp1006 | | Urdu |
997+-----------------+--------------------------------+--------------------------------+
998| cp1026 | ibm1026 | Turkish |
999+-----------------+--------------------------------+--------------------------------+
1000| cp1140 | ibm1140 | Western Europe |
1001+-----------------+--------------------------------+--------------------------------+
1002| cp1250 | windows-1250 | Central and Eastern Europe |
1003+-----------------+--------------------------------+--------------------------------+
1004| cp1251 | windows-1251 | Bulgarian, Byelorussian, |
1005| | | Macedonian, Russian, Serbian |
1006+-----------------+--------------------------------+--------------------------------+
1007| cp1252 | windows-1252 | Western Europe |
1008+-----------------+--------------------------------+--------------------------------+
1009| cp1253 | windows-1253 | Greek |
1010+-----------------+--------------------------------+--------------------------------+
1011| cp1254 | windows-1254 | Turkish |
1012+-----------------+--------------------------------+--------------------------------+
1013| cp1255 | windows-1255 | Hebrew |
1014+-----------------+--------------------------------+--------------------------------+
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00001015| cp1256 | windows-1256 | Arabic |
Georg Brandl116aa622007-08-15 14:28:22 +00001016+-----------------+--------------------------------+--------------------------------+
1017| cp1257 | windows-1257 | Baltic languages |
1018+-----------------+--------------------------------+--------------------------------+
1019| cp1258 | windows-1258 | Vietnamese |
1020+-----------------+--------------------------------+--------------------------------+
Victor Stinner2f3ca9f2011-10-27 01:38:56 +02001021| cp65001 | | Windows only: Windows UTF-8 |
1022| | | (``CP_UTF8``) |
1023| | | |
1024| | | .. versionadded:: 3.3 |
1025+-----------------+--------------------------------+--------------------------------+
Georg Brandl116aa622007-08-15 14:28:22 +00001026| euc_jp | eucjp, ujis, u-jis | Japanese |
1027+-----------------+--------------------------------+--------------------------------+
1028| euc_jis_2004 | jisx0213, eucjis2004 | Japanese |
1029+-----------------+--------------------------------+--------------------------------+
1030| euc_jisx0213 | eucjisx0213 | Japanese |
1031+-----------------+--------------------------------+--------------------------------+
1032| euc_kr | euckr, korean, ksc5601, | Korean |
1033| | ks_c-5601, ks_c-5601-1987, | |
1034| | ksx1001, ks_x-1001 | |
1035+-----------------+--------------------------------+--------------------------------+
1036| gb2312 | chinese, csiso58gb231280, euc- | Simplified Chinese |
1037| | cn, euccn, eucgb2312-cn, | |
1038| | gb2312-1980, gb2312-80, iso- | |
1039| | ir-58 | |
1040+-----------------+--------------------------------+--------------------------------+
1041| gbk | 936, cp936, ms936 | Unified Chinese |
1042+-----------------+--------------------------------+--------------------------------+
1043| gb18030 | gb18030-2000 | Unified Chinese |
1044+-----------------+--------------------------------+--------------------------------+
1045| hz | hzgb, hz-gb, hz-gb-2312 | Simplified Chinese |
1046+-----------------+--------------------------------+--------------------------------+
1047| iso2022_jp | csiso2022jp, iso2022jp, | Japanese |
1048| | iso-2022-jp | |
1049+-----------------+--------------------------------+--------------------------------+
1050| iso2022_jp_1 | iso2022jp-1, iso-2022-jp-1 | Japanese |
1051+-----------------+--------------------------------+--------------------------------+
1052| iso2022_jp_2 | iso2022jp-2, iso-2022-jp-2 | Japanese, Korean, Simplified |
1053| | | Chinese, Western Europe, Greek |
1054+-----------------+--------------------------------+--------------------------------+
1055| iso2022_jp_2004 | iso2022jp-2004, | Japanese |
1056| | iso-2022-jp-2004 | |
1057+-----------------+--------------------------------+--------------------------------+
1058| iso2022_jp_3 | iso2022jp-3, iso-2022-jp-3 | Japanese |
1059+-----------------+--------------------------------+--------------------------------+
1060| iso2022_jp_ext | iso2022jp-ext, iso-2022-jp-ext | Japanese |
1061+-----------------+--------------------------------+--------------------------------+
1062| iso2022_kr | csiso2022kr, iso2022kr, | Korean |
1063| | iso-2022-kr | |
1064+-----------------+--------------------------------+--------------------------------+
1065| latin_1 | iso-8859-1, iso8859-1, 8859, | West Europe |
1066| | cp819, latin, latin1, L1 | |
1067+-----------------+--------------------------------+--------------------------------+
1068| iso8859_2 | iso-8859-2, latin2, L2 | Central and Eastern Europe |
1069+-----------------+--------------------------------+--------------------------------+
1070| iso8859_3 | iso-8859-3, latin3, L3 | Esperanto, Maltese |
1071+-----------------+--------------------------------+--------------------------------+
Christian Heimesc3f30c42008-02-22 16:37:40 +00001072| iso8859_4 | iso-8859-4, latin4, L4 | Baltic languages |
Georg Brandl116aa622007-08-15 14:28:22 +00001073+-----------------+--------------------------------+--------------------------------+
1074| iso8859_5 | iso-8859-5, cyrillic | Bulgarian, Byelorussian, |
1075| | | Macedonian, Russian, Serbian |
1076+-----------------+--------------------------------+--------------------------------+
1077| iso8859_6 | iso-8859-6, arabic | Arabic |
1078+-----------------+--------------------------------+--------------------------------+
1079| iso8859_7 | iso-8859-7, greek, greek8 | Greek |
1080+-----------------+--------------------------------+--------------------------------+
1081| iso8859_8 | iso-8859-8, hebrew | Hebrew |
1082+-----------------+--------------------------------+--------------------------------+
1083| iso8859_9 | iso-8859-9, latin5, L5 | Turkish |
1084+-----------------+--------------------------------+--------------------------------+
1085| iso8859_10 | iso-8859-10, latin6, L6 | Nordic languages |
1086+-----------------+--------------------------------+--------------------------------+
Georg Brandl93dc9eb2010-03-14 10:56:14 +00001087| iso8859_13 | iso-8859-13, latin7, L7 | Baltic languages |
Georg Brandl116aa622007-08-15 14:28:22 +00001088+-----------------+--------------------------------+--------------------------------+
1089| iso8859_14 | iso-8859-14, latin8, L8 | Celtic languages |
1090+-----------------+--------------------------------+--------------------------------+
Georg Brandl93dc9eb2010-03-14 10:56:14 +00001091| iso8859_15 | iso-8859-15, latin9, L9 | Western Europe |
1092+-----------------+--------------------------------+--------------------------------+
1093| iso8859_16 | iso-8859-16, latin10, L10 | South-Eastern Europe |
Georg Brandl116aa622007-08-15 14:28:22 +00001094+-----------------+--------------------------------+--------------------------------+
1095| johab | cp1361, ms1361 | Korean |
1096+-----------------+--------------------------------+--------------------------------+
1097| koi8_r | | Russian |
1098+-----------------+--------------------------------+--------------------------------+
1099| koi8_u | | Ukrainian |
1100+-----------------+--------------------------------+--------------------------------+
1101| mac_cyrillic | maccyrillic | Bulgarian, Byelorussian, |
1102| | | Macedonian, Russian, Serbian |
1103+-----------------+--------------------------------+--------------------------------+
1104| mac_greek | macgreek | Greek |
1105+-----------------+--------------------------------+--------------------------------+
1106| mac_iceland | maciceland | Icelandic |
1107+-----------------+--------------------------------+--------------------------------+
1108| mac_latin2 | maclatin2, maccentraleurope | Central and Eastern Europe |
1109+-----------------+--------------------------------+--------------------------------+
Benjamin Peterson23110e72010-08-21 02:54:44 +00001110| mac_roman | macroman, macintosh | Western Europe |
Georg Brandl116aa622007-08-15 14:28:22 +00001111+-----------------+--------------------------------+--------------------------------+
1112| mac_turkish | macturkish | Turkish |
1113+-----------------+--------------------------------+--------------------------------+
1114| ptcp154 | csptcp154, pt154, cp154, | Kazakh |
1115| | cyrillic-asian | |
1116+-----------------+--------------------------------+--------------------------------+
1117| shift_jis | csshiftjis, shiftjis, sjis, | Japanese |
1118| | s_jis | |
1119+-----------------+--------------------------------+--------------------------------+
1120| shift_jis_2004 | shiftjis2004, sjis_2004, | Japanese |
1121| | sjis2004 | |
1122+-----------------+--------------------------------+--------------------------------+
1123| shift_jisx0213 | shiftjisx0213, sjisx0213, | Japanese |
1124| | s_jisx0213 | |
1125+-----------------+--------------------------------+--------------------------------+
Walter Dörwald41980ca2007-08-16 21:55:45 +00001126| utf_32 | U32, utf32 | all languages |
1127+-----------------+--------------------------------+--------------------------------+
1128| utf_32_be | UTF-32BE | all languages |
1129+-----------------+--------------------------------+--------------------------------+
1130| utf_32_le | UTF-32LE | all languages |
1131+-----------------+--------------------------------+--------------------------------+
Georg Brandl116aa622007-08-15 14:28:22 +00001132| utf_16 | U16, utf16 | all languages |
1133+-----------------+--------------------------------+--------------------------------+
Victor Stinner53a9dd72010-12-08 22:25:45 +00001134| utf_16_be | UTF-16BE | all languages |
Georg Brandl116aa622007-08-15 14:28:22 +00001135+-----------------+--------------------------------+--------------------------------+
Victor Stinner53a9dd72010-12-08 22:25:45 +00001136| utf_16_le | UTF-16LE | all languages |
Georg Brandl116aa622007-08-15 14:28:22 +00001137+-----------------+--------------------------------+--------------------------------+
1138| utf_7 | U7, unicode-1-1-utf-7 | all languages |
1139+-----------------+--------------------------------+--------------------------------+
1140| utf_8 | U8, UTF, utf8 | all languages |
1141+-----------------+--------------------------------+--------------------------------+
1142| utf_8_sig | | all languages |
1143+-----------------+--------------------------------+--------------------------------+
1144
Georg Brandl226878c2007-08-31 10:15:37 +00001145.. XXX fix here, should be in above table
1146
Georg Brandl44ea77b2013-03-28 13:28:44 +01001147.. tabularcolumns:: |l|p{0.3\linewidth}|p{0.3\linewidth}|
1148
Georg Brandl30c78d62008-05-11 14:52:00 +00001149+--------------------+---------+---------------------------+
1150| Codec | Aliases | Purpose |
1151+====================+=========+===========================+
1152| idna | | Implements :rfc:`3490`, |
1153| | | see also |
1154| | | :mod:`encodings.idna` |
1155+--------------------+---------+---------------------------+
1156| mbcs | dbcs | Windows only: Encode |
1157| | | operand according to the |
1158| | | ANSI codepage (CP_ACP) |
1159+--------------------+---------+---------------------------+
1160| palmos | | Encoding of PalmOS 3.5 |
1161+--------------------+---------+---------------------------+
1162| punycode | | Implements :rfc:`3492` |
1163+--------------------+---------+---------------------------+
1164| raw_unicode_escape | | Produce a string that is |
1165| | | suitable as raw Unicode |
1166| | | literal in Python source |
1167| | | code |
1168+--------------------+---------+---------------------------+
1169| undefined | | Raise an exception for |
1170| | | all conversions. Can be |
1171| | | used as the system |
1172| | | encoding if no automatic |
1173| | | coercion between byte and |
1174| | | Unicode strings is |
1175| | | desired. |
1176+--------------------+---------+---------------------------+
1177| unicode_escape | | Produce a string that is |
1178| | | suitable as Unicode |
1179| | | literal in Python source |
1180| | | code |
1181+--------------------+---------+---------------------------+
1182| unicode_internal | | Return the internal |
1183| | | representation of the |
1184| | | operand |
Victor Stinner9f4b1e92011-11-10 20:56:30 +01001185| | | |
1186| | | .. deprecated:: 3.3 |
Georg Brandl30c78d62008-05-11 14:52:00 +00001187+--------------------+---------+---------------------------+
Georg Brandl116aa622007-08-15 14:28:22 +00001188
Benjamin Peterson28a4dce2010-12-12 01:33:04 +00001189The following codecs provide bytes-to-bytes mappings.
Georg Brandl02524622010-12-02 18:06:51 +00001190
Georg Brandl44ea77b2013-03-28 13:28:44 +01001191.. tabularcolumns:: |l|p{0.3\linewidth}|p{0.3\linewidth}|
1192
Georg Brandl02524622010-12-02 18:06:51 +00001193+--------------------+---------------------------+---------------------------+
1194| Codec | Aliases | Purpose |
1195+====================+===========================+===========================+
1196| base64_codec | base64, base-64 | Convert operand to MIME |
1197| | | base64 |
1198+--------------------+---------------------------+---------------------------+
1199| bz2_codec | bz2 | Compress the operand |
1200| | | using bz2 |
1201+--------------------+---------------------------+---------------------------+
1202| hex_codec | hex | Convert operand to |
1203| | | hexadecimal |
1204| | | representation, with two |
1205| | | digits per byte |
1206+--------------------+---------------------------+---------------------------+
1207| quopri_codec | quopri, quoted-printable, | Convert operand to MIME |
1208| | quotedprintable | quoted printable |
1209+--------------------+---------------------------+---------------------------+
1210| uu_codec | uu | Convert the operand using |
1211| | | uuencode |
1212+--------------------+---------------------------+---------------------------+
1213| zlib_codec | zip, zlib | Compress the operand |
1214| | | using gzip |
1215+--------------------+---------------------------+---------------------------+
1216
Benjamin Peterson28a4dce2010-12-12 01:33:04 +00001217The following codecs provide string-to-string mappings.
Georg Brandl02524622010-12-02 18:06:51 +00001218
Georg Brandl44ea77b2013-03-28 13:28:44 +01001219.. tabularcolumns:: |l|p{0.3\linewidth}|p{0.3\linewidth}|
1220
Georg Brandl02524622010-12-02 18:06:51 +00001221+--------------------+---------------------------+---------------------------+
1222| Codec | Aliases | Purpose |
1223+====================+===========================+===========================+
1224| rot_13 | rot13 | Returns the Caesar-cypher |
1225| | | encryption of the operand |
1226+--------------------+---------------------------+---------------------------+
1227
1228.. versionadded:: 3.2
1229 bytes-to-bytes and string-to-string codecs.
1230
Georg Brandl116aa622007-08-15 14:28:22 +00001231
1232:mod:`encodings.idna` --- Internationalized Domain Names in Applications
1233------------------------------------------------------------------------
1234
1235.. module:: encodings.idna
1236 :synopsis: Internationalized Domain Names implementation
1237.. moduleauthor:: Martin v. Löwis
1238
Georg Brandl116aa622007-08-15 14:28:22 +00001239This module implements :rfc:`3490` (Internationalized Domain Names in
1240Applications) and :rfc:`3492` (Nameprep: A Stringprep Profile for
1241Internationalized Domain Names (IDN)). It builds upon the ``punycode`` encoding
1242and :mod:`stringprep`.
1243
1244These RFCs together define a protocol to support non-ASCII characters in domain
1245names. A domain name containing non-ASCII characters (such as
1246``www.Alliancefrançaise.nu``) is converted into an ASCII-compatible encoding
1247(ACE, such as ``www.xn--alliancefranaise-npb.nu``). The ACE form of the domain
1248name is then used in all places where arbitrary characters are not allowed by
1249the protocol, such as DNS queries, HTTP :mailheader:`Host` fields, and so
1250on. This conversion is carried out in the application; if possible invisible to
1251the user: The application should transparently convert Unicode domain labels to
1252IDNA on the wire, and convert back ACE labels to Unicode before presenting them
1253to the user.
1254
R David Murraye0fd2f82011-04-13 14:12:18 -04001255Python supports this conversion in several ways: the ``idna`` codec performs
1256conversion between Unicode and ACE, separating an input string into labels
1257based on the separator characters defined in `section 3.1`_ (1) of :rfc:`3490`
1258and converting each label to ACE as required, and conversely separating an input
1259byte string into labels based on the ``.`` separator and converting any ACE
1260labels found into unicode. Furthermore, the :mod:`socket` module
Georg Brandl116aa622007-08-15 14:28:22 +00001261transparently converts Unicode host names to ACE, so that applications need not
1262be concerned about converting host names themselves when they pass them to the
1263socket module. On top of that, modules that have host names as function
Georg Brandl24420152008-05-26 16:32:26 +00001264parameters, such as :mod:`http.client` and :mod:`ftplib`, accept Unicode host
1265names (:mod:`http.client` then also transparently sends an IDNA hostname in the
Georg Brandl116aa622007-08-15 14:28:22 +00001266:mailheader:`Host` field if it sends that field at all).
1267
R David Murraye0fd2f82011-04-13 14:12:18 -04001268.. _section 3.1: http://tools.ietf.org/html/rfc3490#section-3.1
1269
Georg Brandl116aa622007-08-15 14:28:22 +00001270When receiving host names from the wire (such as in reverse name lookup), no
1271automatic conversion to Unicode is performed: Applications wishing to present
1272such host names to the user should decode them to Unicode.
1273
1274The module :mod:`encodings.idna` also implements the nameprep procedure, which
1275performs certain normalizations on host names, to achieve case-insensitivity of
1276international domain names, and to unify similar characters. The nameprep
1277functions can be used directly if desired.
1278
1279
1280.. function:: nameprep(label)
1281
1282 Return the nameprepped version of *label*. The implementation currently assumes
1283 query strings, so ``AllowUnassigned`` is true.
1284
1285
1286.. function:: ToASCII(label)
1287
1288 Convert a label to ASCII, as specified in :rfc:`3490`. ``UseSTD3ASCIIRules`` is
1289 assumed to be false.
1290
1291
1292.. function:: ToUnicode(label)
1293
1294 Convert a label to Unicode, as specified in :rfc:`3490`.
1295
1296
Victor Stinner554f3f02010-06-16 23:33:54 +00001297:mod:`encodings.mbcs` --- Windows ANSI codepage
1298-----------------------------------------------
1299
1300.. module:: encodings.mbcs
1301 :synopsis: Windows ANSI codepage
1302
Victor Stinner3a50e702011-10-18 21:21:00 +02001303Encode operand according to the ANSI codepage (CP_ACP).
Victor Stinner554f3f02010-06-16 23:33:54 +00001304
1305Availability: Windows only.
1306
Victor Stinner3a50e702011-10-18 21:21:00 +02001307.. versionchanged:: 3.3
1308 Support any error handler.
1309
Victor Stinner554f3f02010-06-16 23:33:54 +00001310.. versionchanged:: 3.2
1311 Before 3.2, the *errors* argument was ignored; ``'replace'`` was always used
1312 to encode, and ``'ignore'`` to decode.
1313
1314
Georg Brandl116aa622007-08-15 14:28:22 +00001315:mod:`encodings.utf_8_sig` --- UTF-8 codec with BOM signature
1316-------------------------------------------------------------
1317
1318.. module:: encodings.utf_8_sig
1319 :synopsis: UTF-8 codec with BOM signature
1320.. moduleauthor:: Walter Dörwald
1321
Georg Brandl116aa622007-08-15 14:28:22 +00001322This module implements a variant of the UTF-8 codec: On encoding a UTF-8 encoded
1323BOM will be prepended to the UTF-8 encoded bytes. For the stateful encoder this
1324is only done once (on the first write to the byte stream). For decoding an
1325optional UTF-8 encoded BOM at the start of the data will be skipped.
1326