blob: 009ae26c99f345dfef9fe8546ca8f626dac1fb31 [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
Nick Coghlan6cb2b5b2013-10-14 00:22:13 +100025.. function:: encode(obj, encoding='utf-8', errors='strict')
26
27 Encodes *obj* using the codec registered for *encoding*.
28
29 *Errors* may be given to set the desired error handling scheme. The
30 default error handler is ``strict`` meaning that encoding errors raise
31 :exc:`ValueError` (or a more codec specific subclass, such as
32 :exc:`UnicodeEncodeError`). Refer to :ref:`codec-base-classes` for more
33 information on codec error handling.
34
35.. function:: decode(obj, encoding='utf-8', errors='strict')
36
37 Decodes *obj* using the codec registered for *encoding*.
38
39 *Errors* may be given to set the desired error handling scheme. The
40 default error handler is ``strict`` meaning that decoding errors raise
41 :exc:`ValueError` (or a more codec specific subclass, such as
42 :exc:`UnicodeDecodeError`). Refer to :ref:`codec-base-classes` for more
43 information on codec error handling.
Georg Brandl116aa622007-08-15 14:28:22 +000044
45.. function:: register(search_function)
46
47 Register a codec search function. Search functions are expected to take one
48 argument, the encoding name in all lower case letters, and return a
49 :class:`CodecInfo` object having the following attributes:
50
51 * ``name`` The name of the encoding;
52
Walter Dörwald62073e02008-10-23 13:21:33 +000053 * ``encode`` The stateless encoding function;
Georg Brandl116aa622007-08-15 14:28:22 +000054
Walter Dörwald62073e02008-10-23 13:21:33 +000055 * ``decode`` The stateless decoding function;
Georg Brandl116aa622007-08-15 14:28:22 +000056
57 * ``incrementalencoder`` An incremental encoder class or factory function;
58
59 * ``incrementaldecoder`` An incremental decoder class or factory function;
60
61 * ``streamwriter`` A stream writer class or factory function;
62
63 * ``streamreader`` A stream reader class or factory function.
64
65 The various functions or classes take the following arguments:
66
Walter Dörwald62073e02008-10-23 13:21:33 +000067 *encode* and *decode*: These must be functions or methods which have the same
Serhiy Storchakabfdcd432013-10-13 23:09:14 +030068 interface as the :meth:`~Codec.encode`/:meth:`~Codec.decode` methods of Codec
69 instances (see :ref:`Codec Interface <codec-objects>`). The functions/methods
70 are expected to work in a stateless mode.
Georg Brandl116aa622007-08-15 14:28:22 +000071
Benjamin Peterson3e4f0552008-09-02 00:31:15 +000072 *incrementalencoder* and *incrementaldecoder*: These have to be factory
Georg Brandl116aa622007-08-15 14:28:22 +000073 functions providing the following interface:
74
Georg Brandl495f7b52009-10-27 15:28:25 +000075 ``factory(errors='strict')``
Georg Brandl116aa622007-08-15 14:28:22 +000076
77 The factory functions must return objects providing the interfaces defined by
Benjamin Peterson3e4f0552008-09-02 00:31:15 +000078 the base classes :class:`IncrementalEncoder` and :class:`IncrementalDecoder`,
Georg Brandl116aa622007-08-15 14:28:22 +000079 respectively. Incremental codecs can maintain state.
80
81 *streamreader* and *streamwriter*: These have to be factory functions providing
82 the following interface:
83
Georg Brandl495f7b52009-10-27 15:28:25 +000084 ``factory(stream, errors='strict')``
Georg Brandl116aa622007-08-15 14:28:22 +000085
86 The factory functions must return objects providing the interfaces defined by
Georg Brandl9c2505b2013-10-06 13:17:04 +020087 the base classes :class:`StreamReader` and :class:`StreamWriter`, respectively.
Georg Brandl116aa622007-08-15 14:28:22 +000088 Stream codecs can maintain state.
89
Georg Brandl495f7b52009-10-27 15:28:25 +000090 Possible values for errors are
91
92 * ``'strict'``: raise an exception in case of an encoding error
93 * ``'replace'``: replace malformed data with a suitable replacement marker,
94 such as ``'?'`` or ``'\ufffd'``
95 * ``'ignore'``: ignore malformed data and continue without further notice
96 * ``'xmlcharrefreplace'``: replace with the appropriate XML character
97 reference (for encoding only)
98 * ``'backslashreplace'``: replace with backslashed escape sequences (for
Ezio Melottie33721e2010-02-27 13:54:27 +000099 encoding only)
Andrew Kuchlingc7b6c502013-06-16 12:58:48 -0400100 * ``'surrogateescape'``: on decoding, replace with code points in the Unicode
101 Private Use Area ranging from U+DC80 to U+DCFF. These private code
102 points will then be turned back into the same bytes when the
103 ``surrogateescape`` error handler is used when encoding the data.
104 (See :pep:`383` for more.)
Georg Brandl495f7b52009-10-27 15:28:25 +0000105
106 as well as any other error handling name defined via :func:`register_error`.
Georg Brandl116aa622007-08-15 14:28:22 +0000107
108 In case a search function cannot find a given encoding, it should return
109 ``None``.
110
111
112.. function:: lookup(encoding)
113
114 Looks up the codec info in the Python codec registry and returns a
115 :class:`CodecInfo` object as defined above.
116
117 Encodings are first looked up in the registry's cache. If not found, the list of
118 registered search functions is scanned. If no :class:`CodecInfo` object is
119 found, a :exc:`LookupError` is raised. Otherwise, the :class:`CodecInfo` object
120 is stored in the cache and returned to the caller.
121
122To simplify access to the various codecs, the module provides these additional
123functions which use :func:`lookup` for the codec lookup:
124
125
126.. function:: getencoder(encoding)
127
128 Look up the codec for the given encoding and return its encoder function.
129
130 Raises a :exc:`LookupError` in case the encoding cannot be found.
131
132
133.. function:: getdecoder(encoding)
134
135 Look up the codec for the given encoding and return its decoder function.
136
137 Raises a :exc:`LookupError` in case the encoding cannot be found.
138
139
140.. function:: getincrementalencoder(encoding)
141
142 Look up the codec for the given encoding and return its incremental encoder
143 class or factory function.
144
145 Raises a :exc:`LookupError` in case the encoding cannot be found or the codec
146 doesn't support an incremental encoder.
147
Georg Brandl116aa622007-08-15 14:28:22 +0000148
149.. function:: getincrementaldecoder(encoding)
150
151 Look up the codec for the given encoding and return its incremental decoder
152 class or factory function.
153
154 Raises a :exc:`LookupError` in case the encoding cannot be found or the codec
155 doesn't support an incremental decoder.
156
Georg Brandl116aa622007-08-15 14:28:22 +0000157
158.. function:: getreader(encoding)
159
160 Look up the codec for the given encoding and return its StreamReader class or
161 factory function.
162
163 Raises a :exc:`LookupError` in case the encoding cannot be found.
164
165
166.. function:: getwriter(encoding)
167
168 Look up the codec for the given encoding and return its StreamWriter class or
169 factory function.
170
171 Raises a :exc:`LookupError` in case the encoding cannot be found.
172
173
174.. function:: register_error(name, error_handler)
175
176 Register the error handling function *error_handler* under the name *name*.
177 *error_handler* will be called during encoding and decoding in case of an error,
178 when *name* is specified as the errors parameter.
179
180 For encoding *error_handler* will be called with a :exc:`UnicodeEncodeError`
Benjamin Peterson19603552012-12-02 11:26:10 -0500181 instance, which contains information about the location of the error. The
182 error handler must either raise this or a different exception or return a
183 tuple with a replacement for the unencodable part of the input and a position
184 where encoding should continue. The replacement may be either :class:`str` or
185 :class:`bytes`. If the replacement is bytes, the encoder will simply copy
186 them into the output buffer. If the replacement is a string, the encoder will
187 encode the replacement. Encoding continues on original input at the
188 specified position. Negative position values will be treated as being
189 relative to the end of the input string. If the resulting position is out of
190 bound an :exc:`IndexError` will be raised.
Georg Brandl116aa622007-08-15 14:28:22 +0000191
192 Decoding and translating works similar, except :exc:`UnicodeDecodeError` or
193 :exc:`UnicodeTranslateError` will be passed to the handler and that the
194 replacement from the error handler will be put into the output directly.
195
196
197.. function:: lookup_error(name)
198
199 Return the error handler previously registered under the name *name*.
200
201 Raises a :exc:`LookupError` in case the handler cannot be found.
202
203
204.. function:: strict_errors(exception)
205
Georg Brandl495f7b52009-10-27 15:28:25 +0000206 Implements the ``strict`` error handling: each encoding or decoding error
207 raises a :exc:`UnicodeError`.
Georg Brandl116aa622007-08-15 14:28:22 +0000208
209
210.. function:: replace_errors(exception)
211
Georg Brandl495f7b52009-10-27 15:28:25 +0000212 Implements the ``replace`` error handling: malformed data is replaced with a
213 suitable replacement character such as ``'?'`` in bytestrings and
214 ``'\ufffd'`` in Unicode strings.
Georg Brandl116aa622007-08-15 14:28:22 +0000215
216
217.. function:: ignore_errors(exception)
218
Georg Brandl495f7b52009-10-27 15:28:25 +0000219 Implements the ``ignore`` error handling: malformed data is ignored and
220 encoding or decoding is continued without further notice.
Georg Brandl116aa622007-08-15 14:28:22 +0000221
222
Thomas Wouters89d996e2007-09-08 17:39:28 +0000223.. function:: xmlcharrefreplace_errors(exception)
Georg Brandl116aa622007-08-15 14:28:22 +0000224
Georg Brandl495f7b52009-10-27 15:28:25 +0000225 Implements the ``xmlcharrefreplace`` error handling (for encoding only): the
226 unencodable character is replaced by an appropriate XML character reference.
Georg Brandl116aa622007-08-15 14:28:22 +0000227
228
Thomas Wouters89d996e2007-09-08 17:39:28 +0000229.. function:: backslashreplace_errors(exception)
Georg Brandl116aa622007-08-15 14:28:22 +0000230
Georg Brandl495f7b52009-10-27 15:28:25 +0000231 Implements the ``backslashreplace`` error handling (for encoding only): the
232 unencodable character is replaced by a backslashed escape sequence.
Georg Brandl116aa622007-08-15 14:28:22 +0000233
234To simplify working with encoded files or stream, the module also defines these
235utility functions:
236
237
238.. function:: open(filename, mode[, encoding[, errors[, buffering]]])
239
240 Open an encoded file using the given *mode* and return a wrapped version
Christian Heimes18c66892008-02-17 13:31:39 +0000241 providing transparent encoding/decoding. The default file mode is ``'r'``
242 meaning to open the file in read mode.
Georg Brandl116aa622007-08-15 14:28:22 +0000243
244 .. note::
245
Georg Brandl30c78d62008-05-11 14:52:00 +0000246 The wrapped version's methods will accept and return strings only. Bytes
247 arguments will be rejected.
Georg Brandl116aa622007-08-15 14:28:22 +0000248
Christian Heimes18c66892008-02-17 13:31:39 +0000249 .. note::
250
251 Files are always opened in binary mode, even if no binary mode was
252 specified. This is done to avoid data loss due to encodings using 8-bit
Georg Brandl30c78d62008-05-11 14:52:00 +0000253 values. This means that no automatic conversion of ``b'\n'`` is done
Christian Heimes18c66892008-02-17 13:31:39 +0000254 on reading and writing.
255
Georg Brandl116aa622007-08-15 14:28:22 +0000256 *encoding* specifies the encoding which is to be used for the file.
257
258 *errors* may be given to define the error handling. It defaults to ``'strict'``
259 which causes a :exc:`ValueError` to be raised in case an encoding error occurs.
260
261 *buffering* has the same meaning as for the built-in :func:`open` function. It
262 defaults to line buffered.
263
264
Georg Brandl0d8f0732009-04-05 22:20:44 +0000265.. function:: EncodedFile(file, data_encoding, file_encoding=None, errors='strict')
Georg Brandl116aa622007-08-15 14:28:22 +0000266
267 Return a wrapped version of file which provides transparent encoding
268 translation.
269
Georg Brandl30c78d62008-05-11 14:52:00 +0000270 Bytes written to the wrapped file are interpreted according to the given
Georg Brandl0d8f0732009-04-05 22:20:44 +0000271 *data_encoding* and then written to the original file as bytes using the
272 *file_encoding*.
Georg Brandl116aa622007-08-15 14:28:22 +0000273
Georg Brandl0d8f0732009-04-05 22:20:44 +0000274 If *file_encoding* is not given, it defaults to *data_encoding*.
Georg Brandl116aa622007-08-15 14:28:22 +0000275
Georg Brandl0d8f0732009-04-05 22:20:44 +0000276 *errors* may be given to define the error handling. It defaults to
277 ``'strict'``, which causes :exc:`ValueError` to be raised in case an encoding
278 error occurs.
Georg Brandl116aa622007-08-15 14:28:22 +0000279
280
Georg Brandl0d8f0732009-04-05 22:20:44 +0000281.. function:: iterencode(iterator, encoding, errors='strict', **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +0000282
283 Uses an incremental encoder to iteratively encode the input provided by
Georg Brandl0d8f0732009-04-05 22:20:44 +0000284 *iterator*. This function is a :term:`generator`. *errors* (as well as any
Georg Brandl9afde1c2007-11-01 20:32:30 +0000285 other keyword argument) is passed through to the incremental encoder.
Georg Brandl116aa622007-08-15 14:28:22 +0000286
Georg Brandl116aa622007-08-15 14:28:22 +0000287
Georg Brandl0d8f0732009-04-05 22:20:44 +0000288.. function:: iterdecode(iterator, encoding, errors='strict', **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +0000289
290 Uses an incremental decoder to iteratively decode the input provided by
Georg Brandl0d8f0732009-04-05 22:20:44 +0000291 *iterator*. This function is a :term:`generator`. *errors* (as well as any
Georg Brandl9afde1c2007-11-01 20:32:30 +0000292 other keyword argument) is passed through to the incremental decoder.
Georg Brandl116aa622007-08-15 14:28:22 +0000293
Georg Brandl0d8f0732009-04-05 22:20:44 +0000294
Georg Brandl116aa622007-08-15 14:28:22 +0000295The module also provides the following constants which are useful for reading
296and writing to platform dependent files:
297
298
299.. data:: BOM
300 BOM_BE
301 BOM_LE
302 BOM_UTF8
303 BOM_UTF16
304 BOM_UTF16_BE
305 BOM_UTF16_LE
306 BOM_UTF32
307 BOM_UTF32_BE
308 BOM_UTF32_LE
309
310 These constants define various encodings of the Unicode byte order mark (BOM)
311 used in UTF-16 and UTF-32 data streams to indicate the byte order used in the
312 stream or file and in UTF-8 as a Unicode signature. :const:`BOM_UTF16` is either
313 :const:`BOM_UTF16_BE` or :const:`BOM_UTF16_LE` depending on the platform's
314 native byte order, :const:`BOM` is an alias for :const:`BOM_UTF16`,
315 :const:`BOM_LE` for :const:`BOM_UTF16_LE` and :const:`BOM_BE` for
316 :const:`BOM_UTF16_BE`. The others represent the BOM in UTF-8 and UTF-32
317 encodings.
318
319
320.. _codec-base-classes:
321
322Codec Base Classes
323------------------
324
325The :mod:`codecs` module defines a set of base classes which define the
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000326interface and can also be used to easily write your own codecs for use in
327Python.
Georg Brandl116aa622007-08-15 14:28:22 +0000328
329Each codec has to define four interfaces to make it usable as codec in Python:
330stateless encoder, stateless decoder, stream reader and stream writer. The
331stream reader and writers typically reuse the stateless encoder/decoder to
332implement the file protocols.
333
334The :class:`Codec` class defines the interface for stateless encoders/decoders.
335
Serhiy Storchakabfdcd432013-10-13 23:09:14 +0300336To simplify and standardize error handling, the :meth:`~Codec.encode` and
337:meth:`~Codec.decode` methods may implement different error handling schemes by
Georg Brandl116aa622007-08-15 14:28:22 +0000338providing the *errors* string argument. The following string values are defined
339and implemented by all standard Python codecs:
340
Georg Brandl44ea77b2013-03-28 13:28:44 +0100341.. tabularcolumns:: |l|L|
342
Georg Brandl116aa622007-08-15 14:28:22 +0000343+-------------------------+-----------------------------------------------+
344| Value | Meaning |
345+=========================+===============================================+
346| ``'strict'`` | Raise :exc:`UnicodeError` (or a subclass); |
347| | this is the default. |
348+-------------------------+-----------------------------------------------+
349| ``'ignore'`` | Ignore the character and continue with the |
350| | next. |
351+-------------------------+-----------------------------------------------+
352| ``'replace'`` | Replace with a suitable replacement |
353| | character; Python will use the official |
354| | U+FFFD REPLACEMENT CHARACTER for the built-in |
355| | Unicode codecs on decoding and '?' on |
356| | encoding. |
357+-------------------------+-----------------------------------------------+
358| ``'xmlcharrefreplace'`` | Replace with the appropriate XML character |
359| | reference (only for encoding). |
360+-------------------------+-----------------------------------------------+
361| ``'backslashreplace'`` | Replace with backslashed escape sequences |
362| | (only for encoding). |
363+-------------------------+-----------------------------------------------+
Martin v. Löwis3d2eca02009-06-29 06:35:26 +0000364| ``'surrogateescape'`` | Replace byte with surrogate U+DCxx, as defined|
365| | in :pep:`383`. |
Martin v. Löwis011e8422009-05-05 04:43:17 +0000366+-------------------------+-----------------------------------------------+
Georg Brandl116aa622007-08-15 14:28:22 +0000367
Martin v. Löwisdb12d452009-05-02 18:52:14 +0000368In addition, the following error handlers are specific to a single codec:
369
Martin v. Löwise0a2b722009-05-10 08:08:56 +0000370+-------------------+---------+-------------------------------------------+
371| Value | Codec | Meaning |
372+===================+=========+===========================================+
373|``'surrogatepass'``| utf-8 | Allow encoding and decoding of surrogate |
374| | | codes in UTF-8. |
375+-------------------+---------+-------------------------------------------+
Martin v. Löwisdb12d452009-05-02 18:52:14 +0000376
377.. versionadded:: 3.1
Martin v. Löwis43c57782009-05-10 08:15:24 +0000378 The ``'surrogateescape'`` and ``'surrogatepass'`` error handlers.
Martin v. Löwisdb12d452009-05-02 18:52:14 +0000379
Georg Brandl116aa622007-08-15 14:28:22 +0000380The set of allowed values can be extended via :meth:`register_error`.
381
382
383.. _codec-objects:
384
385Codec Objects
386^^^^^^^^^^^^^
387
388The :class:`Codec` class defines these methods which also define the function
389interfaces of the stateless encoder and decoder:
390
391
392.. method:: Codec.encode(input[, errors])
393
394 Encodes the object *input* and returns a tuple (output object, length consumed).
Georg Brandl30c78d62008-05-11 14:52:00 +0000395 Encoding converts a string object to a bytes object using a particular
Georg Brandl116aa622007-08-15 14:28:22 +0000396 character set encoding (e.g., ``cp1252`` or ``iso-8859-1``).
397
398 *errors* defines the error handling to apply. It defaults to ``'strict'``
399 handling.
400
401 The method may not store state in the :class:`Codec` instance. Use
402 :class:`StreamCodec` for codecs which have to keep state in order to make
403 encoding/decoding efficient.
404
405 The encoder must be able to handle zero length input and return an empty object
406 of the output object type in this situation.
407
408
409.. method:: Codec.decode(input[, errors])
410
Georg Brandl30c78d62008-05-11 14:52:00 +0000411 Decodes the object *input* and returns a tuple (output object, length
412 consumed). Decoding converts a bytes object encoded using a particular
413 character set encoding to a string object.
Georg Brandl116aa622007-08-15 14:28:22 +0000414
Georg Brandl30c78d62008-05-11 14:52:00 +0000415 *input* must be a bytes object or one which provides the read-only character
416 buffer interface -- for example, buffer objects and memory mapped files.
Georg Brandl116aa622007-08-15 14:28:22 +0000417
418 *errors* defines the error handling to apply. It defaults to ``'strict'``
419 handling.
420
421 The method may not store state in the :class:`Codec` instance. Use
422 :class:`StreamCodec` for codecs which have to keep state in order to make
423 encoding/decoding efficient.
424
425 The decoder must be able to handle zero length input and return an empty object
426 of the output object type in this situation.
427
428The :class:`IncrementalEncoder` and :class:`IncrementalDecoder` classes provide
429the basic interface for incremental encoding and decoding. Encoding/decoding the
430input isn't done with one call to the stateless encoder/decoder function, but
Serhiy Storchakabfdcd432013-10-13 23:09:14 +0300431with multiple calls to the
432:meth:`~IncrementalEncoder.encode`/:meth:`~IncrementalDecoder.decode` method of
433the incremental encoder/decoder. The incremental encoder/decoder keeps track of
434the encoding/decoding process during method calls.
Georg Brandl116aa622007-08-15 14:28:22 +0000435
Serhiy Storchakabfdcd432013-10-13 23:09:14 +0300436The joined output of calls to the
437:meth:`~IncrementalEncoder.encode`/:meth:`~IncrementalDecoder.decode` method is
438the same as if all the single inputs were joined into one, and this input was
Georg Brandl116aa622007-08-15 14:28:22 +0000439encoded/decoded with the stateless encoder/decoder.
440
441
442.. _incremental-encoder-objects:
443
444IncrementalEncoder Objects
445^^^^^^^^^^^^^^^^^^^^^^^^^^
446
Georg Brandl116aa622007-08-15 14:28:22 +0000447The :class:`IncrementalEncoder` class is used for encoding an input in multiple
448steps. It defines the following methods which every incremental encoder must
449define in order to be compatible with the Python codec registry.
450
451
452.. class:: IncrementalEncoder([errors])
453
454 Constructor for an :class:`IncrementalEncoder` instance.
455
456 All incremental encoders must provide this constructor interface. They are free
457 to add additional keyword arguments, but only the ones defined here are used by
458 the Python codec registry.
459
460 The :class:`IncrementalEncoder` may implement different error handling schemes
461 by providing the *errors* keyword argument. These parameters are predefined:
462
463 * ``'strict'`` Raise :exc:`ValueError` (or a subclass); this is the default.
464
465 * ``'ignore'`` Ignore the character and continue with the next.
466
467 * ``'replace'`` Replace with a suitable replacement character
468
469 * ``'xmlcharrefreplace'`` Replace with the appropriate XML character reference
470
471 * ``'backslashreplace'`` Replace with backslashed escape sequences.
472
473 The *errors* argument will be assigned to an attribute of the same name.
474 Assigning to this attribute makes it possible to switch between different error
475 handling strategies during the lifetime of the :class:`IncrementalEncoder`
476 object.
477
478 The set of allowed values for the *errors* argument can be extended with
479 :func:`register_error`.
480
481
Benjamin Petersone41251e2008-04-25 01:59:09 +0000482 .. method:: encode(object[, final])
Georg Brandl116aa622007-08-15 14:28:22 +0000483
Benjamin Petersone41251e2008-04-25 01:59:09 +0000484 Encodes *object* (taking the current state of the encoder into account)
485 and returns the resulting encoded object. If this is the last call to
486 :meth:`encode` *final* must be true (the default is false).
Georg Brandl116aa622007-08-15 14:28:22 +0000487
488
Benjamin Petersone41251e2008-04-25 01:59:09 +0000489 .. method:: reset()
Georg Brandl116aa622007-08-15 14:28:22 +0000490
Victor Stinnere15dce32011-05-30 22:56:00 +0200491 Reset the encoder to the initial state. The output is discarded: call
492 ``.encode('', final=True)`` to reset the encoder and to get the output.
Georg Brandl116aa622007-08-15 14:28:22 +0000493
494
495.. method:: IncrementalEncoder.getstate()
496
497 Return the current state of the encoder which must be an integer. The
498 implementation should make sure that ``0`` is the most common state. (States
499 that are more complicated than integers can be converted into an integer by
500 marshaling/pickling the state and encoding the bytes of the resulting string
501 into an integer).
502
Georg Brandl116aa622007-08-15 14:28:22 +0000503
504.. method:: IncrementalEncoder.setstate(state)
505
506 Set the state of the encoder to *state*. *state* must be an encoder state
507 returned by :meth:`getstate`.
508
Georg Brandl116aa622007-08-15 14:28:22 +0000509
510.. _incremental-decoder-objects:
511
512IncrementalDecoder Objects
513^^^^^^^^^^^^^^^^^^^^^^^^^^
514
515The :class:`IncrementalDecoder` class is used for decoding an input in multiple
516steps. It defines the following methods which every incremental decoder must
517define in order to be compatible with the Python codec registry.
518
519
520.. class:: IncrementalDecoder([errors])
521
522 Constructor for an :class:`IncrementalDecoder` instance.
523
524 All incremental decoders must provide this constructor interface. They are free
525 to add additional keyword arguments, but only the ones defined here are used by
526 the Python codec registry.
527
528 The :class:`IncrementalDecoder` may implement different error handling schemes
529 by providing the *errors* keyword argument. These parameters are predefined:
530
531 * ``'strict'`` Raise :exc:`ValueError` (or a subclass); this is the default.
532
533 * ``'ignore'`` Ignore the character and continue with the next.
534
535 * ``'replace'`` Replace with a suitable replacement character.
536
537 The *errors* argument will be assigned to an attribute of the same name.
538 Assigning to this attribute makes it possible to switch between different error
Benjamin Peterson3e4f0552008-09-02 00:31:15 +0000539 handling strategies during the lifetime of the :class:`IncrementalDecoder`
Georg Brandl116aa622007-08-15 14:28:22 +0000540 object.
541
542 The set of allowed values for the *errors* argument can be extended with
543 :func:`register_error`.
544
545
Benjamin Petersone41251e2008-04-25 01:59:09 +0000546 .. method:: decode(object[, final])
Georg Brandl116aa622007-08-15 14:28:22 +0000547
Benjamin Petersone41251e2008-04-25 01:59:09 +0000548 Decodes *object* (taking the current state of the decoder into account)
549 and returns the resulting decoded object. If this is the last call to
550 :meth:`decode` *final* must be true (the default is false). If *final* is
551 true the decoder must decode the input completely and must flush all
552 buffers. If this isn't possible (e.g. because of incomplete byte sequences
553 at the end of the input) it must initiate error handling just like in the
554 stateless case (which might raise an exception).
Georg Brandl116aa622007-08-15 14:28:22 +0000555
556
Benjamin Petersone41251e2008-04-25 01:59:09 +0000557 .. method:: reset()
Georg Brandl116aa622007-08-15 14:28:22 +0000558
Benjamin Petersone41251e2008-04-25 01:59:09 +0000559 Reset the decoder to the initial state.
Georg Brandl116aa622007-08-15 14:28:22 +0000560
561
Benjamin Petersone41251e2008-04-25 01:59:09 +0000562 .. method:: getstate()
Georg Brandl116aa622007-08-15 14:28:22 +0000563
Benjamin Petersone41251e2008-04-25 01:59:09 +0000564 Return the current state of the decoder. This must be a tuple with two
565 items, the first must be the buffer containing the still undecoded
566 input. The second must be an integer and can be additional state
567 info. (The implementation should make sure that ``0`` is the most common
568 additional state info.) If this additional state info is ``0`` it must be
569 possible to set the decoder to the state which has no input buffered and
570 ``0`` as the additional state info, so that feeding the previously
571 buffered input to the decoder returns it to the previous state without
572 producing any output. (Additional state info that is more complicated than
573 integers can be converted into an integer by marshaling/pickling the info
574 and encoding the bytes of the resulting string into an integer.)
Georg Brandl116aa622007-08-15 14:28:22 +0000575
Georg Brandl116aa622007-08-15 14:28:22 +0000576
Benjamin Petersone41251e2008-04-25 01:59:09 +0000577 .. method:: setstate(state)
Georg Brandl116aa622007-08-15 14:28:22 +0000578
Benjamin Petersone41251e2008-04-25 01:59:09 +0000579 Set the state of the encoder to *state*. *state* must be a decoder state
580 returned by :meth:`getstate`.
581
Georg Brandl116aa622007-08-15 14:28:22 +0000582
Georg Brandl116aa622007-08-15 14:28:22 +0000583The :class:`StreamWriter` and :class:`StreamReader` classes provide generic
584working interfaces which can be used to implement new encoding submodules very
585easily. See :mod:`encodings.utf_8` for an example of how this is done.
586
587
588.. _stream-writer-objects:
589
590StreamWriter Objects
591^^^^^^^^^^^^^^^^^^^^
592
593The :class:`StreamWriter` class is a subclass of :class:`Codec` and defines the
594following methods which every stream writer must define in order to be
595compatible with the Python codec registry.
596
597
598.. class:: StreamWriter(stream[, errors])
599
600 Constructor for a :class:`StreamWriter` instance.
601
602 All stream writers must provide this constructor interface. They are free to add
603 additional keyword arguments, but only the ones defined here are used by the
604 Python codec registry.
605
606 *stream* must be a file-like object open for writing binary data.
607
608 The :class:`StreamWriter` may implement different error handling schemes by
609 providing the *errors* keyword argument. These parameters are predefined:
610
611 * ``'strict'`` Raise :exc:`ValueError` (or a subclass); this is the default.
612
613 * ``'ignore'`` Ignore the character and continue with the next.
614
615 * ``'replace'`` Replace with a suitable replacement character
616
617 * ``'xmlcharrefreplace'`` Replace with the appropriate XML character reference
618
619 * ``'backslashreplace'`` Replace with backslashed escape sequences.
620
621 The *errors* argument will be assigned to an attribute of the same name.
622 Assigning to this attribute makes it possible to switch between different error
623 handling strategies during the lifetime of the :class:`StreamWriter` object.
624
625 The set of allowed values for the *errors* argument can be extended with
626 :func:`register_error`.
627
628
Benjamin Petersone41251e2008-04-25 01:59:09 +0000629 .. method:: write(object)
Georg Brandl116aa622007-08-15 14:28:22 +0000630
Benjamin Petersone41251e2008-04-25 01:59:09 +0000631 Writes the object's contents encoded to the stream.
Georg Brandl116aa622007-08-15 14:28:22 +0000632
633
Benjamin Petersone41251e2008-04-25 01:59:09 +0000634 .. method:: writelines(list)
Georg Brandl116aa622007-08-15 14:28:22 +0000635
Benjamin Petersone41251e2008-04-25 01:59:09 +0000636 Writes the concatenated list of strings to the stream (possibly by reusing
637 the :meth:`write` method).
Georg Brandl116aa622007-08-15 14:28:22 +0000638
639
Benjamin Petersone41251e2008-04-25 01:59:09 +0000640 .. method:: reset()
Georg Brandl116aa622007-08-15 14:28:22 +0000641
Benjamin Petersone41251e2008-04-25 01:59:09 +0000642 Flushes and resets the codec buffers used for keeping state.
Georg Brandl116aa622007-08-15 14:28:22 +0000643
Benjamin Petersone41251e2008-04-25 01:59:09 +0000644 Calling this method should ensure that the data on the output is put into
645 a clean state that allows appending of new fresh data without having to
646 rescan the whole stream to recover state.
647
Georg Brandl116aa622007-08-15 14:28:22 +0000648
649In addition to the above methods, the :class:`StreamWriter` must also inherit
650all other methods and attributes from the underlying stream.
651
652
653.. _stream-reader-objects:
654
655StreamReader Objects
656^^^^^^^^^^^^^^^^^^^^
657
658The :class:`StreamReader` class is a subclass of :class:`Codec` and defines the
659following methods which every stream reader must define in order to be
660compatible with the Python codec registry.
661
662
663.. class:: StreamReader(stream[, errors])
664
665 Constructor for a :class:`StreamReader` instance.
666
667 All stream readers must provide this constructor interface. They are free to add
668 additional keyword arguments, but only the ones defined here are used by the
669 Python codec registry.
670
671 *stream* must be a file-like object open for reading (binary) data.
672
673 The :class:`StreamReader` may implement different error handling schemes by
674 providing the *errors* keyword argument. These parameters are defined:
675
676 * ``'strict'`` Raise :exc:`ValueError` (or a subclass); this is the default.
677
678 * ``'ignore'`` Ignore the character and continue with the next.
679
680 * ``'replace'`` Replace with a suitable replacement character.
681
682 The *errors* argument will be assigned to an attribute of the same name.
683 Assigning to this attribute makes it possible to switch between different error
684 handling strategies during the lifetime of the :class:`StreamReader` object.
685
686 The set of allowed values for the *errors* argument can be extended with
687 :func:`register_error`.
688
689
Benjamin Petersone41251e2008-04-25 01:59:09 +0000690 .. method:: read([size[, chars, [firstline]]])
Georg Brandl116aa622007-08-15 14:28:22 +0000691
Benjamin Petersone41251e2008-04-25 01:59:09 +0000692 Decodes data from the stream and returns the resulting object.
Georg Brandl116aa622007-08-15 14:28:22 +0000693
Benjamin Petersone41251e2008-04-25 01:59:09 +0000694 *chars* indicates the number of characters to read from the
695 stream. :func:`read` will never return more than *chars* characters, but
696 it might return less, if there are not enough characters available.
Georg Brandl116aa622007-08-15 14:28:22 +0000697
Benjamin Petersone41251e2008-04-25 01:59:09 +0000698 *size* indicates the approximate maximum number of bytes to read from the
699 stream for decoding purposes. The decoder can modify this setting as
700 appropriate. The default value -1 indicates to read and decode as much as
701 possible. *size* is intended to prevent having to decode huge files in
702 one step.
Georg Brandl116aa622007-08-15 14:28:22 +0000703
Benjamin Petersone41251e2008-04-25 01:59:09 +0000704 *firstline* indicates that it would be sufficient to only return the first
705 line, if there are decoding errors on later lines.
Georg Brandl116aa622007-08-15 14:28:22 +0000706
Benjamin Petersone41251e2008-04-25 01:59:09 +0000707 The method should use a greedy read strategy meaning that it should read
708 as much data as is allowed within the definition of the encoding and the
709 given size, e.g. if optional encoding endings or state markers are
710 available on the stream, these should be read too.
Georg Brandl116aa622007-08-15 14:28:22 +0000711
Georg Brandl116aa622007-08-15 14:28:22 +0000712
Benjamin Petersone41251e2008-04-25 01:59:09 +0000713 .. method:: readline([size[, keepends]])
Georg Brandl116aa622007-08-15 14:28:22 +0000714
Benjamin Petersone41251e2008-04-25 01:59:09 +0000715 Read one line from the input stream and return the decoded data.
Georg Brandl116aa622007-08-15 14:28:22 +0000716
Benjamin Petersone41251e2008-04-25 01:59:09 +0000717 *size*, if given, is passed as size argument to the stream's
Serhiy Storchakacca40ff2013-07-11 18:26:13 +0300718 :meth:`read` method.
Georg Brandl116aa622007-08-15 14:28:22 +0000719
Benjamin Petersone41251e2008-04-25 01:59:09 +0000720 If *keepends* is false line-endings will be stripped from the lines
721 returned.
Georg Brandl116aa622007-08-15 14:28:22 +0000722
Georg Brandl116aa622007-08-15 14:28:22 +0000723
Benjamin Petersone41251e2008-04-25 01:59:09 +0000724 .. method:: readlines([sizehint[, keepends]])
Georg Brandl116aa622007-08-15 14:28:22 +0000725
Benjamin Petersone41251e2008-04-25 01:59:09 +0000726 Read all lines available on the input stream and return them as a list of
727 lines.
Georg Brandl116aa622007-08-15 14:28:22 +0000728
Benjamin Petersone41251e2008-04-25 01:59:09 +0000729 Line-endings are implemented using the codec's decoder method and are
730 included in the list entries if *keepends* is true.
Georg Brandl116aa622007-08-15 14:28:22 +0000731
Benjamin Petersone41251e2008-04-25 01:59:09 +0000732 *sizehint*, if given, is passed as the *size* argument to the stream's
733 :meth:`read` method.
Georg Brandl116aa622007-08-15 14:28:22 +0000734
735
Benjamin Petersone41251e2008-04-25 01:59:09 +0000736 .. method:: reset()
Georg Brandl116aa622007-08-15 14:28:22 +0000737
Benjamin Petersone41251e2008-04-25 01:59:09 +0000738 Resets the codec buffers used for keeping state.
Georg Brandl116aa622007-08-15 14:28:22 +0000739
Benjamin Petersone41251e2008-04-25 01:59:09 +0000740 Note that no stream repositioning should take place. This method is
741 primarily intended to be able to recover from decoding errors.
742
Georg Brandl116aa622007-08-15 14:28:22 +0000743
744In addition to the above methods, the :class:`StreamReader` must also inherit
745all other methods and attributes from the underlying stream.
746
747The next two base classes are included for convenience. They are not needed by
748the codec registry, but may provide useful in practice.
749
750
751.. _stream-reader-writer:
752
753StreamReaderWriter Objects
754^^^^^^^^^^^^^^^^^^^^^^^^^^
755
756The :class:`StreamReaderWriter` allows wrapping streams which work in both read
757and write modes.
758
759The design is such that one can use the factory functions returned by the
760:func:`lookup` function to construct the instance.
761
762
763.. class:: StreamReaderWriter(stream, Reader, Writer, errors)
764
765 Creates a :class:`StreamReaderWriter` instance. *stream* must be a file-like
766 object. *Reader* and *Writer* must be factory functions or classes providing the
767 :class:`StreamReader` and :class:`StreamWriter` interface resp. Error handling
768 is done in the same way as defined for the stream readers and writers.
769
770:class:`StreamReaderWriter` instances define the combined interfaces of
771:class:`StreamReader` and :class:`StreamWriter` classes. They inherit all other
772methods and attributes from the underlying stream.
773
774
775.. _stream-recoder-objects:
776
777StreamRecoder Objects
778^^^^^^^^^^^^^^^^^^^^^
779
780The :class:`StreamRecoder` provide a frontend - backend view of encoding data
781which is sometimes useful when dealing with different encoding environments.
782
783The design is such that one can use the factory functions returned by the
784:func:`lookup` function to construct the instance.
785
786
787.. class:: StreamRecoder(stream, encode, decode, Reader, Writer, errors)
788
789 Creates a :class:`StreamRecoder` instance which implements a two-way conversion:
790 *encode* and *decode* work on the frontend (the input to :meth:`read` and output
791 of :meth:`write`) while *Reader* and *Writer* work on the backend (reading and
792 writing to the stream).
793
794 You can use these objects to do transparent direct recodings from e.g. Latin-1
795 to UTF-8 and back.
796
797 *stream* must be a file-like object.
798
799 *encode*, *decode* must adhere to the :class:`Codec` interface. *Reader*,
800 *Writer* must be factory functions or classes providing objects of the
801 :class:`StreamReader` and :class:`StreamWriter` interface respectively.
802
803 *encode* and *decode* are needed for the frontend translation, *Reader* and
Georg Brandl30c78d62008-05-11 14:52:00 +0000804 *Writer* for the backend translation.
Georg Brandl116aa622007-08-15 14:28:22 +0000805
806 Error handling is done in the same way as defined for the stream readers and
807 writers.
808
Benjamin Petersone41251e2008-04-25 01:59:09 +0000809
Georg Brandl116aa622007-08-15 14:28:22 +0000810:class:`StreamRecoder` instances define the combined interfaces of
811:class:`StreamReader` and :class:`StreamWriter` classes. They inherit all other
812methods and attributes from the underlying stream.
813
814
815.. _encodings-overview:
816
817Encodings and Unicode
818---------------------
819
Ezio Melotti7a03f642011-10-25 10:30:19 +0300820Strings are stored internally as sequences of codepoints in range ``0 - 10FFFF``
821(see :pep:`393` for more details about the implementation).
822Once a string object is used outside of CPU and memory, CPU endianness
Georg Brandl116aa622007-08-15 14:28:22 +0000823and how these arrays are stored as bytes become an issue. Transforming a
Georg Brandl30c78d62008-05-11 14:52:00 +0000824string object into a sequence of bytes is called encoding and recreating the
825string object from the sequence of bytes is known as decoding. There are many
Georg Brandl116aa622007-08-15 14:28:22 +0000826different methods for how this transformation can be done (these methods are
827also called encodings). The simplest method is to map the codepoints 0-255 to
Georg Brandl30c78d62008-05-11 14:52:00 +0000828the bytes ``0x0``-``0xff``. This means that a string object that contains
Georg Brandl116aa622007-08-15 14:28:22 +0000829codepoints above ``U+00FF`` can't be encoded with this method (which is called
Georg Brandl30c78d62008-05-11 14:52:00 +0000830``'latin-1'`` or ``'iso-8859-1'``). :func:`str.encode` will raise a
Georg Brandl116aa622007-08-15 14:28:22 +0000831:exc:`UnicodeEncodeError` that looks like this: ``UnicodeEncodeError: 'latin-1'
Georg Brandl30c78d62008-05-11 14:52:00 +0000832codec can't encode character '\u1234' in position 3: ordinal not in
Georg Brandl116aa622007-08-15 14:28:22 +0000833range(256)``.
834
835There's another group of encodings (the so called charmap encodings) that choose
Georg Brandl30c78d62008-05-11 14:52:00 +0000836a different subset of all Unicode code points and how these codepoints are
Georg Brandl116aa622007-08-15 14:28:22 +0000837mapped to the bytes ``0x0``-``0xff``. To see how this is done simply open
838e.g. :file:`encodings/cp1252.py` (which is an encoding that is used primarily on
839Windows). There's a string constant with 256 characters that shows you which
840character is mapped to which byte value.
841
Ezio Melottifbb39812011-10-25 10:40:38 +0300842All of these encodings can only encode 256 of the 1114112 codepoints
Georg Brandl30c78d62008-05-11 14:52:00 +0000843defined in Unicode. A simple and straightforward way that can store each Unicode
Ezio Melottifbb39812011-10-25 10:40:38 +0300844code point, is to store each codepoint as four consecutive bytes. There are two
845possibilities: store the bytes in big endian or in little endian order. These
846two encodings are called ``UTF-32-BE`` and ``UTF-32-LE`` respectively. Their
847disadvantage is that if e.g. you use ``UTF-32-BE`` on a little endian machine you
848will always have to swap bytes on encoding and decoding. ``UTF-32`` avoids this
849problem: bytes will always be in natural endianness. When these bytes are read
Georg Brandl116aa622007-08-15 14:28:22 +0000850by a CPU with a different endianness, then bytes have to be swapped though. To
Ezio Melottifbb39812011-10-25 10:40:38 +0300851be able to detect the endianness of a ``UTF-16`` or ``UTF-32`` byte sequence,
852there's the so called BOM ("Byte Order Mark"). This is the Unicode character
853``U+FEFF``. This character can be prepended to every ``UTF-16`` or ``UTF-32``
854byte sequence. The byte swapped version of this character (``0xFFFE``) is an
855illegal character that may not appear in a Unicode text. So when the
856first character in an ``UTF-16`` or ``UTF-32`` byte sequence
Georg Brandl116aa622007-08-15 14:28:22 +0000857appears to be a ``U+FFFE`` the bytes have to be swapped on decoding.
Ezio Melottifbb39812011-10-25 10:40:38 +0300858Unfortunately the character ``U+FEFF`` had a second purpose as
859a ``ZERO WIDTH NO-BREAK SPACE``: a character that has no width and doesn't allow
Georg Brandl116aa622007-08-15 14:28:22 +0000860a word to be split. It can e.g. be used to give hints to a ligature algorithm.
861With Unicode 4.0 using ``U+FEFF`` as a ``ZERO WIDTH NO-BREAK SPACE`` has been
862deprecated (with ``U+2060`` (``WORD JOINER``) assuming this role). Nevertheless
Ezio Melottifbb39812011-10-25 10:40:38 +0300863Unicode software still must be able to handle ``U+FEFF`` in both roles: as a BOM
Georg Brandl116aa622007-08-15 14:28:22 +0000864it's a device to determine the storage layout of the encoded bytes, and vanishes
Georg Brandl30c78d62008-05-11 14:52:00 +0000865once the byte sequence has been decoded into a string; as a ``ZERO WIDTH
Georg Brandl116aa622007-08-15 14:28:22 +0000866NO-BREAK SPACE`` it's a normal character that will be decoded like any other.
867
868There's another encoding that is able to encoding the full range of Unicode
869characters: UTF-8. UTF-8 is an 8-bit encoding, which means there are no issues
870with byte order in UTF-8. Each byte in a UTF-8 byte sequence consists of two
Ezio Melottifbb39812011-10-25 10:40:38 +0300871parts: marker bits (the most significant bits) and payload bits. The marker bits
Ezio Melotti222b2082011-09-01 08:11:28 +0300872are a sequence of zero to four ``1`` bits followed by a ``0`` bit. Unicode characters are
Georg Brandl116aa622007-08-15 14:28:22 +0000873encoded like this (with x being payload bits, which when concatenated give the
874Unicode character):
875
876+-----------------------------------+----------------------------------------------+
877| Range | Encoding |
878+===================================+==============================================+
879| ``U-00000000`` ... ``U-0000007F`` | 0xxxxxxx |
880+-----------------------------------+----------------------------------------------+
881| ``U-00000080`` ... ``U-000007FF`` | 110xxxxx 10xxxxxx |
882+-----------------------------------+----------------------------------------------+
883| ``U-00000800`` ... ``U-0000FFFF`` | 1110xxxx 10xxxxxx 10xxxxxx |
884+-----------------------------------+----------------------------------------------+
Ezio Melotti222b2082011-09-01 08:11:28 +0300885| ``U-00010000`` ... ``U-0010FFFF`` | 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx |
Georg Brandl116aa622007-08-15 14:28:22 +0000886+-----------------------------------+----------------------------------------------+
887
888The least significant bit of the Unicode character is the rightmost x bit.
889
890As UTF-8 is an 8-bit encoding no BOM is required and any ``U+FEFF`` character in
Georg Brandl30c78d62008-05-11 14:52:00 +0000891the decoded string (even if it's the first character) is treated as a ``ZERO
892WIDTH NO-BREAK SPACE``.
Georg Brandl116aa622007-08-15 14:28:22 +0000893
894Without external information it's impossible to reliably determine which
Georg Brandl30c78d62008-05-11 14:52:00 +0000895encoding was used for encoding a string. Each charmap encoding can
Georg Brandl116aa622007-08-15 14:28:22 +0000896decode any random byte sequence. However that's not possible with UTF-8, as
897UTF-8 byte sequences have a structure that doesn't allow arbitrary byte
Thomas Wouters89d996e2007-09-08 17:39:28 +0000898sequences. To increase the reliability with which a UTF-8 encoding can be
Georg Brandl116aa622007-08-15 14:28:22 +0000899detected, Microsoft invented a variant of UTF-8 (that Python 2.5 calls
900``"utf-8-sig"``) for its Notepad program: Before any of the Unicode characters
901is written to the file, a UTF-8 encoded BOM (which looks like this as a byte
902sequence: ``0xef``, ``0xbb``, ``0xbf``) is written. As it's rather improbable
903that any charmap encoded file starts with these byte values (which would e.g.
904map to
905
906 | LATIN SMALL LETTER I WITH DIAERESIS
907 | RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK
908 | INVERTED QUESTION MARK
909
Ezio Melottifbb39812011-10-25 10:40:38 +0300910in iso-8859-1), this increases the probability that a ``utf-8-sig`` encoding can be
Georg Brandl116aa622007-08-15 14:28:22 +0000911correctly guessed from the byte sequence. So here the BOM is not used to be able
912to determine the byte order used for generating the byte sequence, but as a
913signature that helps in guessing the encoding. On encoding the utf-8-sig codec
914will write ``0xef``, ``0xbb``, ``0xbf`` as the first three bytes to the file. On
Ezio Melottifbb39812011-10-25 10:40:38 +0300915decoding ``utf-8-sig`` will skip those three bytes if they appear as the first
916three bytes in the file. In UTF-8, the use of the BOM is discouraged and
917should generally be avoided.
Georg Brandl116aa622007-08-15 14:28:22 +0000918
919
920.. _standard-encodings:
921
922Standard Encodings
923------------------
924
925Python comes with a number of codecs built-in, either implemented as C functions
926or with dictionaries as mapping tables. The following table lists the codecs by
927name, together with a few common aliases, and the languages for which the
928encoding is likely used. Neither the list of aliases nor the list of languages
929is meant to be exhaustive. Notice that spelling alternatives that only differ in
Georg Brandla6053b42009-09-01 08:11:14 +0000930case or use a hyphen instead of an underscore are also valid aliases; therefore,
931e.g. ``'utf-8'`` is a valid alias for the ``'utf_8'`` codec.
Georg Brandl116aa622007-08-15 14:28:22 +0000932
Alexander Belopolsky1d521462011-02-25 19:19:57 +0000933.. impl-detail::
934
935 Some common encodings can bypass the codecs lookup machinery to
936 improve performance. These optimization opportunities are only
937 recognized by CPython for a limited set of aliases: utf-8, utf8,
938 latin-1, latin1, iso-8859-1, mbcs (Windows only), ascii, utf-16,
939 and utf-32. Using alternative spellings for these encodings may
940 result in slower execution.
941
Georg Brandl116aa622007-08-15 14:28:22 +0000942Many of the character sets support the same languages. They vary in individual
943characters (e.g. whether the EURO SIGN is supported or not), and in the
944assignment of characters to code positions. For the European languages in
945particular, the following variants typically exist:
946
947* an ISO 8859 codeset
948
949* a Microsoft Windows code page, which is typically derived from a 8859 codeset,
950 but replaces control characters with additional graphic characters
951
952* an IBM EBCDIC code page
953
954* an IBM PC code page, which is ASCII compatible
955
Georg Brandl44ea77b2013-03-28 13:28:44 +0100956.. tabularcolumns:: |l|p{0.3\linewidth}|p{0.3\linewidth}|
957
Georg Brandl116aa622007-08-15 14:28:22 +0000958+-----------------+--------------------------------+--------------------------------+
959| Codec | Aliases | Languages |
960+=================+================================+================================+
961| ascii | 646, us-ascii | English |
962+-----------------+--------------------------------+--------------------------------+
963| big5 | big5-tw, csbig5 | Traditional Chinese |
964+-----------------+--------------------------------+--------------------------------+
965| big5hkscs | big5-hkscs, hkscs | Traditional Chinese |
966+-----------------+--------------------------------+--------------------------------+
967| cp037 | IBM037, IBM039 | English |
968+-----------------+--------------------------------+--------------------------------+
969| cp424 | EBCDIC-CP-HE, IBM424 | Hebrew |
970+-----------------+--------------------------------+--------------------------------+
971| cp437 | 437, IBM437 | English |
972+-----------------+--------------------------------+--------------------------------+
973| cp500 | EBCDIC-CP-BE, EBCDIC-CP-CH, | Western Europe |
974| | IBM500 | |
975+-----------------+--------------------------------+--------------------------------+
Amaury Forgeot d'Arcae6388d2009-07-15 19:21:18 +0000976| cp720 | | Arabic |
977+-----------------+--------------------------------+--------------------------------+
Georg Brandl116aa622007-08-15 14:28:22 +0000978| cp737 | | Greek |
979+-----------------+--------------------------------+--------------------------------+
980| cp775 | IBM775 | Baltic languages |
981+-----------------+--------------------------------+--------------------------------+
982| cp850 | 850, IBM850 | Western Europe |
983+-----------------+--------------------------------+--------------------------------+
984| cp852 | 852, IBM852 | Central and Eastern Europe |
985+-----------------+--------------------------------+--------------------------------+
986| cp855 | 855, IBM855 | Bulgarian, Byelorussian, |
987| | | Macedonian, Russian, Serbian |
988+-----------------+--------------------------------+--------------------------------+
989| cp856 | | Hebrew |
990+-----------------+--------------------------------+--------------------------------+
991| cp857 | 857, IBM857 | Turkish |
992+-----------------+--------------------------------+--------------------------------+
Benjamin Peterson5a6214a2010-06-27 22:41:29 +0000993| cp858 | 858, IBM858 | Western Europe |
994+-----------------+--------------------------------+--------------------------------+
Georg Brandl116aa622007-08-15 14:28:22 +0000995| cp860 | 860, IBM860 | Portuguese |
996+-----------------+--------------------------------+--------------------------------+
997| cp861 | 861, CP-IS, IBM861 | Icelandic |
998+-----------------+--------------------------------+--------------------------------+
999| cp862 | 862, IBM862 | Hebrew |
1000+-----------------+--------------------------------+--------------------------------+
1001| cp863 | 863, IBM863 | Canadian |
1002+-----------------+--------------------------------+--------------------------------+
1003| cp864 | IBM864 | Arabic |
1004+-----------------+--------------------------------+--------------------------------+
1005| cp865 | 865, IBM865 | Danish, Norwegian |
1006+-----------------+--------------------------------+--------------------------------+
1007| cp866 | 866, IBM866 | Russian |
1008+-----------------+--------------------------------+--------------------------------+
1009| cp869 | 869, CP-GR, IBM869 | Greek |
1010+-----------------+--------------------------------+--------------------------------+
1011| cp874 | | Thai |
1012+-----------------+--------------------------------+--------------------------------+
1013| cp875 | | Greek |
1014+-----------------+--------------------------------+--------------------------------+
1015| cp932 | 932, ms932, mskanji, ms-kanji | Japanese |
1016+-----------------+--------------------------------+--------------------------------+
1017| cp949 | 949, ms949, uhc | Korean |
1018+-----------------+--------------------------------+--------------------------------+
1019| cp950 | 950, ms950 | Traditional Chinese |
1020+-----------------+--------------------------------+--------------------------------+
1021| cp1006 | | Urdu |
1022+-----------------+--------------------------------+--------------------------------+
1023| cp1026 | ibm1026 | Turkish |
1024+-----------------+--------------------------------+--------------------------------+
1025| cp1140 | ibm1140 | Western Europe |
1026+-----------------+--------------------------------+--------------------------------+
1027| cp1250 | windows-1250 | Central and Eastern Europe |
1028+-----------------+--------------------------------+--------------------------------+
1029| cp1251 | windows-1251 | Bulgarian, Byelorussian, |
1030| | | Macedonian, Russian, Serbian |
1031+-----------------+--------------------------------+--------------------------------+
1032| cp1252 | windows-1252 | Western Europe |
1033+-----------------+--------------------------------+--------------------------------+
1034| cp1253 | windows-1253 | Greek |
1035+-----------------+--------------------------------+--------------------------------+
1036| cp1254 | windows-1254 | Turkish |
1037+-----------------+--------------------------------+--------------------------------+
1038| cp1255 | windows-1255 | Hebrew |
1039+-----------------+--------------------------------+--------------------------------+
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00001040| cp1256 | windows-1256 | Arabic |
Georg Brandl116aa622007-08-15 14:28:22 +00001041+-----------------+--------------------------------+--------------------------------+
1042| cp1257 | windows-1257 | Baltic languages |
1043+-----------------+--------------------------------+--------------------------------+
1044| cp1258 | windows-1258 | Vietnamese |
1045+-----------------+--------------------------------+--------------------------------+
Victor Stinner2f3ca9f2011-10-27 01:38:56 +02001046| cp65001 | | Windows only: Windows UTF-8 |
1047| | | (``CP_UTF8``) |
1048| | | |
1049| | | .. versionadded:: 3.3 |
1050+-----------------+--------------------------------+--------------------------------+
Georg Brandl116aa622007-08-15 14:28:22 +00001051| euc_jp | eucjp, ujis, u-jis | Japanese |
1052+-----------------+--------------------------------+--------------------------------+
1053| euc_jis_2004 | jisx0213, eucjis2004 | Japanese |
1054+-----------------+--------------------------------+--------------------------------+
1055| euc_jisx0213 | eucjisx0213 | Japanese |
1056+-----------------+--------------------------------+--------------------------------+
1057| euc_kr | euckr, korean, ksc5601, | Korean |
1058| | ks_c-5601, ks_c-5601-1987, | |
1059| | ksx1001, ks_x-1001 | |
1060+-----------------+--------------------------------+--------------------------------+
1061| gb2312 | chinese, csiso58gb231280, euc- | Simplified Chinese |
1062| | cn, euccn, eucgb2312-cn, | |
1063| | gb2312-1980, gb2312-80, iso- | |
1064| | ir-58 | |
1065+-----------------+--------------------------------+--------------------------------+
1066| gbk | 936, cp936, ms936 | Unified Chinese |
1067+-----------------+--------------------------------+--------------------------------+
1068| gb18030 | gb18030-2000 | Unified Chinese |
1069+-----------------+--------------------------------+--------------------------------+
1070| hz | hzgb, hz-gb, hz-gb-2312 | Simplified Chinese |
1071+-----------------+--------------------------------+--------------------------------+
1072| iso2022_jp | csiso2022jp, iso2022jp, | Japanese |
1073| | iso-2022-jp | |
1074+-----------------+--------------------------------+--------------------------------+
1075| iso2022_jp_1 | iso2022jp-1, iso-2022-jp-1 | Japanese |
1076+-----------------+--------------------------------+--------------------------------+
1077| iso2022_jp_2 | iso2022jp-2, iso-2022-jp-2 | Japanese, Korean, Simplified |
1078| | | Chinese, Western Europe, Greek |
1079+-----------------+--------------------------------+--------------------------------+
1080| iso2022_jp_2004 | iso2022jp-2004, | Japanese |
1081| | iso-2022-jp-2004 | |
1082+-----------------+--------------------------------+--------------------------------+
1083| iso2022_jp_3 | iso2022jp-3, iso-2022-jp-3 | Japanese |
1084+-----------------+--------------------------------+--------------------------------+
1085| iso2022_jp_ext | iso2022jp-ext, iso-2022-jp-ext | Japanese |
1086+-----------------+--------------------------------+--------------------------------+
1087| iso2022_kr | csiso2022kr, iso2022kr, | Korean |
1088| | iso-2022-kr | |
1089+-----------------+--------------------------------+--------------------------------+
1090| latin_1 | iso-8859-1, iso8859-1, 8859, | West Europe |
1091| | cp819, latin, latin1, L1 | |
1092+-----------------+--------------------------------+--------------------------------+
1093| iso8859_2 | iso-8859-2, latin2, L2 | Central and Eastern Europe |
1094+-----------------+--------------------------------+--------------------------------+
1095| iso8859_3 | iso-8859-3, latin3, L3 | Esperanto, Maltese |
1096+-----------------+--------------------------------+--------------------------------+
Christian Heimesc3f30c42008-02-22 16:37:40 +00001097| iso8859_4 | iso-8859-4, latin4, L4 | Baltic languages |
Georg Brandl116aa622007-08-15 14:28:22 +00001098+-----------------+--------------------------------+--------------------------------+
1099| iso8859_5 | iso-8859-5, cyrillic | Bulgarian, Byelorussian, |
1100| | | Macedonian, Russian, Serbian |
1101+-----------------+--------------------------------+--------------------------------+
1102| iso8859_6 | iso-8859-6, arabic | Arabic |
1103+-----------------+--------------------------------+--------------------------------+
1104| iso8859_7 | iso-8859-7, greek, greek8 | Greek |
1105+-----------------+--------------------------------+--------------------------------+
1106| iso8859_8 | iso-8859-8, hebrew | Hebrew |
1107+-----------------+--------------------------------+--------------------------------+
1108| iso8859_9 | iso-8859-9, latin5, L5 | Turkish |
1109+-----------------+--------------------------------+--------------------------------+
1110| iso8859_10 | iso-8859-10, latin6, L6 | Nordic languages |
1111+-----------------+--------------------------------+--------------------------------+
Georg Brandl93dc9eb2010-03-14 10:56:14 +00001112| iso8859_13 | iso-8859-13, latin7, L7 | Baltic languages |
Georg Brandl116aa622007-08-15 14:28:22 +00001113+-----------------+--------------------------------+--------------------------------+
1114| iso8859_14 | iso-8859-14, latin8, L8 | Celtic languages |
1115+-----------------+--------------------------------+--------------------------------+
Georg Brandl93dc9eb2010-03-14 10:56:14 +00001116| iso8859_15 | iso-8859-15, latin9, L9 | Western Europe |
1117+-----------------+--------------------------------+--------------------------------+
1118| iso8859_16 | iso-8859-16, latin10, L10 | South-Eastern Europe |
Georg Brandl116aa622007-08-15 14:28:22 +00001119+-----------------+--------------------------------+--------------------------------+
1120| johab | cp1361, ms1361 | Korean |
1121+-----------------+--------------------------------+--------------------------------+
1122| koi8_r | | Russian |
1123+-----------------+--------------------------------+--------------------------------+
1124| koi8_u | | Ukrainian |
1125+-----------------+--------------------------------+--------------------------------+
1126| mac_cyrillic | maccyrillic | Bulgarian, Byelorussian, |
1127| | | Macedonian, Russian, Serbian |
1128+-----------------+--------------------------------+--------------------------------+
1129| mac_greek | macgreek | Greek |
1130+-----------------+--------------------------------+--------------------------------+
1131| mac_iceland | maciceland | Icelandic |
1132+-----------------+--------------------------------+--------------------------------+
1133| mac_latin2 | maclatin2, maccentraleurope | Central and Eastern Europe |
1134+-----------------+--------------------------------+--------------------------------+
Benjamin Peterson23110e72010-08-21 02:54:44 +00001135| mac_roman | macroman, macintosh | Western Europe |
Georg Brandl116aa622007-08-15 14:28:22 +00001136+-----------------+--------------------------------+--------------------------------+
1137| mac_turkish | macturkish | Turkish |
1138+-----------------+--------------------------------+--------------------------------+
1139| ptcp154 | csptcp154, pt154, cp154, | Kazakh |
1140| | cyrillic-asian | |
1141+-----------------+--------------------------------+--------------------------------+
1142| shift_jis | csshiftjis, shiftjis, sjis, | Japanese |
1143| | s_jis | |
1144+-----------------+--------------------------------+--------------------------------+
1145| shift_jis_2004 | shiftjis2004, sjis_2004, | Japanese |
1146| | sjis2004 | |
1147+-----------------+--------------------------------+--------------------------------+
1148| shift_jisx0213 | shiftjisx0213, sjisx0213, | Japanese |
1149| | s_jisx0213 | |
1150+-----------------+--------------------------------+--------------------------------+
Walter Dörwald41980ca2007-08-16 21:55:45 +00001151| utf_32 | U32, utf32 | all languages |
1152+-----------------+--------------------------------+--------------------------------+
1153| utf_32_be | UTF-32BE | all languages |
1154+-----------------+--------------------------------+--------------------------------+
1155| utf_32_le | UTF-32LE | all languages |
1156+-----------------+--------------------------------+--------------------------------+
Georg Brandl116aa622007-08-15 14:28:22 +00001157| utf_16 | U16, utf16 | all languages |
1158+-----------------+--------------------------------+--------------------------------+
Victor Stinner53a9dd72010-12-08 22:25:45 +00001159| utf_16_be | UTF-16BE | all languages |
Georg Brandl116aa622007-08-15 14:28:22 +00001160+-----------------+--------------------------------+--------------------------------+
Victor Stinner53a9dd72010-12-08 22:25:45 +00001161| utf_16_le | UTF-16LE | all languages |
Georg Brandl116aa622007-08-15 14:28:22 +00001162+-----------------+--------------------------------+--------------------------------+
1163| utf_7 | U7, unicode-1-1-utf-7 | all languages |
1164+-----------------+--------------------------------+--------------------------------+
1165| utf_8 | U8, UTF, utf8 | all languages |
1166+-----------------+--------------------------------+--------------------------------+
1167| utf_8_sig | | all languages |
1168+-----------------+--------------------------------+--------------------------------+
1169
Nick Coghlan650e3222013-05-23 20:24:02 +10001170Python Specific Encodings
1171-------------------------
1172
1173A number of predefined codecs are specific to Python, so their codec names have
1174no meaning outside Python. These are listed in the tables below based on the
1175expected input and output types (note that while text encodings are the most
1176common use case for codecs, the underlying codec infrastructure supports
1177arbitrary data transforms rather than just text encodings). For asymmetric
1178codecs, the stated purpose describes the encoding direction.
1179
1180The following codecs provide :class:`str` to :class:`bytes` encoding and
1181:term:`bytes-like object` to :class:`str` decoding, similar to the Unicode text
1182encodings.
Georg Brandl226878c2007-08-31 10:15:37 +00001183
Georg Brandl44ea77b2013-03-28 13:28:44 +01001184.. tabularcolumns:: |l|p{0.3\linewidth}|p{0.3\linewidth}|
1185
Georg Brandl30c78d62008-05-11 14:52:00 +00001186+--------------------+---------+---------------------------+
1187| Codec | Aliases | Purpose |
1188+====================+=========+===========================+
1189| idna | | Implements :rfc:`3490`, |
1190| | | see also |
1191| | | :mod:`encodings.idna` |
1192+--------------------+---------+---------------------------+
1193| mbcs | dbcs | Windows only: Encode |
1194| | | operand according to the |
1195| | | ANSI codepage (CP_ACP) |
1196+--------------------+---------+---------------------------+
1197| palmos | | Encoding of PalmOS 3.5 |
1198+--------------------+---------+---------------------------+
1199| punycode | | Implements :rfc:`3492` |
1200+--------------------+---------+---------------------------+
1201| raw_unicode_escape | | Produce a string that is |
1202| | | suitable as raw Unicode |
1203| | | literal in Python source |
1204| | | code |
1205+--------------------+---------+---------------------------+
1206| undefined | | Raise an exception for |
1207| | | all conversions. Can be |
1208| | | used as the system |
1209| | | encoding if no automatic |
1210| | | coercion between byte and |
1211| | | Unicode strings is |
1212| | | desired. |
1213+--------------------+---------+---------------------------+
1214| unicode_escape | | Produce a string that is |
1215| | | suitable as Unicode |
1216| | | literal in Python source |
1217| | | code |
1218+--------------------+---------+---------------------------+
1219| unicode_internal | | Return the internal |
1220| | | representation of the |
1221| | | operand |
Victor Stinner9f4b1e92011-11-10 20:56:30 +01001222| | | |
1223| | | .. deprecated:: 3.3 |
Georg Brandl30c78d62008-05-11 14:52:00 +00001224+--------------------+---------+---------------------------+
Georg Brandl116aa622007-08-15 14:28:22 +00001225
Nick Coghlan650e3222013-05-23 20:24:02 +10001226The following codecs provide :term:`bytes-like object` to :class:`bytes`
1227mappings.
1228
Georg Brandl02524622010-12-02 18:06:51 +00001229
Serhiy Storchaka9e62d352013-05-22 15:33:09 +03001230.. tabularcolumns:: |l|L|L|
Georg Brandl44ea77b2013-03-28 13:28:44 +01001231
Nick Coghlan650e3222013-05-23 20:24:02 +10001232+----------------------+---------------------------+------------------------------+
1233| Codec | Purpose | Encoder/decoder |
1234+======================+===========================+==============================+
1235| base64_codec [#b64]_ | Convert operand to MIME | :meth:`base64.b64encode`, |
1236| | base64 (the result always | :meth:`base64.b64decode` |
1237| | includes a trailing | |
1238| | ``'\n'``) | |
1239+----------------------+---------------------------+------------------------------+
1240| bz2_codec | Compress the operand | :meth:`bz2.compress`, |
1241| | using bz2 | :meth:`bz2.decompress` |
1242+----------------------+---------------------------+------------------------------+
1243| hex_codec | Convert operand to | :meth:`base64.b16encode`, |
1244| | hexadecimal | :meth:`base64.b16decode` |
1245| | representation, with two | |
1246| | digits per byte | |
1247+----------------------+---------------------------+------------------------------+
1248| quopri_codec | Convert operand to MIME | :meth:`quopri.encodestring`, |
1249| | quoted printable | :meth:`quopri.decodestring` |
1250+----------------------+---------------------------+------------------------------+
1251| uu_codec | Convert the operand using | :meth:`uu.encode`, |
1252| | uuencode | :meth:`uu.decode` |
1253+----------------------+---------------------------+------------------------------+
1254| zlib_codec | Compress the operand | :meth:`zlib.compress`, |
1255| | using gzip | :meth:`zlib.decompress` |
1256+----------------------+---------------------------+------------------------------+
Georg Brandl02524622010-12-02 18:06:51 +00001257
Nick Coghlan650e3222013-05-23 20:24:02 +10001258.. [#b64] Rather than accepting any :term:`bytes-like object`,
1259 ``'base64_codec'`` accepts only :class:`bytes` and :class:`bytearray` for
1260 encoding and only :class:`bytes`, :class:`bytearray`, and ASCII-only
1261 instances of :class:`str` for decoding
1262
1263
1264The following codecs provide :class:`str` to :class:`str` mappings.
Georg Brandl02524622010-12-02 18:06:51 +00001265
Ezio Melotti173d4102013-05-10 05:21:35 +03001266.. tabularcolumns:: |l|L|
Georg Brandl44ea77b2013-03-28 13:28:44 +01001267
Ezio Melotti173d4102013-05-10 05:21:35 +03001268+--------------------+---------------------------+
1269| Codec | Purpose |
1270+====================+===========================+
1271| rot_13 | Returns the Caesar-cypher |
1272| | encryption of the operand |
1273+--------------------+---------------------------+
Georg Brandl02524622010-12-02 18:06:51 +00001274
1275.. versionadded:: 3.2
Nick Coghlan650e3222013-05-23 20:24:02 +10001276 bytes-to-bytes and str-to-str codecs.
Georg Brandl02524622010-12-02 18:06:51 +00001277
Georg Brandl116aa622007-08-15 14:28:22 +00001278
1279:mod:`encodings.idna` --- Internationalized Domain Names in Applications
1280------------------------------------------------------------------------
1281
1282.. module:: encodings.idna
1283 :synopsis: Internationalized Domain Names implementation
1284.. moduleauthor:: Martin v. Löwis
1285
Georg Brandl116aa622007-08-15 14:28:22 +00001286This module implements :rfc:`3490` (Internationalized Domain Names in
1287Applications) and :rfc:`3492` (Nameprep: A Stringprep Profile for
1288Internationalized Domain Names (IDN)). It builds upon the ``punycode`` encoding
1289and :mod:`stringprep`.
1290
1291These RFCs together define a protocol to support non-ASCII characters in domain
1292names. A domain name containing non-ASCII characters (such as
1293``www.Alliancefrançaise.nu``) is converted into an ASCII-compatible encoding
1294(ACE, such as ``www.xn--alliancefranaise-npb.nu``). The ACE form of the domain
1295name is then used in all places where arbitrary characters are not allowed by
1296the protocol, such as DNS queries, HTTP :mailheader:`Host` fields, and so
1297on. This conversion is carried out in the application; if possible invisible to
1298the user: The application should transparently convert Unicode domain labels to
1299IDNA on the wire, and convert back ACE labels to Unicode before presenting them
1300to the user.
1301
R David Murraye0fd2f82011-04-13 14:12:18 -04001302Python supports this conversion in several ways: the ``idna`` codec performs
1303conversion between Unicode and ACE, separating an input string into labels
1304based on the separator characters defined in `section 3.1`_ (1) of :rfc:`3490`
1305and converting each label to ACE as required, and conversely separating an input
1306byte string into labels based on the ``.`` separator and converting any ACE
1307labels found into unicode. Furthermore, the :mod:`socket` module
Georg Brandl116aa622007-08-15 14:28:22 +00001308transparently converts Unicode host names to ACE, so that applications need not
1309be concerned about converting host names themselves when they pass them to the
1310socket module. On top of that, modules that have host names as function
Georg Brandl24420152008-05-26 16:32:26 +00001311parameters, such as :mod:`http.client` and :mod:`ftplib`, accept Unicode host
1312names (:mod:`http.client` then also transparently sends an IDNA hostname in the
Georg Brandl116aa622007-08-15 14:28:22 +00001313:mailheader:`Host` field if it sends that field at all).
1314
R David Murraye0fd2f82011-04-13 14:12:18 -04001315.. _section 3.1: http://tools.ietf.org/html/rfc3490#section-3.1
1316
Georg Brandl116aa622007-08-15 14:28:22 +00001317When receiving host names from the wire (such as in reverse name lookup), no
1318automatic conversion to Unicode is performed: Applications wishing to present
1319such host names to the user should decode them to Unicode.
1320
1321The module :mod:`encodings.idna` also implements the nameprep procedure, which
1322performs certain normalizations on host names, to achieve case-insensitivity of
1323international domain names, and to unify similar characters. The nameprep
1324functions can be used directly if desired.
1325
1326
1327.. function:: nameprep(label)
1328
1329 Return the nameprepped version of *label*. The implementation currently assumes
1330 query strings, so ``AllowUnassigned`` is true.
1331
1332
1333.. function:: ToASCII(label)
1334
1335 Convert a label to ASCII, as specified in :rfc:`3490`. ``UseSTD3ASCIIRules`` is
1336 assumed to be false.
1337
1338
1339.. function:: ToUnicode(label)
1340
1341 Convert a label to Unicode, as specified in :rfc:`3490`.
1342
1343
Victor Stinner554f3f02010-06-16 23:33:54 +00001344:mod:`encodings.mbcs` --- Windows ANSI codepage
1345-----------------------------------------------
1346
1347.. module:: encodings.mbcs
1348 :synopsis: Windows ANSI codepage
1349
Victor Stinner3a50e702011-10-18 21:21:00 +02001350Encode operand according to the ANSI codepage (CP_ACP).
Victor Stinner554f3f02010-06-16 23:33:54 +00001351
1352Availability: Windows only.
1353
Victor Stinner3a50e702011-10-18 21:21:00 +02001354.. versionchanged:: 3.3
1355 Support any error handler.
1356
Victor Stinner554f3f02010-06-16 23:33:54 +00001357.. versionchanged:: 3.2
1358 Before 3.2, the *errors* argument was ignored; ``'replace'`` was always used
1359 to encode, and ``'ignore'`` to decode.
1360
1361
Georg Brandl116aa622007-08-15 14:28:22 +00001362:mod:`encodings.utf_8_sig` --- UTF-8 codec with BOM signature
1363-------------------------------------------------------------
1364
1365.. module:: encodings.utf_8_sig
1366 :synopsis: UTF-8 codec with BOM signature
1367.. moduleauthor:: Walter Dörwald
1368
Georg Brandl116aa622007-08-15 14:28:22 +00001369This module implements a variant of the UTF-8 codec: On encoding a UTF-8 encoded
1370BOM will be prepended to the UTF-8 encoded bytes. For the stateful encoder this
1371is only done once (on the first write to the byte stream). For decoding an
1372optional UTF-8 encoded BOM at the start of the data will be skipped.
1373