blob: 3729dac8ae5c48c57656d8dc84cb29a2192dd2ab [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
Serhiy Storchaka58cf6072013-11-19 11:32:41 +0200368In addition, the following error handlers are specific to Unicode encoding
369schemes:
Martin v. Löwisdb12d452009-05-02 18:52:14 +0000370
Serhiy Storchaka58cf6072013-11-19 11:32:41 +0200371+-------------------+------------------------+-------------------------------------------+
372| Value | Codec | Meaning |
373+===================+========================+===========================================+
374|``'surrogatepass'``| utf-8, utf-16, utf-32, | Allow encoding and decoding of surrogate |
375| | utf-16-be, utf-16-le, | codes in all the Unicode encoding schemes.|
376| | utf-32-be, utf-32-le | |
377+-------------------+------------------------+-------------------------------------------+
Martin v. Löwisdb12d452009-05-02 18:52:14 +0000378
379.. versionadded:: 3.1
Martin v. Löwis43c57782009-05-10 08:15:24 +0000380 The ``'surrogateescape'`` and ``'surrogatepass'`` error handlers.
Martin v. Löwisdb12d452009-05-02 18:52:14 +0000381
Serhiy Storchaka58cf6072013-11-19 11:32:41 +0200382.. versionchanged:: 3.4
383 The ``'surrogatepass'`` error handlers now works with utf-16\* and utf-32\* codecs.
384
Georg Brandl116aa622007-08-15 14:28:22 +0000385The set of allowed values can be extended via :meth:`register_error`.
386
387
388.. _codec-objects:
389
390Codec Objects
391^^^^^^^^^^^^^
392
393The :class:`Codec` class defines these methods which also define the function
394interfaces of the stateless encoder and decoder:
395
396
397.. method:: Codec.encode(input[, errors])
398
399 Encodes the object *input* and returns a tuple (output object, length consumed).
Georg Brandl30c78d62008-05-11 14:52:00 +0000400 Encoding converts a string object to a bytes object using a particular
Georg Brandl116aa622007-08-15 14:28:22 +0000401 character set encoding (e.g., ``cp1252`` or ``iso-8859-1``).
402
403 *errors* defines the error handling to apply. It defaults to ``'strict'``
404 handling.
405
406 The method may not store state in the :class:`Codec` instance. Use
407 :class:`StreamCodec` for codecs which have to keep state in order to make
408 encoding/decoding efficient.
409
410 The encoder must be able to handle zero length input and return an empty object
411 of the output object type in this situation.
412
413
414.. method:: Codec.decode(input[, errors])
415
Georg Brandl30c78d62008-05-11 14:52:00 +0000416 Decodes the object *input* and returns a tuple (output object, length
417 consumed). Decoding converts a bytes object encoded using a particular
418 character set encoding to a string object.
Georg Brandl116aa622007-08-15 14:28:22 +0000419
Georg Brandl30c78d62008-05-11 14:52:00 +0000420 *input* must be a bytes object or one which provides the read-only character
421 buffer interface -- for example, buffer objects and memory mapped files.
Georg Brandl116aa622007-08-15 14:28:22 +0000422
423 *errors* defines the error handling to apply. It defaults to ``'strict'``
424 handling.
425
426 The method may not store state in the :class:`Codec` instance. Use
427 :class:`StreamCodec` for codecs which have to keep state in order to make
428 encoding/decoding efficient.
429
430 The decoder must be able to handle zero length input and return an empty object
431 of the output object type in this situation.
432
433The :class:`IncrementalEncoder` and :class:`IncrementalDecoder` classes provide
434the basic interface for incremental encoding and decoding. Encoding/decoding the
435input isn't done with one call to the stateless encoder/decoder function, but
Serhiy Storchakabfdcd432013-10-13 23:09:14 +0300436with multiple calls to the
437:meth:`~IncrementalEncoder.encode`/:meth:`~IncrementalDecoder.decode` method of
438the incremental encoder/decoder. The incremental encoder/decoder keeps track of
439the encoding/decoding process during method calls.
Georg Brandl116aa622007-08-15 14:28:22 +0000440
Serhiy Storchakabfdcd432013-10-13 23:09:14 +0300441The joined output of calls to the
442:meth:`~IncrementalEncoder.encode`/:meth:`~IncrementalDecoder.decode` method is
443the same as if all the single inputs were joined into one, and this input was
Georg Brandl116aa622007-08-15 14:28:22 +0000444encoded/decoded with the stateless encoder/decoder.
445
446
447.. _incremental-encoder-objects:
448
449IncrementalEncoder Objects
450^^^^^^^^^^^^^^^^^^^^^^^^^^
451
Georg Brandl116aa622007-08-15 14:28:22 +0000452The :class:`IncrementalEncoder` class is used for encoding an input in multiple
453steps. It defines the following methods which every incremental encoder must
454define in order to be compatible with the Python codec registry.
455
456
457.. class:: IncrementalEncoder([errors])
458
459 Constructor for an :class:`IncrementalEncoder` instance.
460
461 All incremental encoders must provide this constructor interface. They are free
462 to add additional keyword arguments, but only the ones defined here are used by
463 the Python codec registry.
464
465 The :class:`IncrementalEncoder` may implement different error handling schemes
466 by providing the *errors* keyword argument. These parameters are predefined:
467
468 * ``'strict'`` Raise :exc:`ValueError` (or a subclass); this is the default.
469
470 * ``'ignore'`` Ignore the character and continue with the next.
471
472 * ``'replace'`` Replace with a suitable replacement character
473
474 * ``'xmlcharrefreplace'`` Replace with the appropriate XML character reference
475
476 * ``'backslashreplace'`` Replace with backslashed escape sequences.
477
478 The *errors* argument will be assigned to an attribute of the same name.
479 Assigning to this attribute makes it possible to switch between different error
480 handling strategies during the lifetime of the :class:`IncrementalEncoder`
481 object.
482
483 The set of allowed values for the *errors* argument can be extended with
484 :func:`register_error`.
485
486
Benjamin Petersone41251e2008-04-25 01:59:09 +0000487 .. method:: encode(object[, final])
Georg Brandl116aa622007-08-15 14:28:22 +0000488
Benjamin Petersone41251e2008-04-25 01:59:09 +0000489 Encodes *object* (taking the current state of the encoder into account)
490 and returns the resulting encoded object. If this is the last call to
491 :meth:`encode` *final* must be true (the default is false).
Georg Brandl116aa622007-08-15 14:28:22 +0000492
493
Benjamin Petersone41251e2008-04-25 01:59:09 +0000494 .. method:: reset()
Georg Brandl116aa622007-08-15 14:28:22 +0000495
Victor Stinnere15dce32011-05-30 22:56:00 +0200496 Reset the encoder to the initial state. The output is discarded: call
497 ``.encode('', final=True)`` to reset the encoder and to get the output.
Georg Brandl116aa622007-08-15 14:28:22 +0000498
499
500.. method:: IncrementalEncoder.getstate()
501
502 Return the current state of the encoder which must be an integer. The
503 implementation should make sure that ``0`` is the most common state. (States
504 that are more complicated than integers can be converted into an integer by
505 marshaling/pickling the state and encoding the bytes of the resulting string
506 into an integer).
507
Georg Brandl116aa622007-08-15 14:28:22 +0000508
509.. method:: IncrementalEncoder.setstate(state)
510
511 Set the state of the encoder to *state*. *state* must be an encoder state
512 returned by :meth:`getstate`.
513
Georg Brandl116aa622007-08-15 14:28:22 +0000514
515.. _incremental-decoder-objects:
516
517IncrementalDecoder Objects
518^^^^^^^^^^^^^^^^^^^^^^^^^^
519
520The :class:`IncrementalDecoder` class is used for decoding an input in multiple
521steps. It defines the following methods which every incremental decoder must
522define in order to be compatible with the Python codec registry.
523
524
525.. class:: IncrementalDecoder([errors])
526
527 Constructor for an :class:`IncrementalDecoder` instance.
528
529 All incremental decoders must provide this constructor interface. They are free
530 to add additional keyword arguments, but only the ones defined here are used by
531 the Python codec registry.
532
533 The :class:`IncrementalDecoder` may implement different error handling schemes
534 by providing the *errors* keyword argument. These parameters are predefined:
535
536 * ``'strict'`` Raise :exc:`ValueError` (or a subclass); this is the default.
537
538 * ``'ignore'`` Ignore the character and continue with the next.
539
540 * ``'replace'`` Replace with a suitable replacement character.
541
542 The *errors* argument will be assigned to an attribute of the same name.
543 Assigning to this attribute makes it possible to switch between different error
Benjamin Peterson3e4f0552008-09-02 00:31:15 +0000544 handling strategies during the lifetime of the :class:`IncrementalDecoder`
Georg Brandl116aa622007-08-15 14:28:22 +0000545 object.
546
547 The set of allowed values for the *errors* argument can be extended with
548 :func:`register_error`.
549
550
Benjamin Petersone41251e2008-04-25 01:59:09 +0000551 .. method:: decode(object[, final])
Georg Brandl116aa622007-08-15 14:28:22 +0000552
Benjamin Petersone41251e2008-04-25 01:59:09 +0000553 Decodes *object* (taking the current state of the decoder into account)
554 and returns the resulting decoded object. If this is the last call to
555 :meth:`decode` *final* must be true (the default is false). If *final* is
556 true the decoder must decode the input completely and must flush all
557 buffers. If this isn't possible (e.g. because of incomplete byte sequences
558 at the end of the input) it must initiate error handling just like in the
559 stateless case (which might raise an exception).
Georg Brandl116aa622007-08-15 14:28:22 +0000560
561
Benjamin Petersone41251e2008-04-25 01:59:09 +0000562 .. method:: reset()
Georg Brandl116aa622007-08-15 14:28:22 +0000563
Benjamin Petersone41251e2008-04-25 01:59:09 +0000564 Reset the decoder to the initial state.
Georg Brandl116aa622007-08-15 14:28:22 +0000565
566
Benjamin Petersone41251e2008-04-25 01:59:09 +0000567 .. method:: getstate()
Georg Brandl116aa622007-08-15 14:28:22 +0000568
Benjamin Petersone41251e2008-04-25 01:59:09 +0000569 Return the current state of the decoder. This must be a tuple with two
570 items, the first must be the buffer containing the still undecoded
571 input. The second must be an integer and can be additional state
572 info. (The implementation should make sure that ``0`` is the most common
573 additional state info.) If this additional state info is ``0`` it must be
574 possible to set the decoder to the state which has no input buffered and
575 ``0`` as the additional state info, so that feeding the previously
576 buffered input to the decoder returns it to the previous state without
577 producing any output. (Additional state info that is more complicated than
578 integers can be converted into an integer by marshaling/pickling the info
579 and encoding the bytes of the resulting string into an integer.)
Georg Brandl116aa622007-08-15 14:28:22 +0000580
Georg Brandl116aa622007-08-15 14:28:22 +0000581
Benjamin Petersone41251e2008-04-25 01:59:09 +0000582 .. method:: setstate(state)
Georg Brandl116aa622007-08-15 14:28:22 +0000583
Benjamin Petersone41251e2008-04-25 01:59:09 +0000584 Set the state of the encoder to *state*. *state* must be a decoder state
585 returned by :meth:`getstate`.
586
Georg Brandl116aa622007-08-15 14:28:22 +0000587
Georg Brandl116aa622007-08-15 14:28:22 +0000588The :class:`StreamWriter` and :class:`StreamReader` classes provide generic
589working interfaces which can be used to implement new encoding submodules very
590easily. See :mod:`encodings.utf_8` for an example of how this is done.
591
592
593.. _stream-writer-objects:
594
595StreamWriter Objects
596^^^^^^^^^^^^^^^^^^^^
597
598The :class:`StreamWriter` class is a subclass of :class:`Codec` and defines the
599following methods which every stream writer must define in order to be
600compatible with the Python codec registry.
601
602
603.. class:: StreamWriter(stream[, errors])
604
605 Constructor for a :class:`StreamWriter` instance.
606
607 All stream writers must provide this constructor interface. They are free to add
608 additional keyword arguments, but only the ones defined here are used by the
609 Python codec registry.
610
611 *stream* must be a file-like object open for writing binary data.
612
613 The :class:`StreamWriter` may implement different error handling schemes by
614 providing the *errors* keyword argument. These parameters are predefined:
615
616 * ``'strict'`` Raise :exc:`ValueError` (or a subclass); this is the default.
617
618 * ``'ignore'`` Ignore the character and continue with the next.
619
620 * ``'replace'`` Replace with a suitable replacement character
621
622 * ``'xmlcharrefreplace'`` Replace with the appropriate XML character reference
623
624 * ``'backslashreplace'`` Replace with backslashed escape sequences.
625
626 The *errors* argument will be assigned to an attribute of the same name.
627 Assigning to this attribute makes it possible to switch between different error
628 handling strategies during the lifetime of the :class:`StreamWriter` object.
629
630 The set of allowed values for the *errors* argument can be extended with
631 :func:`register_error`.
632
633
Benjamin Petersone41251e2008-04-25 01:59:09 +0000634 .. method:: write(object)
Georg Brandl116aa622007-08-15 14:28:22 +0000635
Benjamin Petersone41251e2008-04-25 01:59:09 +0000636 Writes the object's contents encoded to the stream.
Georg Brandl116aa622007-08-15 14:28:22 +0000637
638
Benjamin Petersone41251e2008-04-25 01:59:09 +0000639 .. method:: writelines(list)
Georg Brandl116aa622007-08-15 14:28:22 +0000640
Benjamin Petersone41251e2008-04-25 01:59:09 +0000641 Writes the concatenated list of strings to the stream (possibly by reusing
642 the :meth:`write` method).
Georg Brandl116aa622007-08-15 14:28:22 +0000643
644
Benjamin Petersone41251e2008-04-25 01:59:09 +0000645 .. method:: reset()
Georg Brandl116aa622007-08-15 14:28:22 +0000646
Benjamin Petersone41251e2008-04-25 01:59:09 +0000647 Flushes and resets the codec buffers used for keeping state.
Georg Brandl116aa622007-08-15 14:28:22 +0000648
Benjamin Petersone41251e2008-04-25 01:59:09 +0000649 Calling this method should ensure that the data on the output is put into
650 a clean state that allows appending of new fresh data without having to
651 rescan the whole stream to recover state.
652
Georg Brandl116aa622007-08-15 14:28:22 +0000653
654In addition to the above methods, the :class:`StreamWriter` must also inherit
655all other methods and attributes from the underlying stream.
656
657
658.. _stream-reader-objects:
659
660StreamReader Objects
661^^^^^^^^^^^^^^^^^^^^
662
663The :class:`StreamReader` class is a subclass of :class:`Codec` and defines the
664following methods which every stream reader must define in order to be
665compatible with the Python codec registry.
666
667
668.. class:: StreamReader(stream[, errors])
669
670 Constructor for a :class:`StreamReader` instance.
671
672 All stream readers must provide this constructor interface. They are free to add
673 additional keyword arguments, but only the ones defined here are used by the
674 Python codec registry.
675
676 *stream* must be a file-like object open for reading (binary) data.
677
678 The :class:`StreamReader` may implement different error handling schemes by
679 providing the *errors* keyword argument. These parameters are defined:
680
681 * ``'strict'`` Raise :exc:`ValueError` (or a subclass); this is the default.
682
683 * ``'ignore'`` Ignore the character and continue with the next.
684
685 * ``'replace'`` Replace with a suitable replacement character.
686
687 The *errors* argument will be assigned to an attribute of the same name.
688 Assigning to this attribute makes it possible to switch between different error
689 handling strategies during the lifetime of the :class:`StreamReader` object.
690
691 The set of allowed values for the *errors* argument can be extended with
692 :func:`register_error`.
693
694
Benjamin Petersone41251e2008-04-25 01:59:09 +0000695 .. method:: read([size[, chars, [firstline]]])
Georg Brandl116aa622007-08-15 14:28:22 +0000696
Benjamin Petersone41251e2008-04-25 01:59:09 +0000697 Decodes data from the stream and returns the resulting object.
Georg Brandl116aa622007-08-15 14:28:22 +0000698
Benjamin Petersone41251e2008-04-25 01:59:09 +0000699 *chars* indicates the number of characters to read from the
700 stream. :func:`read` will never return more than *chars* characters, but
701 it might return less, if there are not enough characters available.
Georg Brandl116aa622007-08-15 14:28:22 +0000702
Benjamin Petersone41251e2008-04-25 01:59:09 +0000703 *size* indicates the approximate maximum number of bytes to read from the
704 stream for decoding purposes. The decoder can modify this setting as
705 appropriate. The default value -1 indicates to read and decode as much as
706 possible. *size* is intended to prevent having to decode huge files in
707 one step.
Georg Brandl116aa622007-08-15 14:28:22 +0000708
Benjamin Petersone41251e2008-04-25 01:59:09 +0000709 *firstline* indicates that it would be sufficient to only return the first
710 line, if there are decoding errors on later lines.
Georg Brandl116aa622007-08-15 14:28:22 +0000711
Benjamin Petersone41251e2008-04-25 01:59:09 +0000712 The method should use a greedy read strategy meaning that it should read
713 as much data as is allowed within the definition of the encoding and the
714 given size, e.g. if optional encoding endings or state markers are
715 available on the stream, these should be read too.
Georg Brandl116aa622007-08-15 14:28:22 +0000716
Georg Brandl116aa622007-08-15 14:28:22 +0000717
Benjamin Petersone41251e2008-04-25 01:59:09 +0000718 .. method:: readline([size[, keepends]])
Georg Brandl116aa622007-08-15 14:28:22 +0000719
Benjamin Petersone41251e2008-04-25 01:59:09 +0000720 Read one line from the input stream and return the decoded data.
Georg Brandl116aa622007-08-15 14:28:22 +0000721
Benjamin Petersone41251e2008-04-25 01:59:09 +0000722 *size*, if given, is passed as size argument to the stream's
Serhiy Storchakacca40ff2013-07-11 18:26:13 +0300723 :meth:`read` method.
Georg Brandl116aa622007-08-15 14:28:22 +0000724
Benjamin Petersone41251e2008-04-25 01:59:09 +0000725 If *keepends* is false line-endings will be stripped from the lines
726 returned.
Georg Brandl116aa622007-08-15 14:28:22 +0000727
Georg Brandl116aa622007-08-15 14:28:22 +0000728
Benjamin Petersone41251e2008-04-25 01:59:09 +0000729 .. method:: readlines([sizehint[, keepends]])
Georg Brandl116aa622007-08-15 14:28:22 +0000730
Benjamin Petersone41251e2008-04-25 01:59:09 +0000731 Read all lines available on the input stream and return them as a list of
732 lines.
Georg Brandl116aa622007-08-15 14:28:22 +0000733
Benjamin Petersone41251e2008-04-25 01:59:09 +0000734 Line-endings are implemented using the codec's decoder method and are
735 included in the list entries if *keepends* is true.
Georg Brandl116aa622007-08-15 14:28:22 +0000736
Benjamin Petersone41251e2008-04-25 01:59:09 +0000737 *sizehint*, if given, is passed as the *size* argument to the stream's
738 :meth:`read` method.
Georg Brandl116aa622007-08-15 14:28:22 +0000739
740
Benjamin Petersone41251e2008-04-25 01:59:09 +0000741 .. method:: reset()
Georg Brandl116aa622007-08-15 14:28:22 +0000742
Benjamin Petersone41251e2008-04-25 01:59:09 +0000743 Resets the codec buffers used for keeping state.
Georg Brandl116aa622007-08-15 14:28:22 +0000744
Benjamin Petersone41251e2008-04-25 01:59:09 +0000745 Note that no stream repositioning should take place. This method is
746 primarily intended to be able to recover from decoding errors.
747
Georg Brandl116aa622007-08-15 14:28:22 +0000748
749In addition to the above methods, the :class:`StreamReader` must also inherit
750all other methods and attributes from the underlying stream.
751
752The next two base classes are included for convenience. They are not needed by
753the codec registry, but may provide useful in practice.
754
755
756.. _stream-reader-writer:
757
758StreamReaderWriter Objects
759^^^^^^^^^^^^^^^^^^^^^^^^^^
760
761The :class:`StreamReaderWriter` allows wrapping streams which work in both read
762and write modes.
763
764The design is such that one can use the factory functions returned by the
765:func:`lookup` function to construct the instance.
766
767
768.. class:: StreamReaderWriter(stream, Reader, Writer, errors)
769
770 Creates a :class:`StreamReaderWriter` instance. *stream* must be a file-like
771 object. *Reader* and *Writer* must be factory functions or classes providing the
772 :class:`StreamReader` and :class:`StreamWriter` interface resp. Error handling
773 is done in the same way as defined for the stream readers and writers.
774
775:class:`StreamReaderWriter` instances define the combined interfaces of
776:class:`StreamReader` and :class:`StreamWriter` classes. They inherit all other
777methods and attributes from the underlying stream.
778
779
780.. _stream-recoder-objects:
781
782StreamRecoder Objects
783^^^^^^^^^^^^^^^^^^^^^
784
785The :class:`StreamRecoder` provide a frontend - backend view of encoding data
786which is sometimes useful when dealing with different encoding environments.
787
788The design is such that one can use the factory functions returned by the
789:func:`lookup` function to construct the instance.
790
791
792.. class:: StreamRecoder(stream, encode, decode, Reader, Writer, errors)
793
794 Creates a :class:`StreamRecoder` instance which implements a two-way conversion:
795 *encode* and *decode* work on the frontend (the input to :meth:`read` and output
796 of :meth:`write`) while *Reader* and *Writer* work on the backend (reading and
797 writing to the stream).
798
799 You can use these objects to do transparent direct recodings from e.g. Latin-1
800 to UTF-8 and back.
801
802 *stream* must be a file-like object.
803
804 *encode*, *decode* must adhere to the :class:`Codec` interface. *Reader*,
805 *Writer* must be factory functions or classes providing objects of the
806 :class:`StreamReader` and :class:`StreamWriter` interface respectively.
807
808 *encode* and *decode* are needed for the frontend translation, *Reader* and
Georg Brandl30c78d62008-05-11 14:52:00 +0000809 *Writer* for the backend translation.
Georg Brandl116aa622007-08-15 14:28:22 +0000810
811 Error handling is done in the same way as defined for the stream readers and
812 writers.
813
Benjamin Petersone41251e2008-04-25 01:59:09 +0000814
Georg Brandl116aa622007-08-15 14:28:22 +0000815:class:`StreamRecoder` instances define the combined interfaces of
816:class:`StreamReader` and :class:`StreamWriter` classes. They inherit all other
817methods and attributes from the underlying stream.
818
819
820.. _encodings-overview:
821
822Encodings and Unicode
823---------------------
824
Ezio Melotti7a03f642011-10-25 10:30:19 +0300825Strings are stored internally as sequences of codepoints in range ``0 - 10FFFF``
826(see :pep:`393` for more details about the implementation).
827Once a string object is used outside of CPU and memory, CPU endianness
Georg Brandl116aa622007-08-15 14:28:22 +0000828and how these arrays are stored as bytes become an issue. Transforming a
Georg Brandl30c78d62008-05-11 14:52:00 +0000829string object into a sequence of bytes is called encoding and recreating the
830string object from the sequence of bytes is known as decoding. There are many
Georg Brandl116aa622007-08-15 14:28:22 +0000831different methods for how this transformation can be done (these methods are
832also called encodings). The simplest method is to map the codepoints 0-255 to
Georg Brandl30c78d62008-05-11 14:52:00 +0000833the bytes ``0x0``-``0xff``. This means that a string object that contains
Georg Brandl116aa622007-08-15 14:28:22 +0000834codepoints above ``U+00FF`` can't be encoded with this method (which is called
Georg Brandl30c78d62008-05-11 14:52:00 +0000835``'latin-1'`` or ``'iso-8859-1'``). :func:`str.encode` will raise a
Georg Brandl116aa622007-08-15 14:28:22 +0000836:exc:`UnicodeEncodeError` that looks like this: ``UnicodeEncodeError: 'latin-1'
Georg Brandl30c78d62008-05-11 14:52:00 +0000837codec can't encode character '\u1234' in position 3: ordinal not in
Georg Brandl116aa622007-08-15 14:28:22 +0000838range(256)``.
839
840There's another group of encodings (the so called charmap encodings) that choose
Georg Brandl30c78d62008-05-11 14:52:00 +0000841a different subset of all Unicode code points and how these codepoints are
Georg Brandl116aa622007-08-15 14:28:22 +0000842mapped to the bytes ``0x0``-``0xff``. To see how this is done simply open
843e.g. :file:`encodings/cp1252.py` (which is an encoding that is used primarily on
844Windows). There's a string constant with 256 characters that shows you which
845character is mapped to which byte value.
846
Ezio Melottifbb39812011-10-25 10:40:38 +0300847All of these encodings can only encode 256 of the 1114112 codepoints
Georg Brandl30c78d62008-05-11 14:52:00 +0000848defined in Unicode. A simple and straightforward way that can store each Unicode
Ezio Melottifbb39812011-10-25 10:40:38 +0300849code point, is to store each codepoint as four consecutive bytes. There are two
850possibilities: store the bytes in big endian or in little endian order. These
851two encodings are called ``UTF-32-BE`` and ``UTF-32-LE`` respectively. Their
852disadvantage is that if e.g. you use ``UTF-32-BE`` on a little endian machine you
853will always have to swap bytes on encoding and decoding. ``UTF-32`` avoids this
854problem: bytes will always be in natural endianness. When these bytes are read
Georg Brandl116aa622007-08-15 14:28:22 +0000855by a CPU with a different endianness, then bytes have to be swapped though. To
Ezio Melottifbb39812011-10-25 10:40:38 +0300856be able to detect the endianness of a ``UTF-16`` or ``UTF-32`` byte sequence,
857there's the so called BOM ("Byte Order Mark"). This is the Unicode character
858``U+FEFF``. This character can be prepended to every ``UTF-16`` or ``UTF-32``
859byte sequence. The byte swapped version of this character (``0xFFFE``) is an
860illegal character that may not appear in a Unicode text. So when the
861first character in an ``UTF-16`` or ``UTF-32`` byte sequence
Georg Brandl116aa622007-08-15 14:28:22 +0000862appears to be a ``U+FFFE`` the bytes have to be swapped on decoding.
Ezio Melottifbb39812011-10-25 10:40:38 +0300863Unfortunately the character ``U+FEFF`` had a second purpose as
864a ``ZERO WIDTH NO-BREAK SPACE``: a character that has no width and doesn't allow
Georg Brandl116aa622007-08-15 14:28:22 +0000865a word to be split. It can e.g. be used to give hints to a ligature algorithm.
866With Unicode 4.0 using ``U+FEFF`` as a ``ZERO WIDTH NO-BREAK SPACE`` has been
867deprecated (with ``U+2060`` (``WORD JOINER``) assuming this role). Nevertheless
Ezio Melottifbb39812011-10-25 10:40:38 +0300868Unicode software still must be able to handle ``U+FEFF`` in both roles: as a BOM
Georg Brandl116aa622007-08-15 14:28:22 +0000869it's a device to determine the storage layout of the encoded bytes, and vanishes
Georg Brandl30c78d62008-05-11 14:52:00 +0000870once the byte sequence has been decoded into a string; as a ``ZERO WIDTH
Georg Brandl116aa622007-08-15 14:28:22 +0000871NO-BREAK SPACE`` it's a normal character that will be decoded like any other.
872
873There's another encoding that is able to encoding the full range of Unicode
874characters: UTF-8. UTF-8 is an 8-bit encoding, which means there are no issues
875with byte order in UTF-8. Each byte in a UTF-8 byte sequence consists of two
Ezio Melottifbb39812011-10-25 10:40:38 +0300876parts: marker bits (the most significant bits) and payload bits. The marker bits
Ezio Melotti222b2082011-09-01 08:11:28 +0300877are a sequence of zero to four ``1`` bits followed by a ``0`` bit. Unicode characters are
Georg Brandl116aa622007-08-15 14:28:22 +0000878encoded like this (with x being payload bits, which when concatenated give the
879Unicode character):
880
881+-----------------------------------+----------------------------------------------+
882| Range | Encoding |
883+===================================+==============================================+
884| ``U-00000000`` ... ``U-0000007F`` | 0xxxxxxx |
885+-----------------------------------+----------------------------------------------+
886| ``U-00000080`` ... ``U-000007FF`` | 110xxxxx 10xxxxxx |
887+-----------------------------------+----------------------------------------------+
888| ``U-00000800`` ... ``U-0000FFFF`` | 1110xxxx 10xxxxxx 10xxxxxx |
889+-----------------------------------+----------------------------------------------+
Ezio Melotti222b2082011-09-01 08:11:28 +0300890| ``U-00010000`` ... ``U-0010FFFF`` | 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx |
Georg Brandl116aa622007-08-15 14:28:22 +0000891+-----------------------------------+----------------------------------------------+
892
893The least significant bit of the Unicode character is the rightmost x bit.
894
895As UTF-8 is an 8-bit encoding no BOM is required and any ``U+FEFF`` character in
Georg Brandl30c78d62008-05-11 14:52:00 +0000896the decoded string (even if it's the first character) is treated as a ``ZERO
897WIDTH NO-BREAK SPACE``.
Georg Brandl116aa622007-08-15 14:28:22 +0000898
899Without external information it's impossible to reliably determine which
Georg Brandl30c78d62008-05-11 14:52:00 +0000900encoding was used for encoding a string. Each charmap encoding can
Georg Brandl116aa622007-08-15 14:28:22 +0000901decode any random byte sequence. However that's not possible with UTF-8, as
902UTF-8 byte sequences have a structure that doesn't allow arbitrary byte
Thomas Wouters89d996e2007-09-08 17:39:28 +0000903sequences. To increase the reliability with which a UTF-8 encoding can be
Georg Brandl116aa622007-08-15 14:28:22 +0000904detected, Microsoft invented a variant of UTF-8 (that Python 2.5 calls
905``"utf-8-sig"``) for its Notepad program: Before any of the Unicode characters
906is written to the file, a UTF-8 encoded BOM (which looks like this as a byte
907sequence: ``0xef``, ``0xbb``, ``0xbf``) is written. As it's rather improbable
908that any charmap encoded file starts with these byte values (which would e.g.
909map to
910
911 | LATIN SMALL LETTER I WITH DIAERESIS
912 | RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK
913 | INVERTED QUESTION MARK
914
Ezio Melottifbb39812011-10-25 10:40:38 +0300915in iso-8859-1), this increases the probability that a ``utf-8-sig`` encoding can be
Georg Brandl116aa622007-08-15 14:28:22 +0000916correctly guessed from the byte sequence. So here the BOM is not used to be able
917to determine the byte order used for generating the byte sequence, but as a
918signature that helps in guessing the encoding. On encoding the utf-8-sig codec
919will write ``0xef``, ``0xbb``, ``0xbf`` as the first three bytes to the file. On
Ezio Melottifbb39812011-10-25 10:40:38 +0300920decoding ``utf-8-sig`` will skip those three bytes if they appear as the first
921three bytes in the file. In UTF-8, the use of the BOM is discouraged and
922should generally be avoided.
Georg Brandl116aa622007-08-15 14:28:22 +0000923
924
925.. _standard-encodings:
926
927Standard Encodings
928------------------
929
930Python comes with a number of codecs built-in, either implemented as C functions
931or with dictionaries as mapping tables. The following table lists the codecs by
932name, together with a few common aliases, and the languages for which the
933encoding is likely used. Neither the list of aliases nor the list of languages
934is meant to be exhaustive. Notice that spelling alternatives that only differ in
Georg Brandla6053b42009-09-01 08:11:14 +0000935case or use a hyphen instead of an underscore are also valid aliases; therefore,
936e.g. ``'utf-8'`` is a valid alias for the ``'utf_8'`` codec.
Georg Brandl116aa622007-08-15 14:28:22 +0000937
Alexander Belopolsky1d521462011-02-25 19:19:57 +0000938.. impl-detail::
939
940 Some common encodings can bypass the codecs lookup machinery to
941 improve performance. These optimization opportunities are only
942 recognized by CPython for a limited set of aliases: utf-8, utf8,
943 latin-1, latin1, iso-8859-1, mbcs (Windows only), ascii, utf-16,
944 and utf-32. Using alternative spellings for these encodings may
945 result in slower execution.
946
Georg Brandl116aa622007-08-15 14:28:22 +0000947Many of the character sets support the same languages. They vary in individual
948characters (e.g. whether the EURO SIGN is supported or not), and in the
949assignment of characters to code positions. For the European languages in
950particular, the following variants typically exist:
951
952* an ISO 8859 codeset
953
954* a Microsoft Windows code page, which is typically derived from a 8859 codeset,
955 but replaces control characters with additional graphic characters
956
957* an IBM EBCDIC code page
958
959* an IBM PC code page, which is ASCII compatible
960
Georg Brandl44ea77b2013-03-28 13:28:44 +0100961.. tabularcolumns:: |l|p{0.3\linewidth}|p{0.3\linewidth}|
962
Georg Brandl116aa622007-08-15 14:28:22 +0000963+-----------------+--------------------------------+--------------------------------+
964| Codec | Aliases | Languages |
965+=================+================================+================================+
966| ascii | 646, us-ascii | English |
967+-----------------+--------------------------------+--------------------------------+
968| big5 | big5-tw, csbig5 | Traditional Chinese |
969+-----------------+--------------------------------+--------------------------------+
970| big5hkscs | big5-hkscs, hkscs | Traditional Chinese |
971+-----------------+--------------------------------+--------------------------------+
972| cp037 | IBM037, IBM039 | English |
973+-----------------+--------------------------------+--------------------------------+
R David Murrayc4c7b1c2014-03-07 21:00:34 -0500974| cp273 | 273, IBM273, csIBM273 | German |
975| | | |
976| | | .. versionadded:: 3.4 |
977+-----------------+--------------------------------+--------------------------------+
Georg Brandl116aa622007-08-15 14:28:22 +0000978| cp424 | EBCDIC-CP-HE, IBM424 | Hebrew |
979+-----------------+--------------------------------+--------------------------------+
980| cp437 | 437, IBM437 | English |
981+-----------------+--------------------------------+--------------------------------+
982| cp500 | EBCDIC-CP-BE, EBCDIC-CP-CH, | Western Europe |
983| | IBM500 | |
984+-----------------+--------------------------------+--------------------------------+
Amaury Forgeot d'Arcae6388d2009-07-15 19:21:18 +0000985| cp720 | | Arabic |
986+-----------------+--------------------------------+--------------------------------+
Georg Brandl116aa622007-08-15 14:28:22 +0000987| cp737 | | Greek |
988+-----------------+--------------------------------+--------------------------------+
989| cp775 | IBM775 | Baltic languages |
990+-----------------+--------------------------------+--------------------------------+
991| cp850 | 850, IBM850 | Western Europe |
992+-----------------+--------------------------------+--------------------------------+
993| cp852 | 852, IBM852 | Central and Eastern Europe |
994+-----------------+--------------------------------+--------------------------------+
995| cp855 | 855, IBM855 | Bulgarian, Byelorussian, |
996| | | Macedonian, Russian, Serbian |
997+-----------------+--------------------------------+--------------------------------+
998| cp856 | | Hebrew |
999+-----------------+--------------------------------+--------------------------------+
1000| cp857 | 857, IBM857 | Turkish |
1001+-----------------+--------------------------------+--------------------------------+
Benjamin Peterson5a6214a2010-06-27 22:41:29 +00001002| cp858 | 858, IBM858 | Western Europe |
1003+-----------------+--------------------------------+--------------------------------+
Georg Brandl116aa622007-08-15 14:28:22 +00001004| cp860 | 860, IBM860 | Portuguese |
1005+-----------------+--------------------------------+--------------------------------+
1006| cp861 | 861, CP-IS, IBM861 | Icelandic |
1007+-----------------+--------------------------------+--------------------------------+
1008| cp862 | 862, IBM862 | Hebrew |
1009+-----------------+--------------------------------+--------------------------------+
1010| cp863 | 863, IBM863 | Canadian |
1011+-----------------+--------------------------------+--------------------------------+
1012| cp864 | IBM864 | Arabic |
1013+-----------------+--------------------------------+--------------------------------+
1014| cp865 | 865, IBM865 | Danish, Norwegian |
1015+-----------------+--------------------------------+--------------------------------+
1016| cp866 | 866, IBM866 | Russian |
1017+-----------------+--------------------------------+--------------------------------+
1018| cp869 | 869, CP-GR, IBM869 | Greek |
1019+-----------------+--------------------------------+--------------------------------+
1020| cp874 | | Thai |
1021+-----------------+--------------------------------+--------------------------------+
1022| cp875 | | Greek |
1023+-----------------+--------------------------------+--------------------------------+
1024| cp932 | 932, ms932, mskanji, ms-kanji | Japanese |
1025+-----------------+--------------------------------+--------------------------------+
1026| cp949 | 949, ms949, uhc | Korean |
1027+-----------------+--------------------------------+--------------------------------+
1028| cp950 | 950, ms950 | Traditional Chinese |
1029+-----------------+--------------------------------+--------------------------------+
1030| cp1006 | | Urdu |
1031+-----------------+--------------------------------+--------------------------------+
1032| cp1026 | ibm1026 | Turkish |
1033+-----------------+--------------------------------+--------------------------------+
Serhiy Storchakabe0c3252013-11-23 18:52:23 +02001034| cp1125 | 1125, ibm1125, cp866u, ruscii | Ukrainian |
1035| | | |
1036| | | .. versionadded:: 3.4 |
1037+-----------------+--------------------------------+--------------------------------+
Georg Brandl116aa622007-08-15 14:28:22 +00001038| cp1140 | ibm1140 | Western Europe |
1039+-----------------+--------------------------------+--------------------------------+
1040| cp1250 | windows-1250 | Central and Eastern Europe |
1041+-----------------+--------------------------------+--------------------------------+
1042| cp1251 | windows-1251 | Bulgarian, Byelorussian, |
1043| | | Macedonian, Russian, Serbian |
1044+-----------------+--------------------------------+--------------------------------+
1045| cp1252 | windows-1252 | Western Europe |
1046+-----------------+--------------------------------+--------------------------------+
1047| cp1253 | windows-1253 | Greek |
1048+-----------------+--------------------------------+--------------------------------+
1049| cp1254 | windows-1254 | Turkish |
1050+-----------------+--------------------------------+--------------------------------+
1051| cp1255 | windows-1255 | Hebrew |
1052+-----------------+--------------------------------+--------------------------------+
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00001053| cp1256 | windows-1256 | Arabic |
Georg Brandl116aa622007-08-15 14:28:22 +00001054+-----------------+--------------------------------+--------------------------------+
1055| cp1257 | windows-1257 | Baltic languages |
1056+-----------------+--------------------------------+--------------------------------+
1057| cp1258 | windows-1258 | Vietnamese |
1058+-----------------+--------------------------------+--------------------------------+
Victor Stinner2f3ca9f2011-10-27 01:38:56 +02001059| cp65001 | | Windows only: Windows UTF-8 |
1060| | | (``CP_UTF8``) |
1061| | | |
1062| | | .. versionadded:: 3.3 |
1063+-----------------+--------------------------------+--------------------------------+
Georg Brandl116aa622007-08-15 14:28:22 +00001064| euc_jp | eucjp, ujis, u-jis | Japanese |
1065+-----------------+--------------------------------+--------------------------------+
1066| euc_jis_2004 | jisx0213, eucjis2004 | Japanese |
1067+-----------------+--------------------------------+--------------------------------+
1068| euc_jisx0213 | eucjisx0213 | Japanese |
1069+-----------------+--------------------------------+--------------------------------+
1070| euc_kr | euckr, korean, ksc5601, | Korean |
1071| | ks_c-5601, ks_c-5601-1987, | |
1072| | ksx1001, ks_x-1001 | |
1073+-----------------+--------------------------------+--------------------------------+
1074| gb2312 | chinese, csiso58gb231280, euc- | Simplified Chinese |
1075| | cn, euccn, eucgb2312-cn, | |
1076| | gb2312-1980, gb2312-80, iso- | |
1077| | ir-58 | |
1078+-----------------+--------------------------------+--------------------------------+
1079| gbk | 936, cp936, ms936 | Unified Chinese |
1080+-----------------+--------------------------------+--------------------------------+
1081| gb18030 | gb18030-2000 | Unified Chinese |
1082+-----------------+--------------------------------+--------------------------------+
1083| hz | hzgb, hz-gb, hz-gb-2312 | Simplified Chinese |
1084+-----------------+--------------------------------+--------------------------------+
1085| iso2022_jp | csiso2022jp, iso2022jp, | Japanese |
1086| | iso-2022-jp | |
1087+-----------------+--------------------------------+--------------------------------+
1088| iso2022_jp_1 | iso2022jp-1, iso-2022-jp-1 | Japanese |
1089+-----------------+--------------------------------+--------------------------------+
1090| iso2022_jp_2 | iso2022jp-2, iso-2022-jp-2 | Japanese, Korean, Simplified |
1091| | | Chinese, Western Europe, Greek |
1092+-----------------+--------------------------------+--------------------------------+
1093| iso2022_jp_2004 | iso2022jp-2004, | Japanese |
1094| | iso-2022-jp-2004 | |
1095+-----------------+--------------------------------+--------------------------------+
1096| iso2022_jp_3 | iso2022jp-3, iso-2022-jp-3 | Japanese |
1097+-----------------+--------------------------------+--------------------------------+
1098| iso2022_jp_ext | iso2022jp-ext, iso-2022-jp-ext | Japanese |
1099+-----------------+--------------------------------+--------------------------------+
1100| iso2022_kr | csiso2022kr, iso2022kr, | Korean |
1101| | iso-2022-kr | |
1102+-----------------+--------------------------------+--------------------------------+
1103| latin_1 | iso-8859-1, iso8859-1, 8859, | West Europe |
1104| | cp819, latin, latin1, L1 | |
1105+-----------------+--------------------------------+--------------------------------+
1106| iso8859_2 | iso-8859-2, latin2, L2 | Central and Eastern Europe |
1107+-----------------+--------------------------------+--------------------------------+
1108| iso8859_3 | iso-8859-3, latin3, L3 | Esperanto, Maltese |
1109+-----------------+--------------------------------+--------------------------------+
Christian Heimesc3f30c42008-02-22 16:37:40 +00001110| iso8859_4 | iso-8859-4, latin4, L4 | Baltic languages |
Georg Brandl116aa622007-08-15 14:28:22 +00001111+-----------------+--------------------------------+--------------------------------+
1112| iso8859_5 | iso-8859-5, cyrillic | Bulgarian, Byelorussian, |
1113| | | Macedonian, Russian, Serbian |
1114+-----------------+--------------------------------+--------------------------------+
1115| iso8859_6 | iso-8859-6, arabic | Arabic |
1116+-----------------+--------------------------------+--------------------------------+
1117| iso8859_7 | iso-8859-7, greek, greek8 | Greek |
1118+-----------------+--------------------------------+--------------------------------+
1119| iso8859_8 | iso-8859-8, hebrew | Hebrew |
1120+-----------------+--------------------------------+--------------------------------+
1121| iso8859_9 | iso-8859-9, latin5, L5 | Turkish |
1122+-----------------+--------------------------------+--------------------------------+
1123| iso8859_10 | iso-8859-10, latin6, L6 | Nordic languages |
1124+-----------------+--------------------------------+--------------------------------+
Georg Brandl93dc9eb2010-03-14 10:56:14 +00001125| iso8859_13 | iso-8859-13, latin7, L7 | Baltic languages |
Georg Brandl116aa622007-08-15 14:28:22 +00001126+-----------------+--------------------------------+--------------------------------+
1127| iso8859_14 | iso-8859-14, latin8, L8 | Celtic languages |
1128+-----------------+--------------------------------+--------------------------------+
Georg Brandl93dc9eb2010-03-14 10:56:14 +00001129| iso8859_15 | iso-8859-15, latin9, L9 | Western Europe |
1130+-----------------+--------------------------------+--------------------------------+
1131| iso8859_16 | iso-8859-16, latin10, L10 | South-Eastern Europe |
Georg Brandl116aa622007-08-15 14:28:22 +00001132+-----------------+--------------------------------+--------------------------------+
1133| johab | cp1361, ms1361 | Korean |
1134+-----------------+--------------------------------+--------------------------------+
1135| koi8_r | | Russian |
1136+-----------------+--------------------------------+--------------------------------+
1137| koi8_u | | Ukrainian |
1138+-----------------+--------------------------------+--------------------------------+
1139| mac_cyrillic | maccyrillic | Bulgarian, Byelorussian, |
1140| | | Macedonian, Russian, Serbian |
1141+-----------------+--------------------------------+--------------------------------+
1142| mac_greek | macgreek | Greek |
1143+-----------------+--------------------------------+--------------------------------+
1144| mac_iceland | maciceland | Icelandic |
1145+-----------------+--------------------------------+--------------------------------+
1146| mac_latin2 | maclatin2, maccentraleurope | Central and Eastern Europe |
1147+-----------------+--------------------------------+--------------------------------+
Benjamin Peterson23110e72010-08-21 02:54:44 +00001148| mac_roman | macroman, macintosh | Western Europe |
Georg Brandl116aa622007-08-15 14:28:22 +00001149+-----------------+--------------------------------+--------------------------------+
1150| mac_turkish | macturkish | Turkish |
1151+-----------------+--------------------------------+--------------------------------+
1152| ptcp154 | csptcp154, pt154, cp154, | Kazakh |
1153| | cyrillic-asian | |
1154+-----------------+--------------------------------+--------------------------------+
1155| shift_jis | csshiftjis, shiftjis, sjis, | Japanese |
1156| | s_jis | |
1157+-----------------+--------------------------------+--------------------------------+
1158| shift_jis_2004 | shiftjis2004, sjis_2004, | Japanese |
1159| | sjis2004 | |
1160+-----------------+--------------------------------+--------------------------------+
1161| shift_jisx0213 | shiftjisx0213, sjisx0213, | Japanese |
1162| | s_jisx0213 | |
1163+-----------------+--------------------------------+--------------------------------+
Walter Dörwald41980ca2007-08-16 21:55:45 +00001164| utf_32 | U32, utf32 | all languages |
1165+-----------------+--------------------------------+--------------------------------+
1166| utf_32_be | UTF-32BE | all languages |
1167+-----------------+--------------------------------+--------------------------------+
1168| utf_32_le | UTF-32LE | all languages |
1169+-----------------+--------------------------------+--------------------------------+
Georg Brandl116aa622007-08-15 14:28:22 +00001170| utf_16 | U16, utf16 | all languages |
1171+-----------------+--------------------------------+--------------------------------+
Victor Stinner53a9dd72010-12-08 22:25:45 +00001172| utf_16_be | UTF-16BE | all languages |
Georg Brandl116aa622007-08-15 14:28:22 +00001173+-----------------+--------------------------------+--------------------------------+
Victor Stinner53a9dd72010-12-08 22:25:45 +00001174| utf_16_le | UTF-16LE | all languages |
Georg Brandl116aa622007-08-15 14:28:22 +00001175+-----------------+--------------------------------+--------------------------------+
1176| utf_7 | U7, unicode-1-1-utf-7 | all languages |
1177+-----------------+--------------------------------+--------------------------------+
1178| utf_8 | U8, UTF, utf8 | all languages |
1179+-----------------+--------------------------------+--------------------------------+
1180| utf_8_sig | | all languages |
1181+-----------------+--------------------------------+--------------------------------+
1182
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02001183.. versionchanged:: 3.4
1184 The utf-16\* and utf-32\* encoders no longer allow surrogate code points
1185 (U+D800--U+DFFF) to be encoded. The utf-32\* decoders no longer decode
1186 byte sequences that correspond to surrogate code points.
1187
1188
Nick Coghlan650e3222013-05-23 20:24:02 +10001189Python Specific Encodings
1190-------------------------
1191
1192A number of predefined codecs are specific to Python, so their codec names have
1193no meaning outside Python. These are listed in the tables below based on the
1194expected input and output types (note that while text encodings are the most
1195common use case for codecs, the underlying codec infrastructure supports
1196arbitrary data transforms rather than just text encodings). For asymmetric
1197codecs, the stated purpose describes the encoding direction.
1198
Nick Coghlan9c1aed82013-11-23 11:13:36 +10001199Text Encodings
1200^^^^^^^^^^^^^^
1201
Nick Coghlan650e3222013-05-23 20:24:02 +10001202The following codecs provide :class:`str` to :class:`bytes` encoding and
1203:term:`bytes-like object` to :class:`str` decoding, similar to the Unicode text
1204encodings.
Georg Brandl226878c2007-08-31 10:15:37 +00001205
Georg Brandl44ea77b2013-03-28 13:28:44 +01001206.. tabularcolumns:: |l|p{0.3\linewidth}|p{0.3\linewidth}|
1207
Georg Brandl30c78d62008-05-11 14:52:00 +00001208+--------------------+---------+---------------------------+
1209| Codec | Aliases | Purpose |
1210+====================+=========+===========================+
1211| idna | | Implements :rfc:`3490`, |
1212| | | see also |
1213| | | :mod:`encodings.idna` |
1214+--------------------+---------+---------------------------+
1215| mbcs | dbcs | Windows only: Encode |
1216| | | operand according to the |
1217| | | ANSI codepage (CP_ACP) |
1218+--------------------+---------+---------------------------+
1219| palmos | | Encoding of PalmOS 3.5 |
1220+--------------------+---------+---------------------------+
1221| punycode | | Implements :rfc:`3492` |
1222+--------------------+---------+---------------------------+
1223| raw_unicode_escape | | Produce a string that is |
1224| | | suitable as raw Unicode |
1225| | | literal in Python source |
1226| | | code |
1227+--------------------+---------+---------------------------+
1228| undefined | | Raise an exception for |
1229| | | all conversions. Can be |
1230| | | used as the system |
1231| | | encoding if no automatic |
1232| | | coercion between byte and |
1233| | | Unicode strings is |
1234| | | desired. |
1235+--------------------+---------+---------------------------+
1236| unicode_escape | | Produce a string that is |
1237| | | suitable as Unicode |
1238| | | literal in Python source |
1239| | | code |
1240+--------------------+---------+---------------------------+
1241| unicode_internal | | Return the internal |
1242| | | representation of the |
1243| | | operand |
Victor Stinner9f4b1e92011-11-10 20:56:30 +01001244| | | |
1245| | | .. deprecated:: 3.3 |
Georg Brandl30c78d62008-05-11 14:52:00 +00001246+--------------------+---------+---------------------------+
Georg Brandl116aa622007-08-15 14:28:22 +00001247
Nick Coghlan9c1aed82013-11-23 11:13:36 +10001248.. _binary-transforms:
1249
1250Binary Transforms
1251^^^^^^^^^^^^^^^^^
1252
1253The following codecs provide binary transforms: :term:`bytes-like object`
1254to :class:`bytes` mappings.
Nick Coghlan650e3222013-05-23 20:24:02 +10001255
Georg Brandl02524622010-12-02 18:06:51 +00001256
Nick Coghlan9c1aed82013-11-23 11:13:36 +10001257.. tabularcolumns:: |l|L|L|L|
Georg Brandl44ea77b2013-03-28 13:28:44 +01001258
Nick Coghlan9c1aed82013-11-23 11:13:36 +10001259+----------------------+------------------+------------------------------+------------------------------+
1260| Codec | Aliases | Purpose | Encoder / decoder |
1261+======================+==================+==============================+==============================+
1262| base64_codec [#b64]_ | base64, base_64 | Convert operand to MIME | :meth:`base64.b64encode` / |
1263| | | base64 (the result always | :meth:`base64.b64decode` |
1264| | | includes a trailing | |
1265| | | ``'\n'``) | |
1266| | | | |
1267| | | .. versionchanged:: 3.4 | |
1268| | | accepts any | |
1269| | | :term:`bytes-like object` | |
1270| | | as input for encoding and | |
1271| | | decoding | |
1272+----------------------+------------------+------------------------------+------------------------------+
1273| bz2_codec | bz2 | Compress the operand | :meth:`bz2.compress` / |
1274| | | using bz2 | :meth:`bz2.decompress` |
1275+----------------------+------------------+------------------------------+------------------------------+
1276| hex_codec | hex | Convert operand to | :meth:`base64.b16encode` / |
1277| | | hexadecimal | :meth:`base64.b16decode` |
1278| | | representation, with two | |
1279| | | digits per byte | |
1280+----------------------+------------------+------------------------------+------------------------------+
1281| quopri_codec | quopri, | Convert operand to MIME | :meth:`quopri.encodestring` /|
1282| | quotedprintable, | quoted printable | :meth:`quopri.decodestring` |
1283| | quoted_printable | | |
1284+----------------------+------------------+------------------------------+------------------------------+
1285| uu_codec | uu | Convert the operand using | :meth:`uu.encode` / |
1286| | | uuencode | :meth:`uu.decode` |
1287+----------------------+------------------+------------------------------+------------------------------+
1288| zlib_codec | zip, zlib | Compress the operand | :meth:`zlib.compress` / |
1289| | | using gzip | :meth:`zlib.decompress` |
1290+----------------------+------------------+------------------------------+------------------------------+
Georg Brandl02524622010-12-02 18:06:51 +00001291
Nick Coghlanfdf239a2013-10-03 00:43:22 +10001292.. [#b64] In addition to :term:`bytes-like objects <bytes-like object>`,
1293 ``'base64_codec'`` also accepts ASCII-only instances of :class:`str` for
1294 decoding
Nick Coghlan650e3222013-05-23 20:24:02 +10001295
Nick Coghlan9c1aed82013-11-23 11:13:36 +10001296.. versionadded:: 3.2
1297 Restoration of the binary transforms.
Nick Coghlan650e3222013-05-23 20:24:02 +10001298
Nick Coghlan9c1aed82013-11-23 11:13:36 +10001299.. versionchanged:: 3.4
1300 Restoration of the aliases for the binary transforms.
Georg Brandl02524622010-12-02 18:06:51 +00001301
Georg Brandl44ea77b2013-03-28 13:28:44 +01001302
Nick Coghlan9c1aed82013-11-23 11:13:36 +10001303.. _text-transforms:
1304
1305Text Transforms
1306^^^^^^^^^^^^^^^
1307
1308The following codec provides a text transform: a :class:`str` to :class:`str`
1309mapping.
1310
1311.. tabularcolumns:: |l|l|L|
1312
1313+--------------------+---------+---------------------------+
1314| Codec | Aliases | Purpose |
1315+====================+=========+===========================+
1316| rot_13 | rot13 | Returns the Caesar-cypher |
1317| | | encryption of the operand |
1318+--------------------+---------+---------------------------+
Georg Brandl02524622010-12-02 18:06:51 +00001319
1320.. versionadded:: 3.2
Nick Coghlan9c1aed82013-11-23 11:13:36 +10001321 Restoration of the ``rot_13`` text transform.
1322
1323.. versionchanged:: 3.4
1324 Restoration of the ``rot13`` alias.
Georg Brandl02524622010-12-02 18:06:51 +00001325
Georg Brandl116aa622007-08-15 14:28:22 +00001326
1327:mod:`encodings.idna` --- Internationalized Domain Names in Applications
1328------------------------------------------------------------------------
1329
1330.. module:: encodings.idna
1331 :synopsis: Internationalized Domain Names implementation
1332.. moduleauthor:: Martin v. Löwis
1333
Georg Brandl116aa622007-08-15 14:28:22 +00001334This module implements :rfc:`3490` (Internationalized Domain Names in
1335Applications) and :rfc:`3492` (Nameprep: A Stringprep Profile for
1336Internationalized Domain Names (IDN)). It builds upon the ``punycode`` encoding
1337and :mod:`stringprep`.
1338
1339These RFCs together define a protocol to support non-ASCII characters in domain
1340names. A domain name containing non-ASCII characters (such as
1341``www.Alliancefrançaise.nu``) is converted into an ASCII-compatible encoding
1342(ACE, such as ``www.xn--alliancefranaise-npb.nu``). The ACE form of the domain
1343name is then used in all places where arbitrary characters are not allowed by
1344the protocol, such as DNS queries, HTTP :mailheader:`Host` fields, and so
1345on. This conversion is carried out in the application; if possible invisible to
1346the user: The application should transparently convert Unicode domain labels to
1347IDNA on the wire, and convert back ACE labels to Unicode before presenting them
1348to the user.
1349
R David Murraye0fd2f82011-04-13 14:12:18 -04001350Python supports this conversion in several ways: the ``idna`` codec performs
1351conversion between Unicode and ACE, separating an input string into labels
1352based on the separator characters defined in `section 3.1`_ (1) of :rfc:`3490`
1353and converting each label to ACE as required, and conversely separating an input
1354byte string into labels based on the ``.`` separator and converting any ACE
1355labels found into unicode. Furthermore, the :mod:`socket` module
Georg Brandl116aa622007-08-15 14:28:22 +00001356transparently converts Unicode host names to ACE, so that applications need not
1357be concerned about converting host names themselves when they pass them to the
1358socket module. On top of that, modules that have host names as function
Georg Brandl24420152008-05-26 16:32:26 +00001359parameters, such as :mod:`http.client` and :mod:`ftplib`, accept Unicode host
1360names (:mod:`http.client` then also transparently sends an IDNA hostname in the
Georg Brandl116aa622007-08-15 14:28:22 +00001361:mailheader:`Host` field if it sends that field at all).
1362
R David Murraye0fd2f82011-04-13 14:12:18 -04001363.. _section 3.1: http://tools.ietf.org/html/rfc3490#section-3.1
1364
Georg Brandl116aa622007-08-15 14:28:22 +00001365When receiving host names from the wire (such as in reverse name lookup), no
1366automatic conversion to Unicode is performed: Applications wishing to present
1367such host names to the user should decode them to Unicode.
1368
1369The module :mod:`encodings.idna` also implements the nameprep procedure, which
1370performs certain normalizations on host names, to achieve case-insensitivity of
1371international domain names, and to unify similar characters. The nameprep
1372functions can be used directly if desired.
1373
1374
1375.. function:: nameprep(label)
1376
1377 Return the nameprepped version of *label*. The implementation currently assumes
1378 query strings, so ``AllowUnassigned`` is true.
1379
1380
1381.. function:: ToASCII(label)
1382
1383 Convert a label to ASCII, as specified in :rfc:`3490`. ``UseSTD3ASCIIRules`` is
1384 assumed to be false.
1385
1386
1387.. function:: ToUnicode(label)
1388
1389 Convert a label to Unicode, as specified in :rfc:`3490`.
1390
1391
Victor Stinner554f3f02010-06-16 23:33:54 +00001392:mod:`encodings.mbcs` --- Windows ANSI codepage
1393-----------------------------------------------
1394
1395.. module:: encodings.mbcs
1396 :synopsis: Windows ANSI codepage
1397
Victor Stinner3a50e702011-10-18 21:21:00 +02001398Encode operand according to the ANSI codepage (CP_ACP).
Victor Stinner554f3f02010-06-16 23:33:54 +00001399
1400Availability: Windows only.
1401
Victor Stinner3a50e702011-10-18 21:21:00 +02001402.. versionchanged:: 3.3
1403 Support any error handler.
1404
Victor Stinner554f3f02010-06-16 23:33:54 +00001405.. versionchanged:: 3.2
1406 Before 3.2, the *errors* argument was ignored; ``'replace'`` was always used
1407 to encode, and ``'ignore'`` to decode.
1408
1409
Georg Brandl116aa622007-08-15 14:28:22 +00001410:mod:`encodings.utf_8_sig` --- UTF-8 codec with BOM signature
1411-------------------------------------------------------------
1412
1413.. module:: encodings.utf_8_sig
1414 :synopsis: UTF-8 codec with BOM signature
1415.. moduleauthor:: Walter Dörwald
1416
Georg Brandl116aa622007-08-15 14:28:22 +00001417This module implements a variant of the UTF-8 codec: On encoding a UTF-8 encoded
1418BOM will be prepended to the UTF-8 encoded bytes. For the stateful encoder this
1419is only done once (on the first write to the byte stream). For decoding an
1420optional UTF-8 encoded BOM at the start of the data will be skipped.
1421