blob: 36144e9ef231160f6f78faaf9b16d883d6c0e110 [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
Andrew Kuchling2e3743c2014-03-19 16:23:01 -040010**Source code:** :source:`Lib/codecs.py`
Georg Brandl116aa622007-08-15 14:28:22 +000011
12.. index::
13 single: Unicode
14 single: Codecs
15 pair: Codecs; encode
16 pair: Codecs; decode
17 single: streams
18 pair: stackable; streams
19
20This module defines base classes for standard Python codecs (encoders and
21decoders) and provides access to the internal Python codec registry which
22manages the codec and error handling lookup process.
23
24It defines the following functions:
25
Nick Coghlan6cb2b5b2013-10-14 00:22:13 +100026.. function:: encode(obj, encoding='utf-8', errors='strict')
27
28 Encodes *obj* using the codec registered for *encoding*.
29
30 *Errors* may be given to set the desired error handling scheme. The
31 default error handler is ``strict`` meaning that encoding errors raise
32 :exc:`ValueError` (or a more codec specific subclass, such as
33 :exc:`UnicodeEncodeError`). Refer to :ref:`codec-base-classes` for more
34 information on codec error handling.
35
36.. function:: decode(obj, encoding='utf-8', errors='strict')
37
38 Decodes *obj* using the codec registered for *encoding*.
39
40 *Errors* may be given to set the desired error handling scheme. The
41 default error handler is ``strict`` meaning that decoding errors raise
42 :exc:`ValueError` (or a more codec specific subclass, such as
43 :exc:`UnicodeDecodeError`). Refer to :ref:`codec-base-classes` for more
44 information on codec error handling.
Georg Brandl116aa622007-08-15 14:28:22 +000045
46.. function:: register(search_function)
47
48 Register a codec search function. Search functions are expected to take one
49 argument, the encoding name in all lower case letters, and return a
50 :class:`CodecInfo` object having the following attributes:
51
52 * ``name`` The name of the encoding;
53
Walter Dörwald62073e02008-10-23 13:21:33 +000054 * ``encode`` The stateless encoding function;
Georg Brandl116aa622007-08-15 14:28:22 +000055
Walter Dörwald62073e02008-10-23 13:21:33 +000056 * ``decode`` The stateless decoding function;
Georg Brandl116aa622007-08-15 14:28:22 +000057
58 * ``incrementalencoder`` An incremental encoder class or factory function;
59
60 * ``incrementaldecoder`` An incremental decoder class or factory function;
61
62 * ``streamwriter`` A stream writer class or factory function;
63
64 * ``streamreader`` A stream reader class or factory function.
65
66 The various functions or classes take the following arguments:
67
Walter Dörwald62073e02008-10-23 13:21:33 +000068 *encode* and *decode*: These must be functions or methods which have the same
Serhiy Storchakabfdcd432013-10-13 23:09:14 +030069 interface as the :meth:`~Codec.encode`/:meth:`~Codec.decode` methods of Codec
70 instances (see :ref:`Codec Interface <codec-objects>`). The functions/methods
71 are expected to work in a stateless mode.
Georg Brandl116aa622007-08-15 14:28:22 +000072
Benjamin Peterson3e4f0552008-09-02 00:31:15 +000073 *incrementalencoder* and *incrementaldecoder*: These have to be factory
Georg Brandl116aa622007-08-15 14:28:22 +000074 functions providing the following interface:
75
Georg Brandl495f7b52009-10-27 15:28:25 +000076 ``factory(errors='strict')``
Georg Brandl116aa622007-08-15 14:28:22 +000077
78 The factory functions must return objects providing the interfaces defined by
Benjamin Peterson3e4f0552008-09-02 00:31:15 +000079 the base classes :class:`IncrementalEncoder` and :class:`IncrementalDecoder`,
Georg Brandl116aa622007-08-15 14:28:22 +000080 respectively. Incremental codecs can maintain state.
81
82 *streamreader* and *streamwriter*: These have to be factory functions providing
83 the following interface:
84
Georg Brandl495f7b52009-10-27 15:28:25 +000085 ``factory(stream, errors='strict')``
Georg Brandl116aa622007-08-15 14:28:22 +000086
87 The factory functions must return objects providing the interfaces defined by
Georg Brandl9c2505b2013-10-06 13:17:04 +020088 the base classes :class:`StreamReader` and :class:`StreamWriter`, respectively.
Georg Brandl116aa622007-08-15 14:28:22 +000089 Stream codecs can maintain state.
90
Georg Brandl495f7b52009-10-27 15:28:25 +000091 Possible values for errors are
92
93 * ``'strict'``: raise an exception in case of an encoding error
94 * ``'replace'``: replace malformed data with a suitable replacement marker,
95 such as ``'?'`` or ``'\ufffd'``
96 * ``'ignore'``: ignore malformed data and continue without further notice
97 * ``'xmlcharrefreplace'``: replace with the appropriate XML character
98 reference (for encoding only)
99 * ``'backslashreplace'``: replace with backslashed escape sequences (for
Ezio Melottie33721e2010-02-27 13:54:27 +0000100 encoding only)
Andrew Kuchlingc7b6c502013-06-16 12:58:48 -0400101 * ``'surrogateescape'``: on decoding, replace with code points in the Unicode
102 Private Use Area ranging from U+DC80 to U+DCFF. These private code
103 points will then be turned back into the same bytes when the
104 ``surrogateescape`` error handler is used when encoding the data.
105 (See :pep:`383` for more.)
Georg Brandl495f7b52009-10-27 15:28:25 +0000106
107 as well as any other error handling name defined via :func:`register_error`.
Georg Brandl116aa622007-08-15 14:28:22 +0000108
109 In case a search function cannot find a given encoding, it should return
110 ``None``.
111
112
113.. function:: lookup(encoding)
114
115 Looks up the codec info in the Python codec registry and returns a
116 :class:`CodecInfo` object as defined above.
117
118 Encodings are first looked up in the registry's cache. If not found, the list of
119 registered search functions is scanned. If no :class:`CodecInfo` object is
120 found, a :exc:`LookupError` is raised. Otherwise, the :class:`CodecInfo` object
121 is stored in the cache and returned to the caller.
122
123To simplify access to the various codecs, the module provides these additional
124functions which use :func:`lookup` for the codec lookup:
125
126
127.. function:: getencoder(encoding)
128
129 Look up the codec for the given encoding and return its encoder function.
130
131 Raises a :exc:`LookupError` in case the encoding cannot be found.
132
133
134.. function:: getdecoder(encoding)
135
136 Look up the codec for the given encoding and return its decoder function.
137
138 Raises a :exc:`LookupError` in case the encoding cannot be found.
139
140
141.. function:: getincrementalencoder(encoding)
142
143 Look up the codec for the given encoding and return its incremental encoder
144 class or factory function.
145
146 Raises a :exc:`LookupError` in case the encoding cannot be found or the codec
147 doesn't support an incremental encoder.
148
Georg Brandl116aa622007-08-15 14:28:22 +0000149
150.. function:: getincrementaldecoder(encoding)
151
152 Look up the codec for the given encoding and return its incremental decoder
153 class or factory function.
154
155 Raises a :exc:`LookupError` in case the encoding cannot be found or the codec
156 doesn't support an incremental decoder.
157
Georg Brandl116aa622007-08-15 14:28:22 +0000158
159.. function:: getreader(encoding)
160
161 Look up the codec for the given encoding and return its StreamReader class or
162 factory function.
163
164 Raises a :exc:`LookupError` in case the encoding cannot be found.
165
166
167.. function:: getwriter(encoding)
168
169 Look up the codec for the given encoding and return its StreamWriter class or
170 factory function.
171
172 Raises a :exc:`LookupError` in case the encoding cannot be found.
173
174
175.. function:: register_error(name, error_handler)
176
177 Register the error handling function *error_handler* under the name *name*.
178 *error_handler* will be called during encoding and decoding in case of an error,
179 when *name* is specified as the errors parameter.
180
181 For encoding *error_handler* will be called with a :exc:`UnicodeEncodeError`
Benjamin Peterson19603552012-12-02 11:26:10 -0500182 instance, which contains information about the location of the error. The
183 error handler must either raise this or a different exception or return a
184 tuple with a replacement for the unencodable part of the input and a position
185 where encoding should continue. The replacement may be either :class:`str` or
186 :class:`bytes`. If the replacement is bytes, the encoder will simply copy
187 them into the output buffer. If the replacement is a string, the encoder will
188 encode the replacement. Encoding continues on original input at the
189 specified position. Negative position values will be treated as being
190 relative to the end of the input string. If the resulting position is out of
191 bound an :exc:`IndexError` will be raised.
Georg Brandl116aa622007-08-15 14:28:22 +0000192
193 Decoding and translating works similar, except :exc:`UnicodeDecodeError` or
194 :exc:`UnicodeTranslateError` will be passed to the handler and that the
195 replacement from the error handler will be put into the output directly.
196
197
198.. function:: lookup_error(name)
199
200 Return the error handler previously registered under the name *name*.
201
202 Raises a :exc:`LookupError` in case the handler cannot be found.
203
204
205.. function:: strict_errors(exception)
206
Georg Brandl495f7b52009-10-27 15:28:25 +0000207 Implements the ``strict`` error handling: each encoding or decoding error
208 raises a :exc:`UnicodeError`.
Georg Brandl116aa622007-08-15 14:28:22 +0000209
210
211.. function:: replace_errors(exception)
212
Georg Brandl495f7b52009-10-27 15:28:25 +0000213 Implements the ``replace`` error handling: malformed data is replaced with a
214 suitable replacement character such as ``'?'`` in bytestrings and
215 ``'\ufffd'`` in Unicode strings.
Georg Brandl116aa622007-08-15 14:28:22 +0000216
217
218.. function:: ignore_errors(exception)
219
Georg Brandl495f7b52009-10-27 15:28:25 +0000220 Implements the ``ignore`` error handling: malformed data is ignored and
221 encoding or decoding is continued without further notice.
Georg Brandl116aa622007-08-15 14:28:22 +0000222
223
Thomas Wouters89d996e2007-09-08 17:39:28 +0000224.. function:: xmlcharrefreplace_errors(exception)
Georg Brandl116aa622007-08-15 14:28:22 +0000225
Georg Brandl495f7b52009-10-27 15:28:25 +0000226 Implements the ``xmlcharrefreplace`` error handling (for encoding only): the
227 unencodable character is replaced by an appropriate XML character reference.
Georg Brandl116aa622007-08-15 14:28:22 +0000228
229
Thomas Wouters89d996e2007-09-08 17:39:28 +0000230.. function:: backslashreplace_errors(exception)
Georg Brandl116aa622007-08-15 14:28:22 +0000231
Georg Brandl495f7b52009-10-27 15:28:25 +0000232 Implements the ``backslashreplace`` error handling (for encoding only): the
233 unencodable character is replaced by a backslashed escape sequence.
Georg Brandl116aa622007-08-15 14:28:22 +0000234
235To simplify working with encoded files or stream, the module also defines these
236utility functions:
237
238
239.. function:: open(filename, mode[, encoding[, errors[, buffering]]])
240
241 Open an encoded file using the given *mode* and return a wrapped version
Christian Heimes18c66892008-02-17 13:31:39 +0000242 providing transparent encoding/decoding. The default file mode is ``'r'``
243 meaning to open the file in read mode.
Georg Brandl116aa622007-08-15 14:28:22 +0000244
245 .. note::
246
Georg Brandl30c78d62008-05-11 14:52:00 +0000247 The wrapped version's methods will accept and return strings only. Bytes
248 arguments will be rejected.
Georg Brandl116aa622007-08-15 14:28:22 +0000249
Christian Heimes18c66892008-02-17 13:31:39 +0000250 .. note::
251
252 Files are always opened in binary mode, even if no binary mode was
253 specified. This is done to avoid data loss due to encodings using 8-bit
Georg Brandl30c78d62008-05-11 14:52:00 +0000254 values. This means that no automatic conversion of ``b'\n'`` is done
Christian Heimes18c66892008-02-17 13:31:39 +0000255 on reading and writing.
256
Georg Brandl116aa622007-08-15 14:28:22 +0000257 *encoding* specifies the encoding which is to be used for the file.
258
259 *errors* may be given to define the error handling. It defaults to ``'strict'``
260 which causes a :exc:`ValueError` to be raised in case an encoding error occurs.
261
262 *buffering* has the same meaning as for the built-in :func:`open` function. It
263 defaults to line buffered.
264
265
Georg Brandl0d8f0732009-04-05 22:20:44 +0000266.. function:: EncodedFile(file, data_encoding, file_encoding=None, errors='strict')
Georg Brandl116aa622007-08-15 14:28:22 +0000267
268 Return a wrapped version of file which provides transparent encoding
269 translation.
270
Georg Brandl30c78d62008-05-11 14:52:00 +0000271 Bytes written to the wrapped file are interpreted according to the given
Georg Brandl0d8f0732009-04-05 22:20:44 +0000272 *data_encoding* and then written to the original file as bytes using the
273 *file_encoding*.
Georg Brandl116aa622007-08-15 14:28:22 +0000274
Georg Brandl0d8f0732009-04-05 22:20:44 +0000275 If *file_encoding* is not given, it defaults to *data_encoding*.
Georg Brandl116aa622007-08-15 14:28:22 +0000276
Georg Brandl0d8f0732009-04-05 22:20:44 +0000277 *errors* may be given to define the error handling. It defaults to
278 ``'strict'``, which causes :exc:`ValueError` to be raised in case an encoding
279 error occurs.
Georg Brandl116aa622007-08-15 14:28:22 +0000280
281
Georg Brandl0d8f0732009-04-05 22:20:44 +0000282.. function:: iterencode(iterator, encoding, errors='strict', **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +0000283
284 Uses an incremental encoder to iteratively encode the input provided by
Georg Brandl0d8f0732009-04-05 22:20:44 +0000285 *iterator*. This function is a :term:`generator`. *errors* (as well as any
Georg Brandl9afde1c2007-11-01 20:32:30 +0000286 other keyword argument) is passed through to the incremental encoder.
Georg Brandl116aa622007-08-15 14:28:22 +0000287
Georg Brandl116aa622007-08-15 14:28:22 +0000288
Georg Brandl0d8f0732009-04-05 22:20:44 +0000289.. function:: iterdecode(iterator, encoding, errors='strict', **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +0000290
291 Uses an incremental decoder to iteratively decode the input provided by
Georg Brandl0d8f0732009-04-05 22:20:44 +0000292 *iterator*. This function is a :term:`generator`. *errors* (as well as any
Georg Brandl9afde1c2007-11-01 20:32:30 +0000293 other keyword argument) is passed through to the incremental decoder.
Georg Brandl116aa622007-08-15 14:28:22 +0000294
Georg Brandl0d8f0732009-04-05 22:20:44 +0000295
Georg Brandl116aa622007-08-15 14:28:22 +0000296The module also provides the following constants which are useful for reading
297and writing to platform dependent files:
298
299
300.. data:: BOM
301 BOM_BE
302 BOM_LE
303 BOM_UTF8
304 BOM_UTF16
305 BOM_UTF16_BE
306 BOM_UTF16_LE
307 BOM_UTF32
308 BOM_UTF32_BE
309 BOM_UTF32_LE
310
311 These constants define various encodings of the Unicode byte order mark (BOM)
312 used in UTF-16 and UTF-32 data streams to indicate the byte order used in the
313 stream or file and in UTF-8 as a Unicode signature. :const:`BOM_UTF16` is either
314 :const:`BOM_UTF16_BE` or :const:`BOM_UTF16_LE` depending on the platform's
315 native byte order, :const:`BOM` is an alias for :const:`BOM_UTF16`,
316 :const:`BOM_LE` for :const:`BOM_UTF16_LE` and :const:`BOM_BE` for
317 :const:`BOM_UTF16_BE`. The others represent the BOM in UTF-8 and UTF-32
318 encodings.
319
320
321.. _codec-base-classes:
322
323Codec Base Classes
324------------------
325
326The :mod:`codecs` module defines a set of base classes which define the
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000327interface and can also be used to easily write your own codecs for use in
328Python.
Georg Brandl116aa622007-08-15 14:28:22 +0000329
330Each codec has to define four interfaces to make it usable as codec in Python:
331stateless encoder, stateless decoder, stream reader and stream writer. The
332stream reader and writers typically reuse the stateless encoder/decoder to
333implement the file protocols.
334
335The :class:`Codec` class defines the interface for stateless encoders/decoders.
336
Serhiy Storchakabfdcd432013-10-13 23:09:14 +0300337To simplify and standardize error handling, the :meth:`~Codec.encode` and
338:meth:`~Codec.decode` methods may implement different error handling schemes by
Georg Brandl116aa622007-08-15 14:28:22 +0000339providing the *errors* string argument. The following string values are defined
340and implemented by all standard Python codecs:
341
Georg Brandl44ea77b2013-03-28 13:28:44 +0100342.. tabularcolumns:: |l|L|
343
Georg Brandl116aa622007-08-15 14:28:22 +0000344+-------------------------+-----------------------------------------------+
345| Value | Meaning |
346+=========================+===============================================+
347| ``'strict'`` | Raise :exc:`UnicodeError` (or a subclass); |
348| | this is the default. |
349+-------------------------+-----------------------------------------------+
350| ``'ignore'`` | Ignore the character and continue with the |
351| | next. |
352+-------------------------+-----------------------------------------------+
353| ``'replace'`` | Replace with a suitable replacement |
354| | character; Python will use the official |
355| | U+FFFD REPLACEMENT CHARACTER for the built-in |
356| | Unicode codecs on decoding and '?' on |
357| | encoding. |
358+-------------------------+-----------------------------------------------+
359| ``'xmlcharrefreplace'`` | Replace with the appropriate XML character |
360| | reference (only for encoding). |
361+-------------------------+-----------------------------------------------+
362| ``'backslashreplace'`` | Replace with backslashed escape sequences |
363| | (only for encoding). |
364+-------------------------+-----------------------------------------------+
Martin v. Löwis3d2eca02009-06-29 06:35:26 +0000365| ``'surrogateescape'`` | Replace byte with surrogate U+DCxx, as defined|
366| | in :pep:`383`. |
Martin v. Löwis011e8422009-05-05 04:43:17 +0000367+-------------------------+-----------------------------------------------+
Georg Brandl116aa622007-08-15 14:28:22 +0000368
Serhiy Storchaka58cf6072013-11-19 11:32:41 +0200369In addition, the following error handlers are specific to Unicode encoding
370schemes:
Martin v. Löwisdb12d452009-05-02 18:52:14 +0000371
Serhiy Storchaka58cf6072013-11-19 11:32:41 +0200372+-------------------+------------------------+-------------------------------------------+
373| Value | Codec | Meaning |
374+===================+========================+===========================================+
375|``'surrogatepass'``| utf-8, utf-16, utf-32, | Allow encoding and decoding of surrogate |
376| | utf-16-be, utf-16-le, | codes in all the Unicode encoding schemes.|
377| | utf-32-be, utf-32-le | |
378+-------------------+------------------------+-------------------------------------------+
Martin v. Löwisdb12d452009-05-02 18:52:14 +0000379
380.. versionadded:: 3.1
Martin v. Löwis43c57782009-05-10 08:15:24 +0000381 The ``'surrogateescape'`` and ``'surrogatepass'`` error handlers.
Martin v. Löwisdb12d452009-05-02 18:52:14 +0000382
Serhiy Storchaka58cf6072013-11-19 11:32:41 +0200383.. versionchanged:: 3.4
384 The ``'surrogatepass'`` error handlers now works with utf-16\* and utf-32\* codecs.
385
Georg Brandl116aa622007-08-15 14:28:22 +0000386The set of allowed values can be extended via :meth:`register_error`.
387
388
389.. _codec-objects:
390
391Codec Objects
392^^^^^^^^^^^^^
393
394The :class:`Codec` class defines these methods which also define the function
395interfaces of the stateless encoder and decoder:
396
397
398.. method:: Codec.encode(input[, errors])
399
400 Encodes the object *input* and returns a tuple (output object, length consumed).
Georg Brandl30c78d62008-05-11 14:52:00 +0000401 Encoding converts a string object to a bytes object using a particular
Georg Brandl116aa622007-08-15 14:28:22 +0000402 character set encoding (e.g., ``cp1252`` or ``iso-8859-1``).
403
404 *errors* defines the error handling to apply. It defaults to ``'strict'``
405 handling.
406
407 The method may not store state in the :class:`Codec` instance. Use
408 :class:`StreamCodec` for codecs which have to keep state in order to make
409 encoding/decoding efficient.
410
411 The encoder must be able to handle zero length input and return an empty object
412 of the output object type in this situation.
413
414
415.. method:: Codec.decode(input[, errors])
416
Georg Brandl30c78d62008-05-11 14:52:00 +0000417 Decodes the object *input* and returns a tuple (output object, length
418 consumed). Decoding converts a bytes object encoded using a particular
419 character set encoding to a string object.
Georg Brandl116aa622007-08-15 14:28:22 +0000420
Georg Brandl30c78d62008-05-11 14:52:00 +0000421 *input* must be a bytes object or one which provides the read-only character
422 buffer interface -- for example, buffer objects and memory mapped files.
Georg Brandl116aa622007-08-15 14:28:22 +0000423
424 *errors* defines the error handling to apply. It defaults to ``'strict'``
425 handling.
426
427 The method may not store state in the :class:`Codec` instance. Use
428 :class:`StreamCodec` for codecs which have to keep state in order to make
429 encoding/decoding efficient.
430
431 The decoder must be able to handle zero length input and return an empty object
432 of the output object type in this situation.
433
434The :class:`IncrementalEncoder` and :class:`IncrementalDecoder` classes provide
435the basic interface for incremental encoding and decoding. Encoding/decoding the
436input isn't done with one call to the stateless encoder/decoder function, but
Serhiy Storchakabfdcd432013-10-13 23:09:14 +0300437with multiple calls to the
438:meth:`~IncrementalEncoder.encode`/:meth:`~IncrementalDecoder.decode` method of
439the incremental encoder/decoder. The incremental encoder/decoder keeps track of
440the encoding/decoding process during method calls.
Georg Brandl116aa622007-08-15 14:28:22 +0000441
Serhiy Storchakabfdcd432013-10-13 23:09:14 +0300442The joined output of calls to the
443:meth:`~IncrementalEncoder.encode`/:meth:`~IncrementalDecoder.decode` method is
444the same as if all the single inputs were joined into one, and this input was
Georg Brandl116aa622007-08-15 14:28:22 +0000445encoded/decoded with the stateless encoder/decoder.
446
447
448.. _incremental-encoder-objects:
449
450IncrementalEncoder Objects
451^^^^^^^^^^^^^^^^^^^^^^^^^^
452
Georg Brandl116aa622007-08-15 14:28:22 +0000453The :class:`IncrementalEncoder` class is used for encoding an input in multiple
454steps. It defines the following methods which every incremental encoder must
455define in order to be compatible with the Python codec registry.
456
457
458.. class:: IncrementalEncoder([errors])
459
460 Constructor for an :class:`IncrementalEncoder` instance.
461
462 All incremental encoders must provide this constructor interface. They are free
463 to add additional keyword arguments, but only the ones defined here are used by
464 the Python codec registry.
465
466 The :class:`IncrementalEncoder` may implement different error handling schemes
467 by providing the *errors* keyword argument. These parameters are predefined:
468
469 * ``'strict'`` Raise :exc:`ValueError` (or a subclass); this is the default.
470
471 * ``'ignore'`` Ignore the character and continue with the next.
472
473 * ``'replace'`` Replace with a suitable replacement character
474
475 * ``'xmlcharrefreplace'`` Replace with the appropriate XML character reference
476
477 * ``'backslashreplace'`` Replace with backslashed escape sequences.
478
479 The *errors* argument will be assigned to an attribute of the same name.
480 Assigning to this attribute makes it possible to switch between different error
481 handling strategies during the lifetime of the :class:`IncrementalEncoder`
482 object.
483
484 The set of allowed values for the *errors* argument can be extended with
485 :func:`register_error`.
486
487
Benjamin Petersone41251e2008-04-25 01:59:09 +0000488 .. method:: encode(object[, final])
Georg Brandl116aa622007-08-15 14:28:22 +0000489
Benjamin Petersone41251e2008-04-25 01:59:09 +0000490 Encodes *object* (taking the current state of the encoder into account)
491 and returns the resulting encoded object. If this is the last call to
492 :meth:`encode` *final* must be true (the default is false).
Georg Brandl116aa622007-08-15 14:28:22 +0000493
494
Benjamin Petersone41251e2008-04-25 01:59:09 +0000495 .. method:: reset()
Georg Brandl116aa622007-08-15 14:28:22 +0000496
Victor Stinnere15dce32011-05-30 22:56:00 +0200497 Reset the encoder to the initial state. The output is discarded: call
498 ``.encode('', final=True)`` to reset the encoder and to get the output.
Georg Brandl116aa622007-08-15 14:28:22 +0000499
500
501.. method:: IncrementalEncoder.getstate()
502
503 Return the current state of the encoder which must be an integer. The
504 implementation should make sure that ``0`` is the most common state. (States
505 that are more complicated than integers can be converted into an integer by
506 marshaling/pickling the state and encoding the bytes of the resulting string
507 into an integer).
508
Georg Brandl116aa622007-08-15 14:28:22 +0000509
510.. method:: IncrementalEncoder.setstate(state)
511
512 Set the state of the encoder to *state*. *state* must be an encoder state
513 returned by :meth:`getstate`.
514
Georg Brandl116aa622007-08-15 14:28:22 +0000515
516.. _incremental-decoder-objects:
517
518IncrementalDecoder Objects
519^^^^^^^^^^^^^^^^^^^^^^^^^^
520
521The :class:`IncrementalDecoder` class is used for decoding an input in multiple
522steps. It defines the following methods which every incremental decoder must
523define in order to be compatible with the Python codec registry.
524
525
526.. class:: IncrementalDecoder([errors])
527
528 Constructor for an :class:`IncrementalDecoder` instance.
529
530 All incremental decoders must provide this constructor interface. They are free
531 to add additional keyword arguments, but only the ones defined here are used by
532 the Python codec registry.
533
534 The :class:`IncrementalDecoder` may implement different error handling schemes
535 by providing the *errors* keyword argument. These parameters are predefined:
536
537 * ``'strict'`` Raise :exc:`ValueError` (or a subclass); this is the default.
538
539 * ``'ignore'`` Ignore the character and continue with the next.
540
541 * ``'replace'`` Replace with a suitable replacement character.
542
543 The *errors* argument will be assigned to an attribute of the same name.
544 Assigning to this attribute makes it possible to switch between different error
Benjamin Peterson3e4f0552008-09-02 00:31:15 +0000545 handling strategies during the lifetime of the :class:`IncrementalDecoder`
Georg Brandl116aa622007-08-15 14:28:22 +0000546 object.
547
548 The set of allowed values for the *errors* argument can be extended with
549 :func:`register_error`.
550
551
Benjamin Petersone41251e2008-04-25 01:59:09 +0000552 .. method:: decode(object[, final])
Georg Brandl116aa622007-08-15 14:28:22 +0000553
Benjamin Petersone41251e2008-04-25 01:59:09 +0000554 Decodes *object* (taking the current state of the decoder into account)
555 and returns the resulting decoded object. If this is the last call to
556 :meth:`decode` *final* must be true (the default is false). If *final* is
557 true the decoder must decode the input completely and must flush all
558 buffers. If this isn't possible (e.g. because of incomplete byte sequences
559 at the end of the input) it must initiate error handling just like in the
560 stateless case (which might raise an exception).
Georg Brandl116aa622007-08-15 14:28:22 +0000561
562
Benjamin Petersone41251e2008-04-25 01:59:09 +0000563 .. method:: reset()
Georg Brandl116aa622007-08-15 14:28:22 +0000564
Benjamin Petersone41251e2008-04-25 01:59:09 +0000565 Reset the decoder to the initial state.
Georg Brandl116aa622007-08-15 14:28:22 +0000566
567
Benjamin Petersone41251e2008-04-25 01:59:09 +0000568 .. method:: getstate()
Georg Brandl116aa622007-08-15 14:28:22 +0000569
Benjamin Petersone41251e2008-04-25 01:59:09 +0000570 Return the current state of the decoder. This must be a tuple with two
571 items, the first must be the buffer containing the still undecoded
572 input. The second must be an integer and can be additional state
573 info. (The implementation should make sure that ``0`` is the most common
574 additional state info.) If this additional state info is ``0`` it must be
575 possible to set the decoder to the state which has no input buffered and
576 ``0`` as the additional state info, so that feeding the previously
577 buffered input to the decoder returns it to the previous state without
578 producing any output. (Additional state info that is more complicated than
579 integers can be converted into an integer by marshaling/pickling the info
580 and encoding the bytes of the resulting string into an integer.)
Georg Brandl116aa622007-08-15 14:28:22 +0000581
Georg Brandl116aa622007-08-15 14:28:22 +0000582
Benjamin Petersone41251e2008-04-25 01:59:09 +0000583 .. method:: setstate(state)
Georg Brandl116aa622007-08-15 14:28:22 +0000584
Benjamin Petersone41251e2008-04-25 01:59:09 +0000585 Set the state of the encoder to *state*. *state* must be a decoder state
586 returned by :meth:`getstate`.
587
Georg Brandl116aa622007-08-15 14:28:22 +0000588
Georg Brandl116aa622007-08-15 14:28:22 +0000589The :class:`StreamWriter` and :class:`StreamReader` classes provide generic
590working interfaces which can be used to implement new encoding submodules very
591easily. See :mod:`encodings.utf_8` for an example of how this is done.
592
593
594.. _stream-writer-objects:
595
596StreamWriter Objects
597^^^^^^^^^^^^^^^^^^^^
598
599The :class:`StreamWriter` class is a subclass of :class:`Codec` and defines the
600following methods which every stream writer must define in order to be
601compatible with the Python codec registry.
602
603
604.. class:: StreamWriter(stream[, errors])
605
606 Constructor for a :class:`StreamWriter` instance.
607
608 All stream writers must provide this constructor interface. They are free to add
609 additional keyword arguments, but only the ones defined here are used by the
610 Python codec registry.
611
612 *stream* must be a file-like object open for writing binary data.
613
614 The :class:`StreamWriter` may implement different error handling schemes by
615 providing the *errors* keyword argument. These parameters are predefined:
616
617 * ``'strict'`` Raise :exc:`ValueError` (or a subclass); this is the default.
618
619 * ``'ignore'`` Ignore the character and continue with the next.
620
621 * ``'replace'`` Replace with a suitable replacement character
622
623 * ``'xmlcharrefreplace'`` Replace with the appropriate XML character reference
624
625 * ``'backslashreplace'`` Replace with backslashed escape sequences.
626
627 The *errors* argument will be assigned to an attribute of the same name.
628 Assigning to this attribute makes it possible to switch between different error
629 handling strategies during the lifetime of the :class:`StreamWriter` object.
630
631 The set of allowed values for the *errors* argument can be extended with
632 :func:`register_error`.
633
634
Benjamin Petersone41251e2008-04-25 01:59:09 +0000635 .. method:: write(object)
Georg Brandl116aa622007-08-15 14:28:22 +0000636
Benjamin Petersone41251e2008-04-25 01:59:09 +0000637 Writes the object's contents encoded to the stream.
Georg Brandl116aa622007-08-15 14:28:22 +0000638
639
Benjamin Petersone41251e2008-04-25 01:59:09 +0000640 .. method:: writelines(list)
Georg Brandl116aa622007-08-15 14:28:22 +0000641
Benjamin Petersone41251e2008-04-25 01:59:09 +0000642 Writes the concatenated list of strings to the stream (possibly by reusing
643 the :meth:`write` method).
Georg Brandl116aa622007-08-15 14:28:22 +0000644
645
Benjamin Petersone41251e2008-04-25 01:59:09 +0000646 .. method:: reset()
Georg Brandl116aa622007-08-15 14:28:22 +0000647
Benjamin Petersone41251e2008-04-25 01:59:09 +0000648 Flushes and resets the codec buffers used for keeping state.
Georg Brandl116aa622007-08-15 14:28:22 +0000649
Benjamin Petersone41251e2008-04-25 01:59:09 +0000650 Calling this method should ensure that the data on the output is put into
651 a clean state that allows appending of new fresh data without having to
652 rescan the whole stream to recover state.
653
Georg Brandl116aa622007-08-15 14:28:22 +0000654
655In addition to the above methods, the :class:`StreamWriter` must also inherit
656all other methods and attributes from the underlying stream.
657
658
659.. _stream-reader-objects:
660
661StreamReader Objects
662^^^^^^^^^^^^^^^^^^^^
663
664The :class:`StreamReader` class is a subclass of :class:`Codec` and defines the
665following methods which every stream reader must define in order to be
666compatible with the Python codec registry.
667
668
669.. class:: StreamReader(stream[, errors])
670
671 Constructor for a :class:`StreamReader` instance.
672
673 All stream readers must provide this constructor interface. They are free to add
674 additional keyword arguments, but only the ones defined here are used by the
675 Python codec registry.
676
677 *stream* must be a file-like object open for reading (binary) data.
678
679 The :class:`StreamReader` may implement different error handling schemes by
680 providing the *errors* keyword argument. These parameters are defined:
681
682 * ``'strict'`` Raise :exc:`ValueError` (or a subclass); this is the default.
683
684 * ``'ignore'`` Ignore the character and continue with the next.
685
686 * ``'replace'`` Replace with a suitable replacement character.
687
688 The *errors* argument will be assigned to an attribute of the same name.
689 Assigning to this attribute makes it possible to switch between different error
690 handling strategies during the lifetime of the :class:`StreamReader` object.
691
692 The set of allowed values for the *errors* argument can be extended with
693 :func:`register_error`.
694
695
Benjamin Petersone41251e2008-04-25 01:59:09 +0000696 .. method:: read([size[, chars, [firstline]]])
Georg Brandl116aa622007-08-15 14:28:22 +0000697
Benjamin Petersone41251e2008-04-25 01:59:09 +0000698 Decodes data from the stream and returns the resulting object.
Georg Brandl116aa622007-08-15 14:28:22 +0000699
Benjamin Petersone41251e2008-04-25 01:59:09 +0000700 *chars* indicates the number of characters to read from the
701 stream. :func:`read` will never return more than *chars* characters, but
702 it might return less, if there are not enough characters available.
Georg Brandl116aa622007-08-15 14:28:22 +0000703
Benjamin Petersone41251e2008-04-25 01:59:09 +0000704 *size* indicates the approximate maximum number of bytes to read from the
705 stream for decoding purposes. The decoder can modify this setting as
706 appropriate. The default value -1 indicates to read and decode as much as
707 possible. *size* is intended to prevent having to decode huge files in
708 one step.
Georg Brandl116aa622007-08-15 14:28:22 +0000709
Benjamin Petersone41251e2008-04-25 01:59:09 +0000710 *firstline* indicates that it would be sufficient to only return the first
711 line, if there are decoding errors on later lines.
Georg Brandl116aa622007-08-15 14:28:22 +0000712
Benjamin Petersone41251e2008-04-25 01:59:09 +0000713 The method should use a greedy read strategy meaning that it should read
714 as much data as is allowed within the definition of the encoding and the
715 given size, e.g. if optional encoding endings or state markers are
716 available on the stream, these should be read too.
Georg Brandl116aa622007-08-15 14:28:22 +0000717
Georg Brandl116aa622007-08-15 14:28:22 +0000718
Benjamin Petersone41251e2008-04-25 01:59:09 +0000719 .. method:: readline([size[, keepends]])
Georg Brandl116aa622007-08-15 14:28:22 +0000720
Benjamin Petersone41251e2008-04-25 01:59:09 +0000721 Read one line from the input stream and return the decoded data.
Georg Brandl116aa622007-08-15 14:28:22 +0000722
Benjamin Petersone41251e2008-04-25 01:59:09 +0000723 *size*, if given, is passed as size argument to the stream's
Serhiy Storchakacca40ff2013-07-11 18:26:13 +0300724 :meth:`read` method.
Georg Brandl116aa622007-08-15 14:28:22 +0000725
Benjamin Petersone41251e2008-04-25 01:59:09 +0000726 If *keepends* is false line-endings will be stripped from the lines
727 returned.
Georg Brandl116aa622007-08-15 14:28:22 +0000728
Georg Brandl116aa622007-08-15 14:28:22 +0000729
Benjamin Petersone41251e2008-04-25 01:59:09 +0000730 .. method:: readlines([sizehint[, keepends]])
Georg Brandl116aa622007-08-15 14:28:22 +0000731
Benjamin Petersone41251e2008-04-25 01:59:09 +0000732 Read all lines available on the input stream and return them as a list of
733 lines.
Georg Brandl116aa622007-08-15 14:28:22 +0000734
Benjamin Petersone41251e2008-04-25 01:59:09 +0000735 Line-endings are implemented using the codec's decoder method and are
736 included in the list entries if *keepends* is true.
Georg Brandl116aa622007-08-15 14:28:22 +0000737
Benjamin Petersone41251e2008-04-25 01:59:09 +0000738 *sizehint*, if given, is passed as the *size* argument to the stream's
739 :meth:`read` method.
Georg Brandl116aa622007-08-15 14:28:22 +0000740
741
Benjamin Petersone41251e2008-04-25 01:59:09 +0000742 .. method:: reset()
Georg Brandl116aa622007-08-15 14:28:22 +0000743
Benjamin Petersone41251e2008-04-25 01:59:09 +0000744 Resets the codec buffers used for keeping state.
Georg Brandl116aa622007-08-15 14:28:22 +0000745
Benjamin Petersone41251e2008-04-25 01:59:09 +0000746 Note that no stream repositioning should take place. This method is
747 primarily intended to be able to recover from decoding errors.
748
Georg Brandl116aa622007-08-15 14:28:22 +0000749
750In addition to the above methods, the :class:`StreamReader` must also inherit
751all other methods and attributes from the underlying stream.
752
753The next two base classes are included for convenience. They are not needed by
754the codec registry, but may provide useful in practice.
755
756
757.. _stream-reader-writer:
758
759StreamReaderWriter Objects
760^^^^^^^^^^^^^^^^^^^^^^^^^^
761
762The :class:`StreamReaderWriter` allows wrapping streams which work in both read
763and write modes.
764
765The design is such that one can use the factory functions returned by the
766:func:`lookup` function to construct the instance.
767
768
769.. class:: StreamReaderWriter(stream, Reader, Writer, errors)
770
771 Creates a :class:`StreamReaderWriter` instance. *stream* must be a file-like
772 object. *Reader* and *Writer* must be factory functions or classes providing the
773 :class:`StreamReader` and :class:`StreamWriter` interface resp. Error handling
774 is done in the same way as defined for the stream readers and writers.
775
776:class:`StreamReaderWriter` instances define the combined interfaces of
777:class:`StreamReader` and :class:`StreamWriter` classes. They inherit all other
778methods and attributes from the underlying stream.
779
780
781.. _stream-recoder-objects:
782
783StreamRecoder Objects
784^^^^^^^^^^^^^^^^^^^^^
785
786The :class:`StreamRecoder` provide a frontend - backend view of encoding data
787which is sometimes useful when dealing with different encoding environments.
788
789The design is such that one can use the factory functions returned by the
790:func:`lookup` function to construct the instance.
791
792
793.. class:: StreamRecoder(stream, encode, decode, Reader, Writer, errors)
794
795 Creates a :class:`StreamRecoder` instance which implements a two-way conversion:
796 *encode* and *decode* work on the frontend (the input to :meth:`read` and output
797 of :meth:`write`) while *Reader* and *Writer* work on the backend (reading and
798 writing to the stream).
799
800 You can use these objects to do transparent direct recodings from e.g. Latin-1
801 to UTF-8 and back.
802
803 *stream* must be a file-like object.
804
805 *encode*, *decode* must adhere to the :class:`Codec` interface. *Reader*,
806 *Writer* must be factory functions or classes providing objects of the
807 :class:`StreamReader` and :class:`StreamWriter` interface respectively.
808
809 *encode* and *decode* are needed for the frontend translation, *Reader* and
Georg Brandl30c78d62008-05-11 14:52:00 +0000810 *Writer* for the backend translation.
Georg Brandl116aa622007-08-15 14:28:22 +0000811
812 Error handling is done in the same way as defined for the stream readers and
813 writers.
814
Benjamin Petersone41251e2008-04-25 01:59:09 +0000815
Georg Brandl116aa622007-08-15 14:28:22 +0000816:class:`StreamRecoder` instances define the combined interfaces of
817:class:`StreamReader` and :class:`StreamWriter` classes. They inherit all other
818methods and attributes from the underlying stream.
819
820
821.. _encodings-overview:
822
823Encodings and Unicode
824---------------------
825
Ezio Melotti7a03f642011-10-25 10:30:19 +0300826Strings are stored internally as sequences of codepoints in range ``0 - 10FFFF``
827(see :pep:`393` for more details about the implementation).
828Once a string object is used outside of CPU and memory, CPU endianness
Georg Brandl116aa622007-08-15 14:28:22 +0000829and how these arrays are stored as bytes become an issue. Transforming a
Georg Brandl30c78d62008-05-11 14:52:00 +0000830string object into a sequence of bytes is called encoding and recreating the
831string object from the sequence of bytes is known as decoding. There are many
Georg Brandl116aa622007-08-15 14:28:22 +0000832different methods for how this transformation can be done (these methods are
833also called encodings). The simplest method is to map the codepoints 0-255 to
Georg Brandl30c78d62008-05-11 14:52:00 +0000834the bytes ``0x0``-``0xff``. This means that a string object that contains
Georg Brandl116aa622007-08-15 14:28:22 +0000835codepoints above ``U+00FF`` can't be encoded with this method (which is called
Georg Brandl30c78d62008-05-11 14:52:00 +0000836``'latin-1'`` or ``'iso-8859-1'``). :func:`str.encode` will raise a
Georg Brandl116aa622007-08-15 14:28:22 +0000837:exc:`UnicodeEncodeError` that looks like this: ``UnicodeEncodeError: 'latin-1'
Georg Brandl30c78d62008-05-11 14:52:00 +0000838codec can't encode character '\u1234' in position 3: ordinal not in
Georg Brandl116aa622007-08-15 14:28:22 +0000839range(256)``.
840
841There's another group of encodings (the so called charmap encodings) that choose
Georg Brandl30c78d62008-05-11 14:52:00 +0000842a different subset of all Unicode code points and how these codepoints are
Georg Brandl116aa622007-08-15 14:28:22 +0000843mapped to the bytes ``0x0``-``0xff``. To see how this is done simply open
844e.g. :file:`encodings/cp1252.py` (which is an encoding that is used primarily on
845Windows). There's a string constant with 256 characters that shows you which
846character is mapped to which byte value.
847
Ezio Melottifbb39812011-10-25 10:40:38 +0300848All of these encodings can only encode 256 of the 1114112 codepoints
Georg Brandl30c78d62008-05-11 14:52:00 +0000849defined in Unicode. A simple and straightforward way that can store each Unicode
Ezio Melottifbb39812011-10-25 10:40:38 +0300850code point, is to store each codepoint as four consecutive bytes. There are two
851possibilities: store the bytes in big endian or in little endian order. These
852two encodings are called ``UTF-32-BE`` and ``UTF-32-LE`` respectively. Their
853disadvantage is that if e.g. you use ``UTF-32-BE`` on a little endian machine you
854will always have to swap bytes on encoding and decoding. ``UTF-32`` avoids this
855problem: bytes will always be in natural endianness. When these bytes are read
Georg Brandl116aa622007-08-15 14:28:22 +0000856by a CPU with a different endianness, then bytes have to be swapped though. To
Ezio Melottifbb39812011-10-25 10:40:38 +0300857be able to detect the endianness of a ``UTF-16`` or ``UTF-32`` byte sequence,
858there's the so called BOM ("Byte Order Mark"). This is the Unicode character
859``U+FEFF``. This character can be prepended to every ``UTF-16`` or ``UTF-32``
860byte sequence. The byte swapped version of this character (``0xFFFE``) is an
861illegal character that may not appear in a Unicode text. So when the
862first character in an ``UTF-16`` or ``UTF-32`` byte sequence
Georg Brandl116aa622007-08-15 14:28:22 +0000863appears to be a ``U+FFFE`` the bytes have to be swapped on decoding.
Ezio Melottifbb39812011-10-25 10:40:38 +0300864Unfortunately the character ``U+FEFF`` had a second purpose as
865a ``ZERO WIDTH NO-BREAK SPACE``: a character that has no width and doesn't allow
Georg Brandl116aa622007-08-15 14:28:22 +0000866a word to be split. It can e.g. be used to give hints to a ligature algorithm.
867With Unicode 4.0 using ``U+FEFF`` as a ``ZERO WIDTH NO-BREAK SPACE`` has been
868deprecated (with ``U+2060`` (``WORD JOINER``) assuming this role). Nevertheless
Ezio Melottifbb39812011-10-25 10:40:38 +0300869Unicode software still must be able to handle ``U+FEFF`` in both roles: as a BOM
Georg Brandl116aa622007-08-15 14:28:22 +0000870it's a device to determine the storage layout of the encoded bytes, and vanishes
Georg Brandl30c78d62008-05-11 14:52:00 +0000871once the byte sequence has been decoded into a string; as a ``ZERO WIDTH
Georg Brandl116aa622007-08-15 14:28:22 +0000872NO-BREAK SPACE`` it's a normal character that will be decoded like any other.
873
874There's another encoding that is able to encoding the full range of Unicode
875characters: UTF-8. UTF-8 is an 8-bit encoding, which means there are no issues
876with byte order in UTF-8. Each byte in a UTF-8 byte sequence consists of two
Ezio Melottifbb39812011-10-25 10:40:38 +0300877parts: marker bits (the most significant bits) and payload bits. The marker bits
Ezio Melotti222b2082011-09-01 08:11:28 +0300878are a sequence of zero to four ``1`` bits followed by a ``0`` bit. Unicode characters are
Georg Brandl116aa622007-08-15 14:28:22 +0000879encoded like this (with x being payload bits, which when concatenated give the
880Unicode character):
881
882+-----------------------------------+----------------------------------------------+
883| Range | Encoding |
884+===================================+==============================================+
885| ``U-00000000`` ... ``U-0000007F`` | 0xxxxxxx |
886+-----------------------------------+----------------------------------------------+
887| ``U-00000080`` ... ``U-000007FF`` | 110xxxxx 10xxxxxx |
888+-----------------------------------+----------------------------------------------+
889| ``U-00000800`` ... ``U-0000FFFF`` | 1110xxxx 10xxxxxx 10xxxxxx |
890+-----------------------------------+----------------------------------------------+
Ezio Melotti222b2082011-09-01 08:11:28 +0300891| ``U-00010000`` ... ``U-0010FFFF`` | 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx |
Georg Brandl116aa622007-08-15 14:28:22 +0000892+-----------------------------------+----------------------------------------------+
893
894The least significant bit of the Unicode character is the rightmost x bit.
895
896As UTF-8 is an 8-bit encoding no BOM is required and any ``U+FEFF`` character in
Georg Brandl30c78d62008-05-11 14:52:00 +0000897the decoded string (even if it's the first character) is treated as a ``ZERO
898WIDTH NO-BREAK SPACE``.
Georg Brandl116aa622007-08-15 14:28:22 +0000899
900Without external information it's impossible to reliably determine which
Georg Brandl30c78d62008-05-11 14:52:00 +0000901encoding was used for encoding a string. Each charmap encoding can
Georg Brandl116aa622007-08-15 14:28:22 +0000902decode any random byte sequence. However that's not possible with UTF-8, as
903UTF-8 byte sequences have a structure that doesn't allow arbitrary byte
Thomas Wouters89d996e2007-09-08 17:39:28 +0000904sequences. To increase the reliability with which a UTF-8 encoding can be
Georg Brandl116aa622007-08-15 14:28:22 +0000905detected, Microsoft invented a variant of UTF-8 (that Python 2.5 calls
906``"utf-8-sig"``) for its Notepad program: Before any of the Unicode characters
907is written to the file, a UTF-8 encoded BOM (which looks like this as a byte
908sequence: ``0xef``, ``0xbb``, ``0xbf``) is written. As it's rather improbable
909that any charmap encoded file starts with these byte values (which would e.g.
910map to
911
912 | LATIN SMALL LETTER I WITH DIAERESIS
913 | RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK
914 | INVERTED QUESTION MARK
915
Ezio Melottifbb39812011-10-25 10:40:38 +0300916in iso-8859-1), this increases the probability that a ``utf-8-sig`` encoding can be
Georg Brandl116aa622007-08-15 14:28:22 +0000917correctly guessed from the byte sequence. So here the BOM is not used to be able
918to determine the byte order used for generating the byte sequence, but as a
919signature that helps in guessing the encoding. On encoding the utf-8-sig codec
920will write ``0xef``, ``0xbb``, ``0xbf`` as the first three bytes to the file. On
Ezio Melottifbb39812011-10-25 10:40:38 +0300921decoding ``utf-8-sig`` will skip those three bytes if they appear as the first
922three bytes in the file. In UTF-8, the use of the BOM is discouraged and
923should generally be avoided.
Georg Brandl116aa622007-08-15 14:28:22 +0000924
925
926.. _standard-encodings:
927
928Standard Encodings
929------------------
930
931Python comes with a number of codecs built-in, either implemented as C functions
932or with dictionaries as mapping tables. The following table lists the codecs by
933name, together with a few common aliases, and the languages for which the
934encoding is likely used. Neither the list of aliases nor the list of languages
935is meant to be exhaustive. Notice that spelling alternatives that only differ in
Georg Brandla6053b42009-09-01 08:11:14 +0000936case or use a hyphen instead of an underscore are also valid aliases; therefore,
937e.g. ``'utf-8'`` is a valid alias for the ``'utf_8'`` codec.
Georg Brandl116aa622007-08-15 14:28:22 +0000938
Alexander Belopolsky1d521462011-02-25 19:19:57 +0000939.. impl-detail::
940
941 Some common encodings can bypass the codecs lookup machinery to
942 improve performance. These optimization opportunities are only
943 recognized by CPython for a limited set of aliases: utf-8, utf8,
944 latin-1, latin1, iso-8859-1, mbcs (Windows only), ascii, utf-16,
945 and utf-32. Using alternative spellings for these encodings may
946 result in slower execution.
947
Georg Brandl116aa622007-08-15 14:28:22 +0000948Many of the character sets support the same languages. They vary in individual
949characters (e.g. whether the EURO SIGN is supported or not), and in the
950assignment of characters to code positions. For the European languages in
951particular, the following variants typically exist:
952
953* an ISO 8859 codeset
954
955* a Microsoft Windows code page, which is typically derived from a 8859 codeset,
956 but replaces control characters with additional graphic characters
957
958* an IBM EBCDIC code page
959
960* an IBM PC code page, which is ASCII compatible
961
Georg Brandl44ea77b2013-03-28 13:28:44 +0100962.. tabularcolumns:: |l|p{0.3\linewidth}|p{0.3\linewidth}|
963
Georg Brandl116aa622007-08-15 14:28:22 +0000964+-----------------+--------------------------------+--------------------------------+
965| Codec | Aliases | Languages |
966+=================+================================+================================+
967| ascii | 646, us-ascii | English |
968+-----------------+--------------------------------+--------------------------------+
969| big5 | big5-tw, csbig5 | Traditional Chinese |
970+-----------------+--------------------------------+--------------------------------+
971| big5hkscs | big5-hkscs, hkscs | Traditional Chinese |
972+-----------------+--------------------------------+--------------------------------+
973| cp037 | IBM037, IBM039 | English |
974+-----------------+--------------------------------+--------------------------------+
R David Murray47d083c2014-03-07 21:00:34 -0500975| cp273 | 273, IBM273, csIBM273 | German |
976| | | |
977| | | .. versionadded:: 3.4 |
978+-----------------+--------------------------------+--------------------------------+
Georg Brandl116aa622007-08-15 14:28:22 +0000979| cp424 | EBCDIC-CP-HE, IBM424 | Hebrew |
980+-----------------+--------------------------------+--------------------------------+
981| cp437 | 437, IBM437 | English |
982+-----------------+--------------------------------+--------------------------------+
983| cp500 | EBCDIC-CP-BE, EBCDIC-CP-CH, | Western Europe |
984| | IBM500 | |
985+-----------------+--------------------------------+--------------------------------+
Amaury Forgeot d'Arcae6388d2009-07-15 19:21:18 +0000986| cp720 | | Arabic |
987+-----------------+--------------------------------+--------------------------------+
Georg Brandl116aa622007-08-15 14:28:22 +0000988| cp737 | | Greek |
989+-----------------+--------------------------------+--------------------------------+
990| cp775 | IBM775 | Baltic languages |
991+-----------------+--------------------------------+--------------------------------+
992| cp850 | 850, IBM850 | Western Europe |
993+-----------------+--------------------------------+--------------------------------+
994| cp852 | 852, IBM852 | Central and Eastern Europe |
995+-----------------+--------------------------------+--------------------------------+
996| cp855 | 855, IBM855 | Bulgarian, Byelorussian, |
997| | | Macedonian, Russian, Serbian |
998+-----------------+--------------------------------+--------------------------------+
999| cp856 | | Hebrew |
1000+-----------------+--------------------------------+--------------------------------+
1001| cp857 | 857, IBM857 | Turkish |
1002+-----------------+--------------------------------+--------------------------------+
Benjamin Peterson5a6214a2010-06-27 22:41:29 +00001003| cp858 | 858, IBM858 | Western Europe |
1004+-----------------+--------------------------------+--------------------------------+
Georg Brandl116aa622007-08-15 14:28:22 +00001005| cp860 | 860, IBM860 | Portuguese |
1006+-----------------+--------------------------------+--------------------------------+
1007| cp861 | 861, CP-IS, IBM861 | Icelandic |
1008+-----------------+--------------------------------+--------------------------------+
1009| cp862 | 862, IBM862 | Hebrew |
1010+-----------------+--------------------------------+--------------------------------+
1011| cp863 | 863, IBM863 | Canadian |
1012+-----------------+--------------------------------+--------------------------------+
1013| cp864 | IBM864 | Arabic |
1014+-----------------+--------------------------------+--------------------------------+
1015| cp865 | 865, IBM865 | Danish, Norwegian |
1016+-----------------+--------------------------------+--------------------------------+
1017| cp866 | 866, IBM866 | Russian |
1018+-----------------+--------------------------------+--------------------------------+
1019| cp869 | 869, CP-GR, IBM869 | Greek |
1020+-----------------+--------------------------------+--------------------------------+
1021| cp874 | | Thai |
1022+-----------------+--------------------------------+--------------------------------+
1023| cp875 | | Greek |
1024+-----------------+--------------------------------+--------------------------------+
1025| cp932 | 932, ms932, mskanji, ms-kanji | Japanese |
1026+-----------------+--------------------------------+--------------------------------+
1027| cp949 | 949, ms949, uhc | Korean |
1028+-----------------+--------------------------------+--------------------------------+
1029| cp950 | 950, ms950 | Traditional Chinese |
1030+-----------------+--------------------------------+--------------------------------+
1031| cp1006 | | Urdu |
1032+-----------------+--------------------------------+--------------------------------+
1033| cp1026 | ibm1026 | Turkish |
1034+-----------------+--------------------------------+--------------------------------+
Serhiy Storchakabe0c3252013-11-23 18:52:23 +02001035| cp1125 | 1125, ibm1125, cp866u, ruscii | Ukrainian |
1036| | | |
1037| | | .. versionadded:: 3.4 |
1038+-----------------+--------------------------------+--------------------------------+
Georg Brandl116aa622007-08-15 14:28:22 +00001039| cp1140 | ibm1140 | Western Europe |
1040+-----------------+--------------------------------+--------------------------------+
1041| cp1250 | windows-1250 | Central and Eastern Europe |
1042+-----------------+--------------------------------+--------------------------------+
1043| cp1251 | windows-1251 | Bulgarian, Byelorussian, |
1044| | | Macedonian, Russian, Serbian |
1045+-----------------+--------------------------------+--------------------------------+
1046| cp1252 | windows-1252 | Western Europe |
1047+-----------------+--------------------------------+--------------------------------+
1048| cp1253 | windows-1253 | Greek |
1049+-----------------+--------------------------------+--------------------------------+
1050| cp1254 | windows-1254 | Turkish |
1051+-----------------+--------------------------------+--------------------------------+
1052| cp1255 | windows-1255 | Hebrew |
1053+-----------------+--------------------------------+--------------------------------+
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00001054| cp1256 | windows-1256 | Arabic |
Georg Brandl116aa622007-08-15 14:28:22 +00001055+-----------------+--------------------------------+--------------------------------+
1056| cp1257 | windows-1257 | Baltic languages |
1057+-----------------+--------------------------------+--------------------------------+
1058| cp1258 | windows-1258 | Vietnamese |
1059+-----------------+--------------------------------+--------------------------------+
Victor Stinner2f3ca9f2011-10-27 01:38:56 +02001060| cp65001 | | Windows only: Windows UTF-8 |
1061| | | (``CP_UTF8``) |
1062| | | |
1063| | | .. versionadded:: 3.3 |
1064+-----------------+--------------------------------+--------------------------------+
Georg Brandl116aa622007-08-15 14:28:22 +00001065| euc_jp | eucjp, ujis, u-jis | Japanese |
1066+-----------------+--------------------------------+--------------------------------+
1067| euc_jis_2004 | jisx0213, eucjis2004 | Japanese |
1068+-----------------+--------------------------------+--------------------------------+
1069| euc_jisx0213 | eucjisx0213 | Japanese |
1070+-----------------+--------------------------------+--------------------------------+
1071| euc_kr | euckr, korean, ksc5601, | Korean |
1072| | ks_c-5601, ks_c-5601-1987, | |
1073| | ksx1001, ks_x-1001 | |
1074+-----------------+--------------------------------+--------------------------------+
1075| gb2312 | chinese, csiso58gb231280, euc- | Simplified Chinese |
1076| | cn, euccn, eucgb2312-cn, | |
1077| | gb2312-1980, gb2312-80, iso- | |
1078| | ir-58 | |
1079+-----------------+--------------------------------+--------------------------------+
1080| gbk | 936, cp936, ms936 | Unified Chinese |
1081+-----------------+--------------------------------+--------------------------------+
1082| gb18030 | gb18030-2000 | Unified Chinese |
1083+-----------------+--------------------------------+--------------------------------+
1084| hz | hzgb, hz-gb, hz-gb-2312 | Simplified Chinese |
1085+-----------------+--------------------------------+--------------------------------+
1086| iso2022_jp | csiso2022jp, iso2022jp, | Japanese |
1087| | iso-2022-jp | |
1088+-----------------+--------------------------------+--------------------------------+
1089| iso2022_jp_1 | iso2022jp-1, iso-2022-jp-1 | Japanese |
1090+-----------------+--------------------------------+--------------------------------+
1091| iso2022_jp_2 | iso2022jp-2, iso-2022-jp-2 | Japanese, Korean, Simplified |
1092| | | Chinese, Western Europe, Greek |
1093+-----------------+--------------------------------+--------------------------------+
1094| iso2022_jp_2004 | iso2022jp-2004, | Japanese |
1095| | iso-2022-jp-2004 | |
1096+-----------------+--------------------------------+--------------------------------+
1097| iso2022_jp_3 | iso2022jp-3, iso-2022-jp-3 | Japanese |
1098+-----------------+--------------------------------+--------------------------------+
1099| iso2022_jp_ext | iso2022jp-ext, iso-2022-jp-ext | Japanese |
1100+-----------------+--------------------------------+--------------------------------+
1101| iso2022_kr | csiso2022kr, iso2022kr, | Korean |
1102| | iso-2022-kr | |
1103+-----------------+--------------------------------+--------------------------------+
1104| latin_1 | iso-8859-1, iso8859-1, 8859, | West Europe |
1105| | cp819, latin, latin1, L1 | |
1106+-----------------+--------------------------------+--------------------------------+
1107| iso8859_2 | iso-8859-2, latin2, L2 | Central and Eastern Europe |
1108+-----------------+--------------------------------+--------------------------------+
1109| iso8859_3 | iso-8859-3, latin3, L3 | Esperanto, Maltese |
1110+-----------------+--------------------------------+--------------------------------+
Christian Heimesc3f30c42008-02-22 16:37:40 +00001111| iso8859_4 | iso-8859-4, latin4, L4 | Baltic languages |
Georg Brandl116aa622007-08-15 14:28:22 +00001112+-----------------+--------------------------------+--------------------------------+
1113| iso8859_5 | iso-8859-5, cyrillic | Bulgarian, Byelorussian, |
1114| | | Macedonian, Russian, Serbian |
1115+-----------------+--------------------------------+--------------------------------+
1116| iso8859_6 | iso-8859-6, arabic | Arabic |
1117+-----------------+--------------------------------+--------------------------------+
1118| iso8859_7 | iso-8859-7, greek, greek8 | Greek |
1119+-----------------+--------------------------------+--------------------------------+
1120| iso8859_8 | iso-8859-8, hebrew | Hebrew |
1121+-----------------+--------------------------------+--------------------------------+
1122| iso8859_9 | iso-8859-9, latin5, L5 | Turkish |
1123+-----------------+--------------------------------+--------------------------------+
1124| iso8859_10 | iso-8859-10, latin6, L6 | Nordic languages |
1125+-----------------+--------------------------------+--------------------------------+
Georg Brandl93dc9eb2010-03-14 10:56:14 +00001126| iso8859_13 | iso-8859-13, latin7, L7 | Baltic languages |
Georg Brandl116aa622007-08-15 14:28:22 +00001127+-----------------+--------------------------------+--------------------------------+
1128| iso8859_14 | iso-8859-14, latin8, L8 | Celtic languages |
1129+-----------------+--------------------------------+--------------------------------+
Georg Brandl93dc9eb2010-03-14 10:56:14 +00001130| iso8859_15 | iso-8859-15, latin9, L9 | Western Europe |
1131+-----------------+--------------------------------+--------------------------------+
1132| iso8859_16 | iso-8859-16, latin10, L10 | South-Eastern Europe |
Georg Brandl116aa622007-08-15 14:28:22 +00001133+-----------------+--------------------------------+--------------------------------+
1134| johab | cp1361, ms1361 | Korean |
1135+-----------------+--------------------------------+--------------------------------+
1136| koi8_r | | Russian |
1137+-----------------+--------------------------------+--------------------------------+
1138| koi8_u | | Ukrainian |
1139+-----------------+--------------------------------+--------------------------------+
1140| mac_cyrillic | maccyrillic | Bulgarian, Byelorussian, |
1141| | | Macedonian, Russian, Serbian |
1142+-----------------+--------------------------------+--------------------------------+
1143| mac_greek | macgreek | Greek |
1144+-----------------+--------------------------------+--------------------------------+
1145| mac_iceland | maciceland | Icelandic |
1146+-----------------+--------------------------------+--------------------------------+
1147| mac_latin2 | maclatin2, maccentraleurope | Central and Eastern Europe |
1148+-----------------+--------------------------------+--------------------------------+
Benjamin Peterson23110e72010-08-21 02:54:44 +00001149| mac_roman | macroman, macintosh | Western Europe |
Georg Brandl116aa622007-08-15 14:28:22 +00001150+-----------------+--------------------------------+--------------------------------+
1151| mac_turkish | macturkish | Turkish |
1152+-----------------+--------------------------------+--------------------------------+
1153| ptcp154 | csptcp154, pt154, cp154, | Kazakh |
1154| | cyrillic-asian | |
1155+-----------------+--------------------------------+--------------------------------+
1156| shift_jis | csshiftjis, shiftjis, sjis, | Japanese |
1157| | s_jis | |
1158+-----------------+--------------------------------+--------------------------------+
1159| shift_jis_2004 | shiftjis2004, sjis_2004, | Japanese |
1160| | sjis2004 | |
1161+-----------------+--------------------------------+--------------------------------+
1162| shift_jisx0213 | shiftjisx0213, sjisx0213, | Japanese |
1163| | s_jisx0213 | |
1164+-----------------+--------------------------------+--------------------------------+
Walter Dörwald41980ca2007-08-16 21:55:45 +00001165| utf_32 | U32, utf32 | all languages |
1166+-----------------+--------------------------------+--------------------------------+
1167| utf_32_be | UTF-32BE | all languages |
1168+-----------------+--------------------------------+--------------------------------+
1169| utf_32_le | UTF-32LE | all languages |
1170+-----------------+--------------------------------+--------------------------------+
Georg Brandl116aa622007-08-15 14:28:22 +00001171| utf_16 | U16, utf16 | all languages |
1172+-----------------+--------------------------------+--------------------------------+
Victor Stinner53a9dd72010-12-08 22:25:45 +00001173| utf_16_be | UTF-16BE | all languages |
Georg Brandl116aa622007-08-15 14:28:22 +00001174+-----------------+--------------------------------+--------------------------------+
Victor Stinner53a9dd72010-12-08 22:25:45 +00001175| utf_16_le | UTF-16LE | all languages |
Georg Brandl116aa622007-08-15 14:28:22 +00001176+-----------------+--------------------------------+--------------------------------+
1177| utf_7 | U7, unicode-1-1-utf-7 | all languages |
1178+-----------------+--------------------------------+--------------------------------+
1179| utf_8 | U8, UTF, utf8 | all languages |
1180+-----------------+--------------------------------+--------------------------------+
1181| utf_8_sig | | all languages |
1182+-----------------+--------------------------------+--------------------------------+
1183
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02001184.. versionchanged:: 3.4
1185 The utf-16\* and utf-32\* encoders no longer allow surrogate code points
1186 (U+D800--U+DFFF) to be encoded. The utf-32\* decoders no longer decode
1187 byte sequences that correspond to surrogate code points.
1188
1189
Nick Coghlan650e3222013-05-23 20:24:02 +10001190Python Specific Encodings
1191-------------------------
1192
1193A number of predefined codecs are specific to Python, so their codec names have
1194no meaning outside Python. These are listed in the tables below based on the
1195expected input and output types (note that while text encodings are the most
1196common use case for codecs, the underlying codec infrastructure supports
1197arbitrary data transforms rather than just text encodings). For asymmetric
1198codecs, the stated purpose describes the encoding direction.
1199
Nick Coghlan9c1aed82013-11-23 11:13:36 +10001200Text Encodings
1201^^^^^^^^^^^^^^
1202
Nick Coghlan650e3222013-05-23 20:24:02 +10001203The following codecs provide :class:`str` to :class:`bytes` encoding and
1204:term:`bytes-like object` to :class:`str` decoding, similar to the Unicode text
1205encodings.
Georg Brandl226878c2007-08-31 10:15:37 +00001206
Georg Brandl44ea77b2013-03-28 13:28:44 +01001207.. tabularcolumns:: |l|p{0.3\linewidth}|p{0.3\linewidth}|
1208
Georg Brandl30c78d62008-05-11 14:52:00 +00001209+--------------------+---------+---------------------------+
1210| Codec | Aliases | Purpose |
1211+====================+=========+===========================+
1212| idna | | Implements :rfc:`3490`, |
1213| | | see also |
1214| | | :mod:`encodings.idna` |
1215+--------------------+---------+---------------------------+
1216| mbcs | dbcs | Windows only: Encode |
1217| | | operand according to the |
1218| | | ANSI codepage (CP_ACP) |
1219+--------------------+---------+---------------------------+
1220| palmos | | Encoding of PalmOS 3.5 |
1221+--------------------+---------+---------------------------+
1222| punycode | | Implements :rfc:`3492` |
1223+--------------------+---------+---------------------------+
1224| raw_unicode_escape | | Produce a string that is |
1225| | | suitable as raw Unicode |
1226| | | literal in Python source |
1227| | | code |
1228+--------------------+---------+---------------------------+
1229| undefined | | Raise an exception for |
1230| | | all conversions. Can be |
1231| | | used as the system |
1232| | | encoding if no automatic |
1233| | | coercion between byte and |
1234| | | Unicode strings is |
1235| | | desired. |
1236+--------------------+---------+---------------------------+
1237| unicode_escape | | Produce a string that is |
1238| | | suitable as Unicode |
1239| | | literal in Python source |
1240| | | code |
1241+--------------------+---------+---------------------------+
1242| unicode_internal | | Return the internal |
1243| | | representation of the |
1244| | | operand |
Victor Stinner9f4b1e92011-11-10 20:56:30 +01001245| | | |
1246| | | .. deprecated:: 3.3 |
Georg Brandl30c78d62008-05-11 14:52:00 +00001247+--------------------+---------+---------------------------+
Georg Brandl116aa622007-08-15 14:28:22 +00001248
Nick Coghlan9c1aed82013-11-23 11:13:36 +10001249.. _binary-transforms:
1250
1251Binary Transforms
1252^^^^^^^^^^^^^^^^^
1253
1254The following codecs provide binary transforms: :term:`bytes-like object`
1255to :class:`bytes` mappings.
Nick Coghlan650e3222013-05-23 20:24:02 +10001256
Georg Brandl02524622010-12-02 18:06:51 +00001257
Nick Coghlan9c1aed82013-11-23 11:13:36 +10001258.. tabularcolumns:: |l|L|L|L|
Georg Brandl44ea77b2013-03-28 13:28:44 +01001259
Nick Coghlan9c1aed82013-11-23 11:13:36 +10001260+----------------------+------------------+------------------------------+------------------------------+
1261| Codec | Aliases | Purpose | Encoder / decoder |
1262+======================+==================+==============================+==============================+
1263| base64_codec [#b64]_ | base64, base_64 | Convert operand to MIME | :meth:`base64.b64encode` / |
1264| | | base64 (the result always | :meth:`base64.b64decode` |
1265| | | includes a trailing | |
1266| | | ``'\n'``) | |
1267| | | | |
1268| | | .. versionchanged:: 3.4 | |
1269| | | accepts any | |
1270| | | :term:`bytes-like object` | |
1271| | | as input for encoding and | |
1272| | | decoding | |
1273+----------------------+------------------+------------------------------+------------------------------+
1274| bz2_codec | bz2 | Compress the operand | :meth:`bz2.compress` / |
1275| | | using bz2 | :meth:`bz2.decompress` |
1276+----------------------+------------------+------------------------------+------------------------------+
1277| hex_codec | hex | Convert operand to | :meth:`base64.b16encode` / |
1278| | | hexadecimal | :meth:`base64.b16decode` |
1279| | | representation, with two | |
1280| | | digits per byte | |
1281+----------------------+------------------+------------------------------+------------------------------+
1282| quopri_codec | quopri, | Convert operand to MIME | :meth:`quopri.encodestring` /|
1283| | quotedprintable, | quoted printable | :meth:`quopri.decodestring` |
1284| | quoted_printable | | |
1285+----------------------+------------------+------------------------------+------------------------------+
1286| uu_codec | uu | Convert the operand using | :meth:`uu.encode` / |
1287| | | uuencode | :meth:`uu.decode` |
1288+----------------------+------------------+------------------------------+------------------------------+
1289| zlib_codec | zip, zlib | Compress the operand | :meth:`zlib.compress` / |
1290| | | using gzip | :meth:`zlib.decompress` |
1291+----------------------+------------------+------------------------------+------------------------------+
Georg Brandl02524622010-12-02 18:06:51 +00001292
Nick Coghlanfdf239a2013-10-03 00:43:22 +10001293.. [#b64] In addition to :term:`bytes-like objects <bytes-like object>`,
1294 ``'base64_codec'`` also accepts ASCII-only instances of :class:`str` for
1295 decoding
Nick Coghlan650e3222013-05-23 20:24:02 +10001296
Nick Coghlan9c1aed82013-11-23 11:13:36 +10001297.. versionadded:: 3.2
1298 Restoration of the binary transforms.
Nick Coghlan650e3222013-05-23 20:24:02 +10001299
Nick Coghlan9c1aed82013-11-23 11:13:36 +10001300.. versionchanged:: 3.4
1301 Restoration of the aliases for the binary transforms.
Georg Brandl02524622010-12-02 18:06:51 +00001302
Georg Brandl44ea77b2013-03-28 13:28:44 +01001303
Nick Coghlan9c1aed82013-11-23 11:13:36 +10001304.. _text-transforms:
1305
1306Text Transforms
1307^^^^^^^^^^^^^^^
1308
1309The following codec provides a text transform: a :class:`str` to :class:`str`
1310mapping.
1311
1312.. tabularcolumns:: |l|l|L|
1313
1314+--------------------+---------+---------------------------+
1315| Codec | Aliases | Purpose |
1316+====================+=========+===========================+
1317| rot_13 | rot13 | Returns the Caesar-cypher |
1318| | | encryption of the operand |
1319+--------------------+---------+---------------------------+
Georg Brandl02524622010-12-02 18:06:51 +00001320
1321.. versionadded:: 3.2
Nick Coghlan9c1aed82013-11-23 11:13:36 +10001322 Restoration of the ``rot_13`` text transform.
1323
1324.. versionchanged:: 3.4
1325 Restoration of the ``rot13`` alias.
Georg Brandl02524622010-12-02 18:06:51 +00001326
Georg Brandl116aa622007-08-15 14:28:22 +00001327
1328:mod:`encodings.idna` --- Internationalized Domain Names in Applications
1329------------------------------------------------------------------------
1330
1331.. module:: encodings.idna
1332 :synopsis: Internationalized Domain Names implementation
1333.. moduleauthor:: Martin v. Löwis
1334
Georg Brandl116aa622007-08-15 14:28:22 +00001335This module implements :rfc:`3490` (Internationalized Domain Names in
1336Applications) and :rfc:`3492` (Nameprep: A Stringprep Profile for
1337Internationalized Domain Names (IDN)). It builds upon the ``punycode`` encoding
1338and :mod:`stringprep`.
1339
1340These RFCs together define a protocol to support non-ASCII characters in domain
1341names. A domain name containing non-ASCII characters (such as
1342``www.Alliancefrançaise.nu``) is converted into an ASCII-compatible encoding
1343(ACE, such as ``www.xn--alliancefranaise-npb.nu``). The ACE form of the domain
1344name is then used in all places where arbitrary characters are not allowed by
1345the protocol, such as DNS queries, HTTP :mailheader:`Host` fields, and so
1346on. This conversion is carried out in the application; if possible invisible to
1347the user: The application should transparently convert Unicode domain labels to
1348IDNA on the wire, and convert back ACE labels to Unicode before presenting them
1349to the user.
1350
R David Murraye0fd2f82011-04-13 14:12:18 -04001351Python supports this conversion in several ways: the ``idna`` codec performs
1352conversion between Unicode and ACE, separating an input string into labels
1353based on the separator characters defined in `section 3.1`_ (1) of :rfc:`3490`
1354and converting each label to ACE as required, and conversely separating an input
1355byte string into labels based on the ``.`` separator and converting any ACE
1356labels found into unicode. Furthermore, the :mod:`socket` module
Georg Brandl116aa622007-08-15 14:28:22 +00001357transparently converts Unicode host names to ACE, so that applications need not
1358be concerned about converting host names themselves when they pass them to the
1359socket module. On top of that, modules that have host names as function
Georg Brandl24420152008-05-26 16:32:26 +00001360parameters, such as :mod:`http.client` and :mod:`ftplib`, accept Unicode host
1361names (:mod:`http.client` then also transparently sends an IDNA hostname in the
Georg Brandl116aa622007-08-15 14:28:22 +00001362:mailheader:`Host` field if it sends that field at all).
1363
R David Murraye0fd2f82011-04-13 14:12:18 -04001364.. _section 3.1: http://tools.ietf.org/html/rfc3490#section-3.1
1365
Georg Brandl116aa622007-08-15 14:28:22 +00001366When receiving host names from the wire (such as in reverse name lookup), no
1367automatic conversion to Unicode is performed: Applications wishing to present
1368such host names to the user should decode them to Unicode.
1369
1370The module :mod:`encodings.idna` also implements the nameprep procedure, which
1371performs certain normalizations on host names, to achieve case-insensitivity of
1372international domain names, and to unify similar characters. The nameprep
1373functions can be used directly if desired.
1374
1375
1376.. function:: nameprep(label)
1377
1378 Return the nameprepped version of *label*. The implementation currently assumes
1379 query strings, so ``AllowUnassigned`` is true.
1380
1381
1382.. function:: ToASCII(label)
1383
1384 Convert a label to ASCII, as specified in :rfc:`3490`. ``UseSTD3ASCIIRules`` is
1385 assumed to be false.
1386
1387
1388.. function:: ToUnicode(label)
1389
1390 Convert a label to Unicode, as specified in :rfc:`3490`.
1391
1392
Victor Stinner554f3f02010-06-16 23:33:54 +00001393:mod:`encodings.mbcs` --- Windows ANSI codepage
1394-----------------------------------------------
1395
1396.. module:: encodings.mbcs
1397 :synopsis: Windows ANSI codepage
1398
Victor Stinner3a50e702011-10-18 21:21:00 +02001399Encode operand according to the ANSI codepage (CP_ACP).
Victor Stinner554f3f02010-06-16 23:33:54 +00001400
1401Availability: Windows only.
1402
Victor Stinner3a50e702011-10-18 21:21:00 +02001403.. versionchanged:: 3.3
1404 Support any error handler.
1405
Victor Stinner554f3f02010-06-16 23:33:54 +00001406.. versionchanged:: 3.2
1407 Before 3.2, the *errors* argument was ignored; ``'replace'`` was always used
1408 to encode, and ``'ignore'`` to decode.
1409
1410
Georg Brandl116aa622007-08-15 14:28:22 +00001411:mod:`encodings.utf_8_sig` --- UTF-8 codec with BOM signature
1412-------------------------------------------------------------
1413
1414.. module:: encodings.utf_8_sig
1415 :synopsis: UTF-8 codec with BOM signature
1416.. moduleauthor:: Walter Dörwald
1417
Georg Brandl116aa622007-08-15 14:28:22 +00001418This module implements a variant of the UTF-8 codec: On encoding a UTF-8 encoded
1419BOM will be prepended to the UTF-8 encoded bytes. For the stateful encoder this
1420is only done once (on the first write to the byte stream). For decoding an
1421optional UTF-8 encoded BOM at the start of the data will be skipped.