blob: a9fae95d07b6baa18a0e4302ab1eae41ef71d167 [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.
6.. moduleauthor:: Marc-Andre Lemburg <mal@lemburg.com>
7.. sectionauthor:: Marc-Andre Lemburg <mal@lemburg.com>
8.. 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`
158 instance, which contains information about the location of the error. The error
159 handler must either raise this or a different exception or return a tuple with a
160 replacement for the unencodable part of the input and a position where encoding
161 should continue. The encoder will encode the replacement and continue encoding
162 the original input at the specified position. Negative position values will be
163 treated as being relative to the end of the input string. If the resulting
164 position is out of bound an :exc:`IndexError` will be raised.
165
166 Decoding and translating works similar, except :exc:`UnicodeDecodeError` or
167 :exc:`UnicodeTranslateError` will be passed to the handler and that the
168 replacement from the error handler will be put into the output directly.
169
170
171.. function:: lookup_error(name)
172
173 Return the error handler previously registered under the name *name*.
174
175 Raises a :exc:`LookupError` in case the handler cannot be found.
176
177
178.. function:: strict_errors(exception)
179
Georg Brandl495f7b52009-10-27 15:28:25 +0000180 Implements the ``strict`` error handling: each encoding or decoding error
181 raises a :exc:`UnicodeError`.
Georg Brandl116aa622007-08-15 14:28:22 +0000182
183
184.. function:: replace_errors(exception)
185
Georg Brandl495f7b52009-10-27 15:28:25 +0000186 Implements the ``replace`` error handling: malformed data is replaced with a
187 suitable replacement character such as ``'?'`` in bytestrings and
188 ``'\ufffd'`` in Unicode strings.
Georg Brandl116aa622007-08-15 14:28:22 +0000189
190
191.. function:: ignore_errors(exception)
192
Georg Brandl495f7b52009-10-27 15:28:25 +0000193 Implements the ``ignore`` error handling: malformed data is ignored and
194 encoding or decoding is continued without further notice.
Georg Brandl116aa622007-08-15 14:28:22 +0000195
196
Thomas Wouters89d996e2007-09-08 17:39:28 +0000197.. function:: xmlcharrefreplace_errors(exception)
Georg Brandl116aa622007-08-15 14:28:22 +0000198
Georg Brandl495f7b52009-10-27 15:28:25 +0000199 Implements the ``xmlcharrefreplace`` error handling (for encoding only): the
200 unencodable character is replaced by an appropriate XML character reference.
Georg Brandl116aa622007-08-15 14:28:22 +0000201
202
Thomas Wouters89d996e2007-09-08 17:39:28 +0000203.. function:: backslashreplace_errors(exception)
Georg Brandl116aa622007-08-15 14:28:22 +0000204
Georg Brandl495f7b52009-10-27 15:28:25 +0000205 Implements the ``backslashreplace`` error handling (for encoding only): the
206 unencodable character is replaced by a backslashed escape sequence.
Georg Brandl116aa622007-08-15 14:28:22 +0000207
208To simplify working with encoded files or stream, the module also defines these
209utility functions:
210
211
212.. function:: open(filename, mode[, encoding[, errors[, buffering]]])
213
214 Open an encoded file using the given *mode* and return a wrapped version
Christian Heimes18c66892008-02-17 13:31:39 +0000215 providing transparent encoding/decoding. The default file mode is ``'r'``
216 meaning to open the file in read mode.
Georg Brandl116aa622007-08-15 14:28:22 +0000217
218 .. note::
219
Georg Brandl30c78d62008-05-11 14:52:00 +0000220 The wrapped version's methods will accept and return strings only. Bytes
221 arguments will be rejected.
Georg Brandl116aa622007-08-15 14:28:22 +0000222
Christian Heimes18c66892008-02-17 13:31:39 +0000223 .. note::
224
225 Files are always opened in binary mode, even if no binary mode was
226 specified. This is done to avoid data loss due to encodings using 8-bit
Georg Brandl30c78d62008-05-11 14:52:00 +0000227 values. This means that no automatic conversion of ``b'\n'`` is done
Christian Heimes18c66892008-02-17 13:31:39 +0000228 on reading and writing.
229
Georg Brandl116aa622007-08-15 14:28:22 +0000230 *encoding* specifies the encoding which is to be used for the file.
231
232 *errors* may be given to define the error handling. It defaults to ``'strict'``
233 which causes a :exc:`ValueError` to be raised in case an encoding error occurs.
234
235 *buffering* has the same meaning as for the built-in :func:`open` function. It
236 defaults to line buffered.
237
238
Georg Brandl0d8f0732009-04-05 22:20:44 +0000239.. function:: EncodedFile(file, data_encoding, file_encoding=None, errors='strict')
Georg Brandl116aa622007-08-15 14:28:22 +0000240
241 Return a wrapped version of file which provides transparent encoding
242 translation.
243
Georg Brandl30c78d62008-05-11 14:52:00 +0000244 Bytes written to the wrapped file are interpreted according to the given
Georg Brandl0d8f0732009-04-05 22:20:44 +0000245 *data_encoding* and then written to the original file as bytes using the
246 *file_encoding*.
Georg Brandl116aa622007-08-15 14:28:22 +0000247
Georg Brandl0d8f0732009-04-05 22:20:44 +0000248 If *file_encoding* is not given, it defaults to *data_encoding*.
Georg Brandl116aa622007-08-15 14:28:22 +0000249
Georg Brandl0d8f0732009-04-05 22:20:44 +0000250 *errors* may be given to define the error handling. It defaults to
251 ``'strict'``, which causes :exc:`ValueError` to be raised in case an encoding
252 error occurs.
Georg Brandl116aa622007-08-15 14:28:22 +0000253
254
Georg Brandl0d8f0732009-04-05 22:20:44 +0000255.. function:: iterencode(iterator, encoding, errors='strict', **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +0000256
257 Uses an incremental encoder to iteratively encode the input provided by
Georg Brandl0d8f0732009-04-05 22:20:44 +0000258 *iterator*. This function is a :term:`generator`. *errors* (as well as any
Georg Brandl9afde1c2007-11-01 20:32:30 +0000259 other keyword argument) is passed through to the incremental encoder.
Georg Brandl116aa622007-08-15 14:28:22 +0000260
Georg Brandl116aa622007-08-15 14:28:22 +0000261
Georg Brandl0d8f0732009-04-05 22:20:44 +0000262.. function:: iterdecode(iterator, encoding, errors='strict', **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +0000263
264 Uses an incremental decoder to iteratively decode 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 decoder.
Georg Brandl116aa622007-08-15 14:28:22 +0000267
Georg Brandl0d8f0732009-04-05 22:20:44 +0000268
Georg Brandl116aa622007-08-15 14:28:22 +0000269The module also provides the following constants which are useful for reading
270and writing to platform dependent files:
271
272
273.. data:: BOM
274 BOM_BE
275 BOM_LE
276 BOM_UTF8
277 BOM_UTF16
278 BOM_UTF16_BE
279 BOM_UTF16_LE
280 BOM_UTF32
281 BOM_UTF32_BE
282 BOM_UTF32_LE
283
284 These constants define various encodings of the Unicode byte order mark (BOM)
285 used in UTF-16 and UTF-32 data streams to indicate the byte order used in the
286 stream or file and in UTF-8 as a Unicode signature. :const:`BOM_UTF16` is either
287 :const:`BOM_UTF16_BE` or :const:`BOM_UTF16_LE` depending on the platform's
288 native byte order, :const:`BOM` is an alias for :const:`BOM_UTF16`,
289 :const:`BOM_LE` for :const:`BOM_UTF16_LE` and :const:`BOM_BE` for
290 :const:`BOM_UTF16_BE`. The others represent the BOM in UTF-8 and UTF-32
291 encodings.
292
293
294.. _codec-base-classes:
295
296Codec Base Classes
297------------------
298
299The :mod:`codecs` module defines a set of base classes which define the
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000300interface and can also be used to easily write your own codecs for use in
301Python.
Georg Brandl116aa622007-08-15 14:28:22 +0000302
303Each codec has to define four interfaces to make it usable as codec in Python:
304stateless encoder, stateless decoder, stream reader and stream writer. The
305stream reader and writers typically reuse the stateless encoder/decoder to
306implement the file protocols.
307
308The :class:`Codec` class defines the interface for stateless encoders/decoders.
309
310To simplify and standardize error handling, the :meth:`encode` and
311:meth:`decode` methods may implement different error handling schemes by
312providing the *errors* string argument. The following string values are defined
313and implemented by all standard Python codecs:
314
315+-------------------------+-----------------------------------------------+
316| Value | Meaning |
317+=========================+===============================================+
318| ``'strict'`` | Raise :exc:`UnicodeError` (or a subclass); |
319| | this is the default. |
320+-------------------------+-----------------------------------------------+
321| ``'ignore'`` | Ignore the character and continue with the |
322| | next. |
323+-------------------------+-----------------------------------------------+
324| ``'replace'`` | Replace with a suitable replacement |
325| | character; Python will use the official |
326| | U+FFFD REPLACEMENT CHARACTER for the built-in |
327| | Unicode codecs on decoding and '?' on |
328| | encoding. |
329+-------------------------+-----------------------------------------------+
330| ``'xmlcharrefreplace'`` | Replace with the appropriate XML character |
331| | reference (only for encoding). |
332+-------------------------+-----------------------------------------------+
333| ``'backslashreplace'`` | Replace with backslashed escape sequences |
334| | (only for encoding). |
335+-------------------------+-----------------------------------------------+
Martin v. Löwis3d2eca02009-06-29 06:35:26 +0000336| ``'surrogateescape'`` | Replace byte with surrogate U+DCxx, as defined|
337| | in :pep:`383`. |
Martin v. Löwis011e8422009-05-05 04:43:17 +0000338+-------------------------+-----------------------------------------------+
Georg Brandl116aa622007-08-15 14:28:22 +0000339
Martin v. Löwisdb12d452009-05-02 18:52:14 +0000340In addition, the following error handlers are specific to a single codec:
341
Martin v. Löwise0a2b722009-05-10 08:08:56 +0000342+-------------------+---------+-------------------------------------------+
343| Value | Codec | Meaning |
344+===================+=========+===========================================+
345|``'surrogatepass'``| utf-8 | Allow encoding and decoding of surrogate |
346| | | codes in UTF-8. |
347+-------------------+---------+-------------------------------------------+
Martin v. Löwisdb12d452009-05-02 18:52:14 +0000348
349.. versionadded:: 3.1
Martin v. Löwis43c57782009-05-10 08:15:24 +0000350 The ``'surrogateescape'`` and ``'surrogatepass'`` error handlers.
Martin v. Löwisdb12d452009-05-02 18:52:14 +0000351
Georg Brandl116aa622007-08-15 14:28:22 +0000352The set of allowed values can be extended via :meth:`register_error`.
353
354
355.. _codec-objects:
356
357Codec Objects
358^^^^^^^^^^^^^
359
360The :class:`Codec` class defines these methods which also define the function
361interfaces of the stateless encoder and decoder:
362
363
364.. method:: Codec.encode(input[, errors])
365
366 Encodes the object *input* and returns a tuple (output object, length consumed).
Georg Brandl30c78d62008-05-11 14:52:00 +0000367 Encoding converts a string object to a bytes object using a particular
Georg Brandl116aa622007-08-15 14:28:22 +0000368 character set encoding (e.g., ``cp1252`` or ``iso-8859-1``).
369
370 *errors* defines the error handling to apply. It defaults to ``'strict'``
371 handling.
372
373 The method may not store state in the :class:`Codec` instance. Use
374 :class:`StreamCodec` for codecs which have to keep state in order to make
375 encoding/decoding efficient.
376
377 The encoder must be able to handle zero length input and return an empty object
378 of the output object type in this situation.
379
380
381.. method:: Codec.decode(input[, errors])
382
Georg Brandl30c78d62008-05-11 14:52:00 +0000383 Decodes the object *input* and returns a tuple (output object, length
384 consumed). Decoding converts a bytes object encoded using a particular
385 character set encoding to a string object.
Georg Brandl116aa622007-08-15 14:28:22 +0000386
Georg Brandl30c78d62008-05-11 14:52:00 +0000387 *input* must be a bytes object or one which provides the read-only character
388 buffer interface -- for example, buffer objects and memory mapped files.
Georg Brandl116aa622007-08-15 14:28:22 +0000389
390 *errors* defines the error handling to apply. It defaults to ``'strict'``
391 handling.
392
393 The method may not store state in the :class:`Codec` instance. Use
394 :class:`StreamCodec` for codecs which have to keep state in order to make
395 encoding/decoding efficient.
396
397 The decoder must be able to handle zero length input and return an empty object
398 of the output object type in this situation.
399
400The :class:`IncrementalEncoder` and :class:`IncrementalDecoder` classes provide
401the basic interface for incremental encoding and decoding. Encoding/decoding the
402input isn't done with one call to the stateless encoder/decoder function, but
403with multiple calls to the :meth:`encode`/:meth:`decode` method of the
404incremental encoder/decoder. The incremental encoder/decoder keeps track of the
405encoding/decoding process during method calls.
406
407The joined output of calls to the :meth:`encode`/:meth:`decode` method is the
408same as if all the single inputs were joined into one, and this input was
409encoded/decoded with the stateless encoder/decoder.
410
411
412.. _incremental-encoder-objects:
413
414IncrementalEncoder Objects
415^^^^^^^^^^^^^^^^^^^^^^^^^^
416
Georg Brandl116aa622007-08-15 14:28:22 +0000417The :class:`IncrementalEncoder` class is used for encoding an input in multiple
418steps. It defines the following methods which every incremental encoder must
419define in order to be compatible with the Python codec registry.
420
421
422.. class:: IncrementalEncoder([errors])
423
424 Constructor for an :class:`IncrementalEncoder` instance.
425
426 All incremental encoders must provide this constructor interface. They are free
427 to add additional keyword arguments, but only the ones defined here are used by
428 the Python codec registry.
429
430 The :class:`IncrementalEncoder` may implement different error handling schemes
431 by providing the *errors* keyword argument. These parameters are predefined:
432
433 * ``'strict'`` Raise :exc:`ValueError` (or a subclass); this is the default.
434
435 * ``'ignore'`` Ignore the character and continue with the next.
436
437 * ``'replace'`` Replace with a suitable replacement character
438
439 * ``'xmlcharrefreplace'`` Replace with the appropriate XML character reference
440
441 * ``'backslashreplace'`` Replace with backslashed escape sequences.
442
443 The *errors* argument will be assigned to an attribute of the same name.
444 Assigning to this attribute makes it possible to switch between different error
445 handling strategies during the lifetime of the :class:`IncrementalEncoder`
446 object.
447
448 The set of allowed values for the *errors* argument can be extended with
449 :func:`register_error`.
450
451
Benjamin Petersone41251e2008-04-25 01:59:09 +0000452 .. method:: encode(object[, final])
Georg Brandl116aa622007-08-15 14:28:22 +0000453
Benjamin Petersone41251e2008-04-25 01:59:09 +0000454 Encodes *object* (taking the current state of the encoder into account)
455 and returns the resulting encoded object. If this is the last call to
456 :meth:`encode` *final* must be true (the default is false).
Georg Brandl116aa622007-08-15 14:28:22 +0000457
458
Benjamin Petersone41251e2008-04-25 01:59:09 +0000459 .. method:: reset()
Georg Brandl116aa622007-08-15 14:28:22 +0000460
Victor Stinnere15dce32011-05-30 22:56:00 +0200461 Reset the encoder to the initial state. The output is discarded: call
462 ``.encode('', final=True)`` to reset the encoder and to get the output.
Georg Brandl116aa622007-08-15 14:28:22 +0000463
464
465.. method:: IncrementalEncoder.getstate()
466
467 Return the current state of the encoder which must be an integer. The
468 implementation should make sure that ``0`` is the most common state. (States
469 that are more complicated than integers can be converted into an integer by
470 marshaling/pickling the state and encoding the bytes of the resulting string
471 into an integer).
472
Georg Brandl116aa622007-08-15 14:28:22 +0000473
474.. method:: IncrementalEncoder.setstate(state)
475
476 Set the state of the encoder to *state*. *state* must be an encoder state
477 returned by :meth:`getstate`.
478
Georg Brandl116aa622007-08-15 14:28:22 +0000479
480.. _incremental-decoder-objects:
481
482IncrementalDecoder Objects
483^^^^^^^^^^^^^^^^^^^^^^^^^^
484
485The :class:`IncrementalDecoder` class is used for decoding an input in multiple
486steps. It defines the following methods which every incremental decoder must
487define in order to be compatible with the Python codec registry.
488
489
490.. class:: IncrementalDecoder([errors])
491
492 Constructor for an :class:`IncrementalDecoder` instance.
493
494 All incremental decoders must provide this constructor interface. They are free
495 to add additional keyword arguments, but only the ones defined here are used by
496 the Python codec registry.
497
498 The :class:`IncrementalDecoder` may implement different error handling schemes
499 by providing the *errors* keyword argument. These parameters are predefined:
500
501 * ``'strict'`` Raise :exc:`ValueError` (or a subclass); this is the default.
502
503 * ``'ignore'`` Ignore the character and continue with the next.
504
505 * ``'replace'`` Replace with a suitable replacement character.
506
507 The *errors* argument will be assigned to an attribute of the same name.
508 Assigning to this attribute makes it possible to switch between different error
Benjamin Peterson3e4f0552008-09-02 00:31:15 +0000509 handling strategies during the lifetime of the :class:`IncrementalDecoder`
Georg Brandl116aa622007-08-15 14:28:22 +0000510 object.
511
512 The set of allowed values for the *errors* argument can be extended with
513 :func:`register_error`.
514
515
Benjamin Petersone41251e2008-04-25 01:59:09 +0000516 .. method:: decode(object[, final])
Georg Brandl116aa622007-08-15 14:28:22 +0000517
Benjamin Petersone41251e2008-04-25 01:59:09 +0000518 Decodes *object* (taking the current state of the decoder into account)
519 and returns the resulting decoded object. If this is the last call to
520 :meth:`decode` *final* must be true (the default is false). If *final* is
521 true the decoder must decode the input completely and must flush all
522 buffers. If this isn't possible (e.g. because of incomplete byte sequences
523 at the end of the input) it must initiate error handling just like in the
524 stateless case (which might raise an exception).
Georg Brandl116aa622007-08-15 14:28:22 +0000525
526
Benjamin Petersone41251e2008-04-25 01:59:09 +0000527 .. method:: reset()
Georg Brandl116aa622007-08-15 14:28:22 +0000528
Benjamin Petersone41251e2008-04-25 01:59:09 +0000529 Reset the decoder to the initial state.
Georg Brandl116aa622007-08-15 14:28:22 +0000530
531
Benjamin Petersone41251e2008-04-25 01:59:09 +0000532 .. method:: getstate()
Georg Brandl116aa622007-08-15 14:28:22 +0000533
Benjamin Petersone41251e2008-04-25 01:59:09 +0000534 Return the current state of the decoder. This must be a tuple with two
535 items, the first must be the buffer containing the still undecoded
536 input. The second must be an integer and can be additional state
537 info. (The implementation should make sure that ``0`` is the most common
538 additional state info.) If this additional state info is ``0`` it must be
539 possible to set the decoder to the state which has no input buffered and
540 ``0`` as the additional state info, so that feeding the previously
541 buffered input to the decoder returns it to the previous state without
542 producing any output. (Additional state info that is more complicated than
543 integers can be converted into an integer by marshaling/pickling the info
544 and encoding the bytes of the resulting string into an integer.)
Georg Brandl116aa622007-08-15 14:28:22 +0000545
Georg Brandl116aa622007-08-15 14:28:22 +0000546
Benjamin Petersone41251e2008-04-25 01:59:09 +0000547 .. method:: setstate(state)
Georg Brandl116aa622007-08-15 14:28:22 +0000548
Benjamin Petersone41251e2008-04-25 01:59:09 +0000549 Set the state of the encoder to *state*. *state* must be a decoder state
550 returned by :meth:`getstate`.
551
Georg Brandl116aa622007-08-15 14:28:22 +0000552
Georg Brandl116aa622007-08-15 14:28:22 +0000553The :class:`StreamWriter` and :class:`StreamReader` classes provide generic
554working interfaces which can be used to implement new encoding submodules very
555easily. See :mod:`encodings.utf_8` for an example of how this is done.
556
557
558.. _stream-writer-objects:
559
560StreamWriter Objects
561^^^^^^^^^^^^^^^^^^^^
562
563The :class:`StreamWriter` class is a subclass of :class:`Codec` and defines the
564following methods which every stream writer must define in order to be
565compatible with the Python codec registry.
566
567
568.. class:: StreamWriter(stream[, errors])
569
570 Constructor for a :class:`StreamWriter` instance.
571
572 All stream writers must provide this constructor interface. They are free to add
573 additional keyword arguments, but only the ones defined here are used by the
574 Python codec registry.
575
576 *stream* must be a file-like object open for writing binary data.
577
578 The :class:`StreamWriter` may implement different error handling schemes by
579 providing the *errors* keyword argument. These parameters are predefined:
580
581 * ``'strict'`` Raise :exc:`ValueError` (or a subclass); this is the default.
582
583 * ``'ignore'`` Ignore the character and continue with the next.
584
585 * ``'replace'`` Replace with a suitable replacement character
586
587 * ``'xmlcharrefreplace'`` Replace with the appropriate XML character reference
588
589 * ``'backslashreplace'`` Replace with backslashed escape sequences.
590
591 The *errors* argument will be assigned to an attribute of the same name.
592 Assigning to this attribute makes it possible to switch between different error
593 handling strategies during the lifetime of the :class:`StreamWriter` object.
594
595 The set of allowed values for the *errors* argument can be extended with
596 :func:`register_error`.
597
598
Benjamin Petersone41251e2008-04-25 01:59:09 +0000599 .. method:: write(object)
Georg Brandl116aa622007-08-15 14:28:22 +0000600
Benjamin Petersone41251e2008-04-25 01:59:09 +0000601 Writes the object's contents encoded to the stream.
Georg Brandl116aa622007-08-15 14:28:22 +0000602
603
Benjamin Petersone41251e2008-04-25 01:59:09 +0000604 .. method:: writelines(list)
Georg Brandl116aa622007-08-15 14:28:22 +0000605
Benjamin Petersone41251e2008-04-25 01:59:09 +0000606 Writes the concatenated list of strings to the stream (possibly by reusing
607 the :meth:`write` method).
Georg Brandl116aa622007-08-15 14:28:22 +0000608
609
Benjamin Petersone41251e2008-04-25 01:59:09 +0000610 .. method:: reset()
Georg Brandl116aa622007-08-15 14:28:22 +0000611
Benjamin Petersone41251e2008-04-25 01:59:09 +0000612 Flushes and resets the codec buffers used for keeping state.
Georg Brandl116aa622007-08-15 14:28:22 +0000613
Benjamin Petersone41251e2008-04-25 01:59:09 +0000614 Calling this method should ensure that the data on the output is put into
615 a clean state that allows appending of new fresh data without having to
616 rescan the whole stream to recover state.
617
Georg Brandl116aa622007-08-15 14:28:22 +0000618
619In addition to the above methods, the :class:`StreamWriter` must also inherit
620all other methods and attributes from the underlying stream.
621
622
623.. _stream-reader-objects:
624
625StreamReader Objects
626^^^^^^^^^^^^^^^^^^^^
627
628The :class:`StreamReader` class is a subclass of :class:`Codec` and defines the
629following methods which every stream reader must define in order to be
630compatible with the Python codec registry.
631
632
633.. class:: StreamReader(stream[, errors])
634
635 Constructor for a :class:`StreamReader` instance.
636
637 All stream readers must provide this constructor interface. They are free to add
638 additional keyword arguments, but only the ones defined here are used by the
639 Python codec registry.
640
641 *stream* must be a file-like object open for reading (binary) data.
642
643 The :class:`StreamReader` may implement different error handling schemes by
644 providing the *errors* keyword argument. These parameters are defined:
645
646 * ``'strict'`` Raise :exc:`ValueError` (or a subclass); this is the default.
647
648 * ``'ignore'`` Ignore the character and continue with the next.
649
650 * ``'replace'`` Replace with a suitable replacement character.
651
652 The *errors* argument will be assigned to an attribute of the same name.
653 Assigning to this attribute makes it possible to switch between different error
654 handling strategies during the lifetime of the :class:`StreamReader` object.
655
656 The set of allowed values for the *errors* argument can be extended with
657 :func:`register_error`.
658
659
Benjamin Petersone41251e2008-04-25 01:59:09 +0000660 .. method:: read([size[, chars, [firstline]]])
Georg Brandl116aa622007-08-15 14:28:22 +0000661
Benjamin Petersone41251e2008-04-25 01:59:09 +0000662 Decodes data from the stream and returns the resulting object.
Georg Brandl116aa622007-08-15 14:28:22 +0000663
Benjamin Petersone41251e2008-04-25 01:59:09 +0000664 *chars* indicates the number of characters to read from the
665 stream. :func:`read` will never return more than *chars* characters, but
666 it might return less, if there are not enough characters available.
Georg Brandl116aa622007-08-15 14:28:22 +0000667
Benjamin Petersone41251e2008-04-25 01:59:09 +0000668 *size* indicates the approximate maximum number of bytes to read from the
669 stream for decoding purposes. The decoder can modify this setting as
670 appropriate. The default value -1 indicates to read and decode as much as
671 possible. *size* is intended to prevent having to decode huge files in
672 one step.
Georg Brandl116aa622007-08-15 14:28:22 +0000673
Benjamin Petersone41251e2008-04-25 01:59:09 +0000674 *firstline* indicates that it would be sufficient to only return the first
675 line, if there are decoding errors on later lines.
Georg Brandl116aa622007-08-15 14:28:22 +0000676
Benjamin Petersone41251e2008-04-25 01:59:09 +0000677 The method should use a greedy read strategy meaning that it should read
678 as much data as is allowed within the definition of the encoding and the
679 given size, e.g. if optional encoding endings or state markers are
680 available on the stream, these should be read too.
Georg Brandl116aa622007-08-15 14:28:22 +0000681
Georg Brandl116aa622007-08-15 14:28:22 +0000682
Benjamin Petersone41251e2008-04-25 01:59:09 +0000683 .. method:: readline([size[, keepends]])
Georg Brandl116aa622007-08-15 14:28:22 +0000684
Benjamin Petersone41251e2008-04-25 01:59:09 +0000685 Read one line from the input stream and return the decoded data.
Georg Brandl116aa622007-08-15 14:28:22 +0000686
Benjamin Petersone41251e2008-04-25 01:59:09 +0000687 *size*, if given, is passed as size argument to the stream's
688 :meth:`readline` method.
Georg Brandl116aa622007-08-15 14:28:22 +0000689
Benjamin Petersone41251e2008-04-25 01:59:09 +0000690 If *keepends* is false line-endings will be stripped from the lines
691 returned.
Georg Brandl116aa622007-08-15 14:28:22 +0000692
Georg Brandl116aa622007-08-15 14:28:22 +0000693
Benjamin Petersone41251e2008-04-25 01:59:09 +0000694 .. method:: readlines([sizehint[, keepends]])
Georg Brandl116aa622007-08-15 14:28:22 +0000695
Benjamin Petersone41251e2008-04-25 01:59:09 +0000696 Read all lines available on the input stream and return them as a list of
697 lines.
Georg Brandl116aa622007-08-15 14:28:22 +0000698
Benjamin Petersone41251e2008-04-25 01:59:09 +0000699 Line-endings are implemented using the codec's decoder method and are
700 included in the list entries if *keepends* is true.
Georg Brandl116aa622007-08-15 14:28:22 +0000701
Benjamin Petersone41251e2008-04-25 01:59:09 +0000702 *sizehint*, if given, is passed as the *size* argument to the stream's
703 :meth:`read` method.
Georg Brandl116aa622007-08-15 14:28:22 +0000704
705
Benjamin Petersone41251e2008-04-25 01:59:09 +0000706 .. method:: reset()
Georg Brandl116aa622007-08-15 14:28:22 +0000707
Benjamin Petersone41251e2008-04-25 01:59:09 +0000708 Resets the codec buffers used for keeping state.
Georg Brandl116aa622007-08-15 14:28:22 +0000709
Benjamin Petersone41251e2008-04-25 01:59:09 +0000710 Note that no stream repositioning should take place. This method is
711 primarily intended to be able to recover from decoding errors.
712
Georg Brandl116aa622007-08-15 14:28:22 +0000713
714In addition to the above methods, the :class:`StreamReader` must also inherit
715all other methods and attributes from the underlying stream.
716
717The next two base classes are included for convenience. They are not needed by
718the codec registry, but may provide useful in practice.
719
720
721.. _stream-reader-writer:
722
723StreamReaderWriter Objects
724^^^^^^^^^^^^^^^^^^^^^^^^^^
725
726The :class:`StreamReaderWriter` allows wrapping streams which work in both read
727and write modes.
728
729The design is such that one can use the factory functions returned by the
730:func:`lookup` function to construct the instance.
731
732
733.. class:: StreamReaderWriter(stream, Reader, Writer, errors)
734
735 Creates a :class:`StreamReaderWriter` instance. *stream* must be a file-like
736 object. *Reader* and *Writer* must be factory functions or classes providing the
737 :class:`StreamReader` and :class:`StreamWriter` interface resp. Error handling
738 is done in the same way as defined for the stream readers and writers.
739
740:class:`StreamReaderWriter` instances define the combined interfaces of
741:class:`StreamReader` and :class:`StreamWriter` classes. They inherit all other
742methods and attributes from the underlying stream.
743
744
745.. _stream-recoder-objects:
746
747StreamRecoder Objects
748^^^^^^^^^^^^^^^^^^^^^
749
750The :class:`StreamRecoder` provide a frontend - backend view of encoding data
751which is sometimes useful when dealing with different encoding environments.
752
753The design is such that one can use the factory functions returned by the
754:func:`lookup` function to construct the instance.
755
756
757.. class:: StreamRecoder(stream, encode, decode, Reader, Writer, errors)
758
759 Creates a :class:`StreamRecoder` instance which implements a two-way conversion:
760 *encode* and *decode* work on the frontend (the input to :meth:`read` and output
761 of :meth:`write`) while *Reader* and *Writer* work on the backend (reading and
762 writing to the stream).
763
764 You can use these objects to do transparent direct recodings from e.g. Latin-1
765 to UTF-8 and back.
766
767 *stream* must be a file-like object.
768
769 *encode*, *decode* must adhere to the :class:`Codec` interface. *Reader*,
770 *Writer* must be factory functions or classes providing objects of the
771 :class:`StreamReader` and :class:`StreamWriter` interface respectively.
772
773 *encode* and *decode* are needed for the frontend translation, *Reader* and
Georg Brandl30c78d62008-05-11 14:52:00 +0000774 *Writer* for the backend translation.
Georg Brandl116aa622007-08-15 14:28:22 +0000775
776 Error handling is done in the same way as defined for the stream readers and
777 writers.
778
Benjamin Petersone41251e2008-04-25 01:59:09 +0000779
Georg Brandl116aa622007-08-15 14:28:22 +0000780:class:`StreamRecoder` instances define the combined interfaces of
781:class:`StreamReader` and :class:`StreamWriter` classes. They inherit all other
782methods and attributes from the underlying stream.
783
784
785.. _encodings-overview:
786
787Encodings and Unicode
788---------------------
789
Ezio Melotti7a03f642011-10-25 10:30:19 +0300790Strings are stored internally as sequences of codepoints in range ``0 - 10FFFF``
791(see :pep:`393` for more details about the implementation).
792Once a string object is used outside of CPU and memory, CPU endianness
Georg Brandl116aa622007-08-15 14:28:22 +0000793and how these arrays are stored as bytes become an issue. Transforming a
Georg Brandl30c78d62008-05-11 14:52:00 +0000794string object into a sequence of bytes is called encoding and recreating the
795string object from the sequence of bytes is known as decoding. There are many
Georg Brandl116aa622007-08-15 14:28:22 +0000796different methods for how this transformation can be done (these methods are
797also called encodings). The simplest method is to map the codepoints 0-255 to
Georg Brandl30c78d62008-05-11 14:52:00 +0000798the bytes ``0x0``-``0xff``. This means that a string object that contains
Georg Brandl116aa622007-08-15 14:28:22 +0000799codepoints above ``U+00FF`` can't be encoded with this method (which is called
Georg Brandl30c78d62008-05-11 14:52:00 +0000800``'latin-1'`` or ``'iso-8859-1'``). :func:`str.encode` will raise a
Georg Brandl116aa622007-08-15 14:28:22 +0000801:exc:`UnicodeEncodeError` that looks like this: ``UnicodeEncodeError: 'latin-1'
Georg Brandl30c78d62008-05-11 14:52:00 +0000802codec can't encode character '\u1234' in position 3: ordinal not in
Georg Brandl116aa622007-08-15 14:28:22 +0000803range(256)``.
804
805There's another group of encodings (the so called charmap encodings) that choose
Georg Brandl30c78d62008-05-11 14:52:00 +0000806a different subset of all Unicode code points and how these codepoints are
Georg Brandl116aa622007-08-15 14:28:22 +0000807mapped to the bytes ``0x0``-``0xff``. To see how this is done simply open
808e.g. :file:`encodings/cp1252.py` (which is an encoding that is used primarily on
809Windows). There's a string constant with 256 characters that shows you which
810character is mapped to which byte value.
811
Ezio Melottifbb39812011-10-25 10:40:38 +0300812All of these encodings can only encode 256 of the 1114112 codepoints
Georg Brandl30c78d62008-05-11 14:52:00 +0000813defined in Unicode. A simple and straightforward way that can store each Unicode
Ezio Melottifbb39812011-10-25 10:40:38 +0300814code point, is to store each codepoint as four consecutive bytes. There are two
815possibilities: store the bytes in big endian or in little endian order. These
816two encodings are called ``UTF-32-BE`` and ``UTF-32-LE`` respectively. Their
817disadvantage is that if e.g. you use ``UTF-32-BE`` on a little endian machine you
818will always have to swap bytes on encoding and decoding. ``UTF-32`` avoids this
819problem: bytes will always be in natural endianness. When these bytes are read
Georg Brandl116aa622007-08-15 14:28:22 +0000820by a CPU with a different endianness, then bytes have to be swapped though. To
Ezio Melottifbb39812011-10-25 10:40:38 +0300821be able to detect the endianness of a ``UTF-16`` or ``UTF-32`` byte sequence,
822there's the so called BOM ("Byte Order Mark"). This is the Unicode character
823``U+FEFF``. This character can be prepended to every ``UTF-16`` or ``UTF-32``
824byte sequence. The byte swapped version of this character (``0xFFFE``) is an
825illegal character that may not appear in a Unicode text. So when the
826first character in an ``UTF-16`` or ``UTF-32`` byte sequence
Georg Brandl116aa622007-08-15 14:28:22 +0000827appears to be a ``U+FFFE`` the bytes have to be swapped on decoding.
Ezio Melottifbb39812011-10-25 10:40:38 +0300828Unfortunately the character ``U+FEFF`` had a second purpose as
829a ``ZERO WIDTH NO-BREAK SPACE``: a character that has no width and doesn't allow
Georg Brandl116aa622007-08-15 14:28:22 +0000830a word to be split. It can e.g. be used to give hints to a ligature algorithm.
831With Unicode 4.0 using ``U+FEFF`` as a ``ZERO WIDTH NO-BREAK SPACE`` has been
832deprecated (with ``U+2060`` (``WORD JOINER``) assuming this role). Nevertheless
Ezio Melottifbb39812011-10-25 10:40:38 +0300833Unicode software still must be able to handle ``U+FEFF`` in both roles: as a BOM
Georg Brandl116aa622007-08-15 14:28:22 +0000834it's a device to determine the storage layout of the encoded bytes, and vanishes
Georg Brandl30c78d62008-05-11 14:52:00 +0000835once the byte sequence has been decoded into a string; as a ``ZERO WIDTH
Georg Brandl116aa622007-08-15 14:28:22 +0000836NO-BREAK SPACE`` it's a normal character that will be decoded like any other.
837
838There's another encoding that is able to encoding the full range of Unicode
839characters: UTF-8. UTF-8 is an 8-bit encoding, which means there are no issues
840with byte order in UTF-8. Each byte in a UTF-8 byte sequence consists of two
Ezio Melottifbb39812011-10-25 10:40:38 +0300841parts: marker bits (the most significant bits) and payload bits. The marker bits
Ezio Melotti222b2082011-09-01 08:11:28 +0300842are a sequence of zero to four ``1`` bits followed by a ``0`` bit. Unicode characters are
Georg Brandl116aa622007-08-15 14:28:22 +0000843encoded like this (with x being payload bits, which when concatenated give the
844Unicode character):
845
846+-----------------------------------+----------------------------------------------+
847| Range | Encoding |
848+===================================+==============================================+
849| ``U-00000000`` ... ``U-0000007F`` | 0xxxxxxx |
850+-----------------------------------+----------------------------------------------+
851| ``U-00000080`` ... ``U-000007FF`` | 110xxxxx 10xxxxxx |
852+-----------------------------------+----------------------------------------------+
853| ``U-00000800`` ... ``U-0000FFFF`` | 1110xxxx 10xxxxxx 10xxxxxx |
854+-----------------------------------+----------------------------------------------+
Ezio Melotti222b2082011-09-01 08:11:28 +0300855| ``U-00010000`` ... ``U-0010FFFF`` | 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx |
Georg Brandl116aa622007-08-15 14:28:22 +0000856+-----------------------------------+----------------------------------------------+
857
858The least significant bit of the Unicode character is the rightmost x bit.
859
860As UTF-8 is an 8-bit encoding no BOM is required and any ``U+FEFF`` character in
Georg Brandl30c78d62008-05-11 14:52:00 +0000861the decoded string (even if it's the first character) is treated as a ``ZERO
862WIDTH NO-BREAK SPACE``.
Georg Brandl116aa622007-08-15 14:28:22 +0000863
864Without external information it's impossible to reliably determine which
Georg Brandl30c78d62008-05-11 14:52:00 +0000865encoding was used for encoding a string. Each charmap encoding can
Georg Brandl116aa622007-08-15 14:28:22 +0000866decode any random byte sequence. However that's not possible with UTF-8, as
867UTF-8 byte sequences have a structure that doesn't allow arbitrary byte
Thomas Wouters89d996e2007-09-08 17:39:28 +0000868sequences. To increase the reliability with which a UTF-8 encoding can be
Georg Brandl116aa622007-08-15 14:28:22 +0000869detected, Microsoft invented a variant of UTF-8 (that Python 2.5 calls
870``"utf-8-sig"``) for its Notepad program: Before any of the Unicode characters
871is written to the file, a UTF-8 encoded BOM (which looks like this as a byte
872sequence: ``0xef``, ``0xbb``, ``0xbf``) is written. As it's rather improbable
873that any charmap encoded file starts with these byte values (which would e.g.
874map to
875
876 | LATIN SMALL LETTER I WITH DIAERESIS
877 | RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK
878 | INVERTED QUESTION MARK
879
Ezio Melottifbb39812011-10-25 10:40:38 +0300880in iso-8859-1), this increases the probability that a ``utf-8-sig`` encoding can be
Georg Brandl116aa622007-08-15 14:28:22 +0000881correctly guessed from the byte sequence. So here the BOM is not used to be able
882to determine the byte order used for generating the byte sequence, but as a
883signature that helps in guessing the encoding. On encoding the utf-8-sig codec
884will write ``0xef``, ``0xbb``, ``0xbf`` as the first three bytes to the file. On
Ezio Melottifbb39812011-10-25 10:40:38 +0300885decoding ``utf-8-sig`` will skip those three bytes if they appear as the first
886three bytes in the file. In UTF-8, the use of the BOM is discouraged and
887should generally be avoided.
Georg Brandl116aa622007-08-15 14:28:22 +0000888
889
890.. _standard-encodings:
891
892Standard Encodings
893------------------
894
895Python comes with a number of codecs built-in, either implemented as C functions
896or with dictionaries as mapping tables. The following table lists the codecs by
897name, together with a few common aliases, and the languages for which the
898encoding is likely used. Neither the list of aliases nor the list of languages
899is meant to be exhaustive. Notice that spelling alternatives that only differ in
Georg Brandla6053b42009-09-01 08:11:14 +0000900case or use a hyphen instead of an underscore are also valid aliases; therefore,
901e.g. ``'utf-8'`` is a valid alias for the ``'utf_8'`` codec.
Georg Brandl116aa622007-08-15 14:28:22 +0000902
Alexander Belopolsky1d521462011-02-25 19:19:57 +0000903.. impl-detail::
904
905 Some common encodings can bypass the codecs lookup machinery to
906 improve performance. These optimization opportunities are only
907 recognized by CPython for a limited set of aliases: utf-8, utf8,
908 latin-1, latin1, iso-8859-1, mbcs (Windows only), ascii, utf-16,
909 and utf-32. Using alternative spellings for these encodings may
910 result in slower execution.
911
Georg Brandl116aa622007-08-15 14:28:22 +0000912Many of the character sets support the same languages. They vary in individual
913characters (e.g. whether the EURO SIGN is supported or not), and in the
914assignment of characters to code positions. For the European languages in
915particular, the following variants typically exist:
916
917* an ISO 8859 codeset
918
919* a Microsoft Windows code page, which is typically derived from a 8859 codeset,
920 but replaces control characters with additional graphic characters
921
922* an IBM EBCDIC code page
923
924* an IBM PC code page, which is ASCII compatible
925
926+-----------------+--------------------------------+--------------------------------+
927| Codec | Aliases | Languages |
928+=================+================================+================================+
929| ascii | 646, us-ascii | English |
930+-----------------+--------------------------------+--------------------------------+
931| big5 | big5-tw, csbig5 | Traditional Chinese |
932+-----------------+--------------------------------+--------------------------------+
933| big5hkscs | big5-hkscs, hkscs | Traditional Chinese |
934+-----------------+--------------------------------+--------------------------------+
935| cp037 | IBM037, IBM039 | English |
936+-----------------+--------------------------------+--------------------------------+
937| cp424 | EBCDIC-CP-HE, IBM424 | Hebrew |
938+-----------------+--------------------------------+--------------------------------+
939| cp437 | 437, IBM437 | English |
940+-----------------+--------------------------------+--------------------------------+
941| cp500 | EBCDIC-CP-BE, EBCDIC-CP-CH, | Western Europe |
942| | IBM500 | |
943+-----------------+--------------------------------+--------------------------------+
Amaury Forgeot d'Arcae6388d2009-07-15 19:21:18 +0000944| cp720 | | Arabic |
945+-----------------+--------------------------------+--------------------------------+
Georg Brandl116aa622007-08-15 14:28:22 +0000946| cp737 | | Greek |
947+-----------------+--------------------------------+--------------------------------+
948| cp775 | IBM775 | Baltic languages |
949+-----------------+--------------------------------+--------------------------------+
950| cp850 | 850, IBM850 | Western Europe |
951+-----------------+--------------------------------+--------------------------------+
952| cp852 | 852, IBM852 | Central and Eastern Europe |
953+-----------------+--------------------------------+--------------------------------+
954| cp855 | 855, IBM855 | Bulgarian, Byelorussian, |
955| | | Macedonian, Russian, Serbian |
956+-----------------+--------------------------------+--------------------------------+
957| cp856 | | Hebrew |
958+-----------------+--------------------------------+--------------------------------+
959| cp857 | 857, IBM857 | Turkish |
960+-----------------+--------------------------------+--------------------------------+
Benjamin Peterson5a6214a2010-06-27 22:41:29 +0000961| cp858 | 858, IBM858 | Western Europe |
962+-----------------+--------------------------------+--------------------------------+
Georg Brandl116aa622007-08-15 14:28:22 +0000963| cp860 | 860, IBM860 | Portuguese |
964+-----------------+--------------------------------+--------------------------------+
965| cp861 | 861, CP-IS, IBM861 | Icelandic |
966+-----------------+--------------------------------+--------------------------------+
967| cp862 | 862, IBM862 | Hebrew |
968+-----------------+--------------------------------+--------------------------------+
969| cp863 | 863, IBM863 | Canadian |
970+-----------------+--------------------------------+--------------------------------+
971| cp864 | IBM864 | Arabic |
972+-----------------+--------------------------------+--------------------------------+
973| cp865 | 865, IBM865 | Danish, Norwegian |
974+-----------------+--------------------------------+--------------------------------+
975| cp866 | 866, IBM866 | Russian |
976+-----------------+--------------------------------+--------------------------------+
977| cp869 | 869, CP-GR, IBM869 | Greek |
978+-----------------+--------------------------------+--------------------------------+
979| cp874 | | Thai |
980+-----------------+--------------------------------+--------------------------------+
981| cp875 | | Greek |
982+-----------------+--------------------------------+--------------------------------+
983| cp932 | 932, ms932, mskanji, ms-kanji | Japanese |
984+-----------------+--------------------------------+--------------------------------+
985| cp949 | 949, ms949, uhc | Korean |
986+-----------------+--------------------------------+--------------------------------+
987| cp950 | 950, ms950 | Traditional Chinese |
988+-----------------+--------------------------------+--------------------------------+
989| cp1006 | | Urdu |
990+-----------------+--------------------------------+--------------------------------+
991| cp1026 | ibm1026 | Turkish |
992+-----------------+--------------------------------+--------------------------------+
993| cp1140 | ibm1140 | Western Europe |
994+-----------------+--------------------------------+--------------------------------+
995| cp1250 | windows-1250 | Central and Eastern Europe |
996+-----------------+--------------------------------+--------------------------------+
997| cp1251 | windows-1251 | Bulgarian, Byelorussian, |
998| | | Macedonian, Russian, Serbian |
999+-----------------+--------------------------------+--------------------------------+
1000| cp1252 | windows-1252 | Western Europe |
1001+-----------------+--------------------------------+--------------------------------+
1002| cp1253 | windows-1253 | Greek |
1003+-----------------+--------------------------------+--------------------------------+
1004| cp1254 | windows-1254 | Turkish |
1005+-----------------+--------------------------------+--------------------------------+
1006| cp1255 | windows-1255 | Hebrew |
1007+-----------------+--------------------------------+--------------------------------+
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00001008| cp1256 | windows-1256 | Arabic |
Georg Brandl116aa622007-08-15 14:28:22 +00001009+-----------------+--------------------------------+--------------------------------+
1010| cp1257 | windows-1257 | Baltic languages |
1011+-----------------+--------------------------------+--------------------------------+
1012| cp1258 | windows-1258 | Vietnamese |
1013+-----------------+--------------------------------+--------------------------------+
Victor Stinner2f3ca9f2011-10-27 01:38:56 +02001014| cp65001 | | Windows only: Windows UTF-8 |
1015| | | (``CP_UTF8``) |
1016| | | |
1017| | | .. versionadded:: 3.3 |
1018+-----------------+--------------------------------+--------------------------------+
Georg Brandl116aa622007-08-15 14:28:22 +00001019| euc_jp | eucjp, ujis, u-jis | Japanese |
1020+-----------------+--------------------------------+--------------------------------+
1021| euc_jis_2004 | jisx0213, eucjis2004 | Japanese |
1022+-----------------+--------------------------------+--------------------------------+
1023| euc_jisx0213 | eucjisx0213 | Japanese |
1024+-----------------+--------------------------------+--------------------------------+
1025| euc_kr | euckr, korean, ksc5601, | Korean |
1026| | ks_c-5601, ks_c-5601-1987, | |
1027| | ksx1001, ks_x-1001 | |
1028+-----------------+--------------------------------+--------------------------------+
1029| gb2312 | chinese, csiso58gb231280, euc- | Simplified Chinese |
1030| | cn, euccn, eucgb2312-cn, | |
1031| | gb2312-1980, gb2312-80, iso- | |
1032| | ir-58 | |
1033+-----------------+--------------------------------+--------------------------------+
1034| gbk | 936, cp936, ms936 | Unified Chinese |
1035+-----------------+--------------------------------+--------------------------------+
1036| gb18030 | gb18030-2000 | Unified Chinese |
1037+-----------------+--------------------------------+--------------------------------+
1038| hz | hzgb, hz-gb, hz-gb-2312 | Simplified Chinese |
1039+-----------------+--------------------------------+--------------------------------+
1040| iso2022_jp | csiso2022jp, iso2022jp, | Japanese |
1041| | iso-2022-jp | |
1042+-----------------+--------------------------------+--------------------------------+
1043| iso2022_jp_1 | iso2022jp-1, iso-2022-jp-1 | Japanese |
1044+-----------------+--------------------------------+--------------------------------+
1045| iso2022_jp_2 | iso2022jp-2, iso-2022-jp-2 | Japanese, Korean, Simplified |
1046| | | Chinese, Western Europe, Greek |
1047+-----------------+--------------------------------+--------------------------------+
1048| iso2022_jp_2004 | iso2022jp-2004, | Japanese |
1049| | iso-2022-jp-2004 | |
1050+-----------------+--------------------------------+--------------------------------+
1051| iso2022_jp_3 | iso2022jp-3, iso-2022-jp-3 | Japanese |
1052+-----------------+--------------------------------+--------------------------------+
1053| iso2022_jp_ext | iso2022jp-ext, iso-2022-jp-ext | Japanese |
1054+-----------------+--------------------------------+--------------------------------+
1055| iso2022_kr | csiso2022kr, iso2022kr, | Korean |
1056| | iso-2022-kr | |
1057+-----------------+--------------------------------+--------------------------------+
1058| latin_1 | iso-8859-1, iso8859-1, 8859, | West Europe |
1059| | cp819, latin, latin1, L1 | |
1060+-----------------+--------------------------------+--------------------------------+
1061| iso8859_2 | iso-8859-2, latin2, L2 | Central and Eastern Europe |
1062+-----------------+--------------------------------+--------------------------------+
1063| iso8859_3 | iso-8859-3, latin3, L3 | Esperanto, Maltese |
1064+-----------------+--------------------------------+--------------------------------+
Christian Heimesc3f30c42008-02-22 16:37:40 +00001065| iso8859_4 | iso-8859-4, latin4, L4 | Baltic languages |
Georg Brandl116aa622007-08-15 14:28:22 +00001066+-----------------+--------------------------------+--------------------------------+
1067| iso8859_5 | iso-8859-5, cyrillic | Bulgarian, Byelorussian, |
1068| | | Macedonian, Russian, Serbian |
1069+-----------------+--------------------------------+--------------------------------+
1070| iso8859_6 | iso-8859-6, arabic | Arabic |
1071+-----------------+--------------------------------+--------------------------------+
1072| iso8859_7 | iso-8859-7, greek, greek8 | Greek |
1073+-----------------+--------------------------------+--------------------------------+
1074| iso8859_8 | iso-8859-8, hebrew | Hebrew |
1075+-----------------+--------------------------------+--------------------------------+
1076| iso8859_9 | iso-8859-9, latin5, L5 | Turkish |
1077+-----------------+--------------------------------+--------------------------------+
1078| iso8859_10 | iso-8859-10, latin6, L6 | Nordic languages |
1079+-----------------+--------------------------------+--------------------------------+
Georg Brandl93dc9eb2010-03-14 10:56:14 +00001080| iso8859_13 | iso-8859-13, latin7, L7 | Baltic languages |
Georg Brandl116aa622007-08-15 14:28:22 +00001081+-----------------+--------------------------------+--------------------------------+
1082| iso8859_14 | iso-8859-14, latin8, L8 | Celtic languages |
1083+-----------------+--------------------------------+--------------------------------+
Georg Brandl93dc9eb2010-03-14 10:56:14 +00001084| iso8859_15 | iso-8859-15, latin9, L9 | Western Europe |
1085+-----------------+--------------------------------+--------------------------------+
1086| iso8859_16 | iso-8859-16, latin10, L10 | South-Eastern Europe |
Georg Brandl116aa622007-08-15 14:28:22 +00001087+-----------------+--------------------------------+--------------------------------+
1088| johab | cp1361, ms1361 | Korean |
1089+-----------------+--------------------------------+--------------------------------+
1090| koi8_r | | Russian |
1091+-----------------+--------------------------------+--------------------------------+
1092| koi8_u | | Ukrainian |
1093+-----------------+--------------------------------+--------------------------------+
1094| mac_cyrillic | maccyrillic | Bulgarian, Byelorussian, |
1095| | | Macedonian, Russian, Serbian |
1096+-----------------+--------------------------------+--------------------------------+
1097| mac_greek | macgreek | Greek |
1098+-----------------+--------------------------------+--------------------------------+
1099| mac_iceland | maciceland | Icelandic |
1100+-----------------+--------------------------------+--------------------------------+
1101| mac_latin2 | maclatin2, maccentraleurope | Central and Eastern Europe |
1102+-----------------+--------------------------------+--------------------------------+
Benjamin Peterson23110e72010-08-21 02:54:44 +00001103| mac_roman | macroman, macintosh | Western Europe |
Georg Brandl116aa622007-08-15 14:28:22 +00001104+-----------------+--------------------------------+--------------------------------+
1105| mac_turkish | macturkish | Turkish |
1106+-----------------+--------------------------------+--------------------------------+
1107| ptcp154 | csptcp154, pt154, cp154, | Kazakh |
1108| | cyrillic-asian | |
1109+-----------------+--------------------------------+--------------------------------+
1110| shift_jis | csshiftjis, shiftjis, sjis, | Japanese |
1111| | s_jis | |
1112+-----------------+--------------------------------+--------------------------------+
1113| shift_jis_2004 | shiftjis2004, sjis_2004, | Japanese |
1114| | sjis2004 | |
1115+-----------------+--------------------------------+--------------------------------+
1116| shift_jisx0213 | shiftjisx0213, sjisx0213, | Japanese |
1117| | s_jisx0213 | |
1118+-----------------+--------------------------------+--------------------------------+
Walter Dörwald41980ca2007-08-16 21:55:45 +00001119| utf_32 | U32, utf32 | all languages |
1120+-----------------+--------------------------------+--------------------------------+
1121| utf_32_be | UTF-32BE | all languages |
1122+-----------------+--------------------------------+--------------------------------+
1123| utf_32_le | UTF-32LE | all languages |
1124+-----------------+--------------------------------+--------------------------------+
Georg Brandl116aa622007-08-15 14:28:22 +00001125| utf_16 | U16, utf16 | all languages |
1126+-----------------+--------------------------------+--------------------------------+
Victor Stinner53a9dd72010-12-08 22:25:45 +00001127| utf_16_be | UTF-16BE | all languages |
Georg Brandl116aa622007-08-15 14:28:22 +00001128+-----------------+--------------------------------+--------------------------------+
Victor Stinner53a9dd72010-12-08 22:25:45 +00001129| utf_16_le | UTF-16LE | all languages |
Georg Brandl116aa622007-08-15 14:28:22 +00001130+-----------------+--------------------------------+--------------------------------+
1131| utf_7 | U7, unicode-1-1-utf-7 | all languages |
1132+-----------------+--------------------------------+--------------------------------+
1133| utf_8 | U8, UTF, utf8 | all languages |
1134+-----------------+--------------------------------+--------------------------------+
1135| utf_8_sig | | all languages |
1136+-----------------+--------------------------------+--------------------------------+
1137
Georg Brandl226878c2007-08-31 10:15:37 +00001138.. XXX fix here, should be in above table
1139
Georg Brandl30c78d62008-05-11 14:52:00 +00001140+--------------------+---------+---------------------------+
1141| Codec | Aliases | Purpose |
1142+====================+=========+===========================+
1143| idna | | Implements :rfc:`3490`, |
1144| | | see also |
1145| | | :mod:`encodings.idna` |
1146+--------------------+---------+---------------------------+
1147| mbcs | dbcs | Windows only: Encode |
1148| | | operand according to the |
1149| | | ANSI codepage (CP_ACP) |
1150+--------------------+---------+---------------------------+
1151| palmos | | Encoding of PalmOS 3.5 |
1152+--------------------+---------+---------------------------+
1153| punycode | | Implements :rfc:`3492` |
1154+--------------------+---------+---------------------------+
1155| raw_unicode_escape | | Produce a string that is |
1156| | | suitable as raw Unicode |
1157| | | literal in Python source |
1158| | | code |
1159+--------------------+---------+---------------------------+
1160| undefined | | Raise an exception for |
1161| | | all conversions. Can be |
1162| | | used as the system |
1163| | | encoding if no automatic |
1164| | | coercion between byte and |
1165| | | Unicode strings is |
1166| | | desired. |
1167+--------------------+---------+---------------------------+
1168| unicode_escape | | Produce a string that is |
1169| | | suitable as Unicode |
1170| | | literal in Python source |
1171| | | code |
1172+--------------------+---------+---------------------------+
1173| unicode_internal | | Return the internal |
1174| | | representation of the |
1175| | | operand |
Victor Stinner9f4b1e92011-11-10 20:56:30 +01001176| | | |
1177| | | .. deprecated:: 3.3 |
Georg Brandl30c78d62008-05-11 14:52:00 +00001178+--------------------+---------+---------------------------+
Georg Brandl116aa622007-08-15 14:28:22 +00001179
Benjamin Peterson28a4dce2010-12-12 01:33:04 +00001180The following codecs provide bytes-to-bytes mappings.
Georg Brandl02524622010-12-02 18:06:51 +00001181
1182+--------------------+---------------------------+---------------------------+
1183| Codec | Aliases | Purpose |
1184+====================+===========================+===========================+
1185| base64_codec | base64, base-64 | Convert operand to MIME |
1186| | | base64 |
1187+--------------------+---------------------------+---------------------------+
1188| bz2_codec | bz2 | Compress the operand |
1189| | | using bz2 |
1190+--------------------+---------------------------+---------------------------+
1191| hex_codec | hex | Convert operand to |
1192| | | hexadecimal |
1193| | | representation, with two |
1194| | | digits per byte |
1195+--------------------+---------------------------+---------------------------+
1196| quopri_codec | quopri, quoted-printable, | Convert operand to MIME |
1197| | quotedprintable | quoted printable |
1198+--------------------+---------------------------+---------------------------+
1199| uu_codec | uu | Convert the operand using |
1200| | | uuencode |
1201+--------------------+---------------------------+---------------------------+
1202| zlib_codec | zip, zlib | Compress the operand |
1203| | | using gzip |
1204+--------------------+---------------------------+---------------------------+
1205
Benjamin Peterson28a4dce2010-12-12 01:33:04 +00001206The following codecs provide string-to-string mappings.
Georg Brandl02524622010-12-02 18:06:51 +00001207
1208+--------------------+---------------------------+---------------------------+
1209| Codec | Aliases | Purpose |
1210+====================+===========================+===========================+
1211| rot_13 | rot13 | Returns the Caesar-cypher |
1212| | | encryption of the operand |
1213+--------------------+---------------------------+---------------------------+
1214
1215.. versionadded:: 3.2
1216 bytes-to-bytes and string-to-string codecs.
1217
Georg Brandl116aa622007-08-15 14:28:22 +00001218
1219:mod:`encodings.idna` --- Internationalized Domain Names in Applications
1220------------------------------------------------------------------------
1221
1222.. module:: encodings.idna
1223 :synopsis: Internationalized Domain Names implementation
1224.. moduleauthor:: Martin v. Löwis
1225
Georg Brandl116aa622007-08-15 14:28:22 +00001226This module implements :rfc:`3490` (Internationalized Domain Names in
1227Applications) and :rfc:`3492` (Nameprep: A Stringprep Profile for
1228Internationalized Domain Names (IDN)). It builds upon the ``punycode`` encoding
1229and :mod:`stringprep`.
1230
1231These RFCs together define a protocol to support non-ASCII characters in domain
1232names. A domain name containing non-ASCII characters (such as
1233``www.Alliancefrançaise.nu``) is converted into an ASCII-compatible encoding
1234(ACE, such as ``www.xn--alliancefranaise-npb.nu``). The ACE form of the domain
1235name is then used in all places where arbitrary characters are not allowed by
1236the protocol, such as DNS queries, HTTP :mailheader:`Host` fields, and so
1237on. This conversion is carried out in the application; if possible invisible to
1238the user: The application should transparently convert Unicode domain labels to
1239IDNA on the wire, and convert back ACE labels to Unicode before presenting them
1240to the user.
1241
R David Murraye0fd2f82011-04-13 14:12:18 -04001242Python supports this conversion in several ways: the ``idna`` codec performs
1243conversion between Unicode and ACE, separating an input string into labels
1244based on the separator characters defined in `section 3.1`_ (1) of :rfc:`3490`
1245and converting each label to ACE as required, and conversely separating an input
1246byte string into labels based on the ``.`` separator and converting any ACE
1247labels found into unicode. Furthermore, the :mod:`socket` module
Georg Brandl116aa622007-08-15 14:28:22 +00001248transparently converts Unicode host names to ACE, so that applications need not
1249be concerned about converting host names themselves when they pass them to the
1250socket module. On top of that, modules that have host names as function
Georg Brandl24420152008-05-26 16:32:26 +00001251parameters, such as :mod:`http.client` and :mod:`ftplib`, accept Unicode host
1252names (:mod:`http.client` then also transparently sends an IDNA hostname in the
Georg Brandl116aa622007-08-15 14:28:22 +00001253:mailheader:`Host` field if it sends that field at all).
1254
R David Murraye0fd2f82011-04-13 14:12:18 -04001255.. _section 3.1: http://tools.ietf.org/html/rfc3490#section-3.1
1256
Georg Brandl116aa622007-08-15 14:28:22 +00001257When receiving host names from the wire (such as in reverse name lookup), no
1258automatic conversion to Unicode is performed: Applications wishing to present
1259such host names to the user should decode them to Unicode.
1260
1261The module :mod:`encodings.idna` also implements the nameprep procedure, which
1262performs certain normalizations on host names, to achieve case-insensitivity of
1263international domain names, and to unify similar characters. The nameprep
1264functions can be used directly if desired.
1265
1266
1267.. function:: nameprep(label)
1268
1269 Return the nameprepped version of *label*. The implementation currently assumes
1270 query strings, so ``AllowUnassigned`` is true.
1271
1272
1273.. function:: ToASCII(label)
1274
1275 Convert a label to ASCII, as specified in :rfc:`3490`. ``UseSTD3ASCIIRules`` is
1276 assumed to be false.
1277
1278
1279.. function:: ToUnicode(label)
1280
1281 Convert a label to Unicode, as specified in :rfc:`3490`.
1282
1283
Victor Stinner554f3f02010-06-16 23:33:54 +00001284:mod:`encodings.mbcs` --- Windows ANSI codepage
1285-----------------------------------------------
1286
1287.. module:: encodings.mbcs
1288 :synopsis: Windows ANSI codepage
1289
Victor Stinner3a50e702011-10-18 21:21:00 +02001290Encode operand according to the ANSI codepage (CP_ACP).
Victor Stinner554f3f02010-06-16 23:33:54 +00001291
1292Availability: Windows only.
1293
Victor Stinner3a50e702011-10-18 21:21:00 +02001294.. versionchanged:: 3.3
1295 Support any error handler.
1296
Victor Stinner554f3f02010-06-16 23:33:54 +00001297.. versionchanged:: 3.2
1298 Before 3.2, the *errors* argument was ignored; ``'replace'`` was always used
1299 to encode, and ``'ignore'`` to decode.
1300
1301
Georg Brandl116aa622007-08-15 14:28:22 +00001302:mod:`encodings.utf_8_sig` --- UTF-8 codec with BOM signature
1303-------------------------------------------------------------
1304
1305.. module:: encodings.utf_8_sig
1306 :synopsis: UTF-8 codec with BOM signature
1307.. moduleauthor:: Walter Dörwald
1308
Georg Brandl116aa622007-08-15 14:28:22 +00001309This module implements a variant of the UTF-8 codec: On encoding a UTF-8 encoded
1310BOM will be prepended to the UTF-8 encoded bytes. For the stateful encoder this
1311is only done once (on the first write to the byte stream). For decoding an
1312optional UTF-8 encoded BOM at the start of the data will be skipped.
1313