blob: 53437ce1e52b7063c9fd04f43a01fcd2257fb779 [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +00001:mod:`codecs` --- Codec registry and base classes
2=================================================
3
4.. module:: codecs
5 :synopsis: Encode and decode data and streams.
6.. moduleauthor:: Marc-Andre Lemburg <mal@lemburg.com>
7.. sectionauthor:: Marc-Andre Lemburg <mal@lemburg.com>
8.. sectionauthor:: Martin v. Löwis <martin@v.loewis.de>
9
10
11.. index::
12 single: Unicode
13 single: Codecs
14 pair: Codecs; encode
15 pair: Codecs; decode
16 single: streams
17 pair: stackable; streams
18
19This module defines base classes for standard Python codecs (encoders and
20decoders) and provides access to the internal Python codec registry which
21manages the codec and error handling lookup process.
22
23It defines the following functions:
24
25
26.. function:: register(search_function)
27
28 Register a codec search function. Search functions are expected to take one
29 argument, the encoding name in all lower case letters, and return a
30 :class:`CodecInfo` object having the following attributes:
31
32 * ``name`` The name of the encoding;
33
Walter Dörwald62073e02008-10-23 13:21:33 +000034 * ``encode`` The stateless encoding function;
Georg Brandl116aa622007-08-15 14:28:22 +000035
Walter Dörwald62073e02008-10-23 13:21:33 +000036 * ``decode`` The stateless decoding function;
Georg Brandl116aa622007-08-15 14:28:22 +000037
38 * ``incrementalencoder`` An incremental encoder class or factory function;
39
40 * ``incrementaldecoder`` An incremental decoder class or factory function;
41
42 * ``streamwriter`` A stream writer class or factory function;
43
44 * ``streamreader`` A stream reader class or factory function.
45
46 The various functions or classes take the following arguments:
47
Walter Dörwald62073e02008-10-23 13:21:33 +000048 *encode* and *decode*: These must be functions or methods which have the same
Georg Brandl116aa622007-08-15 14:28:22 +000049 interface as the :meth:`encode`/:meth:`decode` methods of Codec instances (see
50 Codec Interface). The functions/methods are expected to work in a stateless
51 mode.
52
Benjamin Peterson3e4f0552008-09-02 00:31:15 +000053 *incrementalencoder* and *incrementaldecoder*: These have to be factory
Georg Brandl116aa622007-08-15 14:28:22 +000054 functions providing the following interface:
55
56 ``factory(errors='strict')``
57
58 The factory functions must return objects providing the interfaces defined by
Benjamin Peterson3e4f0552008-09-02 00:31:15 +000059 the base classes :class:`IncrementalEncoder` and :class:`IncrementalDecoder`,
Georg Brandl116aa622007-08-15 14:28:22 +000060 respectively. Incremental codecs can maintain state.
61
62 *streamreader* and *streamwriter*: These have to be factory functions providing
63 the following interface:
64
65 ``factory(stream, errors='strict')``
66
67 The factory functions must return objects providing the interfaces defined by
68 the base classes :class:`StreamWriter` and :class:`StreamReader`, respectively.
69 Stream codecs can maintain state.
70
71 Possible values for errors are ``'strict'`` (raise an exception in case of an
72 encoding error), ``'replace'`` (replace malformed data with a suitable
73 replacement marker, such as ``'?'``), ``'ignore'`` (ignore malformed data and
74 continue without further notice), ``'xmlcharrefreplace'`` (replace with the
75 appropriate XML character reference (for encoding only)) and
76 ``'backslashreplace'`` (replace with backslashed escape sequences (for encoding
77 only)) as well as any other error handling name defined via
78 :func:`register_error`.
79
80 In case a search function cannot find a given encoding, it should return
81 ``None``.
82
83
84.. function:: lookup(encoding)
85
86 Looks up the codec info in the Python codec registry and returns a
87 :class:`CodecInfo` object as defined above.
88
89 Encodings are first looked up in the registry's cache. If not found, the list of
90 registered search functions is scanned. If no :class:`CodecInfo` object is
91 found, a :exc:`LookupError` is raised. Otherwise, the :class:`CodecInfo` object
92 is stored in the cache and returned to the caller.
93
94To simplify access to the various codecs, the module provides these additional
95functions which use :func:`lookup` for the codec lookup:
96
97
98.. function:: getencoder(encoding)
99
100 Look up the codec for the given encoding and return its encoder function.
101
102 Raises a :exc:`LookupError` in case the encoding cannot be found.
103
104
105.. function:: getdecoder(encoding)
106
107 Look up the codec for the given encoding and return its decoder function.
108
109 Raises a :exc:`LookupError` in case the encoding cannot be found.
110
111
112.. function:: getincrementalencoder(encoding)
113
114 Look up the codec for the given encoding and return its incremental encoder
115 class or factory function.
116
117 Raises a :exc:`LookupError` in case the encoding cannot be found or the codec
118 doesn't support an incremental encoder.
119
Georg Brandl116aa622007-08-15 14:28:22 +0000120
121.. function:: getincrementaldecoder(encoding)
122
123 Look up the codec for the given encoding and return its incremental decoder
124 class or factory function.
125
126 Raises a :exc:`LookupError` in case the encoding cannot be found or the codec
127 doesn't support an incremental decoder.
128
Georg Brandl116aa622007-08-15 14:28:22 +0000129
130.. function:: getreader(encoding)
131
132 Look up the codec for the given encoding and return its StreamReader class or
133 factory function.
134
135 Raises a :exc:`LookupError` in case the encoding cannot be found.
136
137
138.. function:: getwriter(encoding)
139
140 Look up the codec for the given encoding and return its StreamWriter class or
141 factory function.
142
143 Raises a :exc:`LookupError` in case the encoding cannot be found.
144
145
146.. function:: register_error(name, error_handler)
147
148 Register the error handling function *error_handler* under the name *name*.
149 *error_handler* will be called during encoding and decoding in case of an error,
150 when *name* is specified as the errors parameter.
151
152 For encoding *error_handler* will be called with a :exc:`UnicodeEncodeError`
153 instance, which contains information about the location of the error. The error
154 handler must either raise this or a different exception or return a tuple with a
155 replacement for the unencodable part of the input and a position where encoding
156 should continue. The encoder will encode the replacement and continue encoding
157 the original input at the specified position. Negative position values will be
158 treated as being relative to the end of the input string. If the resulting
159 position is out of bound an :exc:`IndexError` will be raised.
160
161 Decoding and translating works similar, except :exc:`UnicodeDecodeError` or
162 :exc:`UnicodeTranslateError` will be passed to the handler and that the
163 replacement from the error handler will be put into the output directly.
164
165
166.. function:: lookup_error(name)
167
168 Return the error handler previously registered under the name *name*.
169
170 Raises a :exc:`LookupError` in case the handler cannot be found.
171
172
173.. function:: strict_errors(exception)
174
175 Implements the ``strict`` error handling.
176
177
178.. function:: replace_errors(exception)
179
180 Implements the ``replace`` error handling.
181
182
183.. function:: ignore_errors(exception)
184
185 Implements the ``ignore`` error handling.
186
187
Thomas Wouters89d996e2007-09-08 17:39:28 +0000188.. function:: xmlcharrefreplace_errors(exception)
Georg Brandl116aa622007-08-15 14:28:22 +0000189
190 Implements the ``xmlcharrefreplace`` error handling.
191
192
Thomas Wouters89d996e2007-09-08 17:39:28 +0000193.. function:: backslashreplace_errors(exception)
Georg Brandl116aa622007-08-15 14:28:22 +0000194
195 Implements the ``backslashreplace`` error handling.
196
197To simplify working with encoded files or stream, the module also defines these
198utility functions:
199
200
201.. function:: open(filename, mode[, encoding[, errors[, buffering]]])
202
203 Open an encoded file using the given *mode* and return a wrapped version
Christian Heimes18c66892008-02-17 13:31:39 +0000204 providing transparent encoding/decoding. The default file mode is ``'r'``
205 meaning to open the file in read mode.
Georg Brandl116aa622007-08-15 14:28:22 +0000206
207 .. note::
208
Georg Brandl30c78d62008-05-11 14:52:00 +0000209 The wrapped version's methods will accept and return strings only. Bytes
210 arguments will be rejected.
Georg Brandl116aa622007-08-15 14:28:22 +0000211
Christian Heimes18c66892008-02-17 13:31:39 +0000212 .. note::
213
214 Files are always opened in binary mode, even if no binary mode was
215 specified. This is done to avoid data loss due to encodings using 8-bit
Georg Brandl30c78d62008-05-11 14:52:00 +0000216 values. This means that no automatic conversion of ``b'\n'`` is done
Christian Heimes18c66892008-02-17 13:31:39 +0000217 on reading and writing.
218
Georg Brandl116aa622007-08-15 14:28:22 +0000219 *encoding* specifies the encoding which is to be used for the file.
220
221 *errors* may be given to define the error handling. It defaults to ``'strict'``
222 which causes a :exc:`ValueError` to be raised in case an encoding error occurs.
223
224 *buffering* has the same meaning as for the built-in :func:`open` function. It
225 defaults to line buffered.
226
227
Georg Brandl0d8f0732009-04-05 22:20:44 +0000228.. function:: EncodedFile(file, data_encoding, file_encoding=None, errors='strict')
Georg Brandl116aa622007-08-15 14:28:22 +0000229
230 Return a wrapped version of file which provides transparent encoding
231 translation.
232
Georg Brandl30c78d62008-05-11 14:52:00 +0000233 Bytes written to the wrapped file are interpreted according to the given
Georg Brandl0d8f0732009-04-05 22:20:44 +0000234 *data_encoding* and then written to the original file as bytes using the
235 *file_encoding*.
Georg Brandl116aa622007-08-15 14:28:22 +0000236
Georg Brandl0d8f0732009-04-05 22:20:44 +0000237 If *file_encoding* is not given, it defaults to *data_encoding*.
Georg Brandl116aa622007-08-15 14:28:22 +0000238
Georg Brandl0d8f0732009-04-05 22:20:44 +0000239 *errors* may be given to define the error handling. It defaults to
240 ``'strict'``, which causes :exc:`ValueError` to be raised in case an encoding
241 error occurs.
Georg Brandl116aa622007-08-15 14:28:22 +0000242
243
Georg Brandl0d8f0732009-04-05 22:20:44 +0000244.. function:: iterencode(iterator, encoding, errors='strict', **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +0000245
246 Uses an incremental encoder to iteratively encode the input provided by
Georg Brandl0d8f0732009-04-05 22:20:44 +0000247 *iterator*. This function is a :term:`generator`. *errors* (as well as any
Georg Brandl9afde1c2007-11-01 20:32:30 +0000248 other keyword argument) is passed through to the incremental encoder.
Georg Brandl116aa622007-08-15 14:28:22 +0000249
Georg Brandl116aa622007-08-15 14:28:22 +0000250
Georg Brandl0d8f0732009-04-05 22:20:44 +0000251.. function:: iterdecode(iterator, encoding, errors='strict', **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +0000252
253 Uses an incremental decoder to iteratively decode the input provided by
Georg Brandl0d8f0732009-04-05 22:20:44 +0000254 *iterator*. This function is a :term:`generator`. *errors* (as well as any
Georg Brandl9afde1c2007-11-01 20:32:30 +0000255 other keyword argument) is passed through to the incremental decoder.
Georg Brandl116aa622007-08-15 14:28:22 +0000256
Georg Brandl0d8f0732009-04-05 22:20:44 +0000257
Georg Brandl116aa622007-08-15 14:28:22 +0000258The module also provides the following constants which are useful for reading
259and writing to platform dependent files:
260
261
262.. data:: BOM
263 BOM_BE
264 BOM_LE
265 BOM_UTF8
266 BOM_UTF16
267 BOM_UTF16_BE
268 BOM_UTF16_LE
269 BOM_UTF32
270 BOM_UTF32_BE
271 BOM_UTF32_LE
272
273 These constants define various encodings of the Unicode byte order mark (BOM)
274 used in UTF-16 and UTF-32 data streams to indicate the byte order used in the
275 stream or file and in UTF-8 as a Unicode signature. :const:`BOM_UTF16` is either
276 :const:`BOM_UTF16_BE` or :const:`BOM_UTF16_LE` depending on the platform's
277 native byte order, :const:`BOM` is an alias for :const:`BOM_UTF16`,
278 :const:`BOM_LE` for :const:`BOM_UTF16_LE` and :const:`BOM_BE` for
279 :const:`BOM_UTF16_BE`. The others represent the BOM in UTF-8 and UTF-32
280 encodings.
281
282
283.. _codec-base-classes:
284
285Codec Base Classes
286------------------
287
288The :mod:`codecs` module defines a set of base classes which define the
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000289interface and can also be used to easily write your own codecs for use in
290Python.
Georg Brandl116aa622007-08-15 14:28:22 +0000291
292Each codec has to define four interfaces to make it usable as codec in Python:
293stateless encoder, stateless decoder, stream reader and stream writer. The
294stream reader and writers typically reuse the stateless encoder/decoder to
295implement the file protocols.
296
297The :class:`Codec` class defines the interface for stateless encoders/decoders.
298
299To simplify and standardize error handling, the :meth:`encode` and
300:meth:`decode` methods may implement different error handling schemes by
301providing the *errors* string argument. The following string values are defined
302and implemented by all standard Python codecs:
303
304+-------------------------+-----------------------------------------------+
305| Value | Meaning |
306+=========================+===============================================+
307| ``'strict'`` | Raise :exc:`UnicodeError` (or a subclass); |
308| | this is the default. |
309+-------------------------+-----------------------------------------------+
310| ``'ignore'`` | Ignore the character and continue with the |
311| | next. |
312+-------------------------+-----------------------------------------------+
313| ``'replace'`` | Replace with a suitable replacement |
314| | character; Python will use the official |
315| | U+FFFD REPLACEMENT CHARACTER for the built-in |
316| | Unicode codecs on decoding and '?' on |
317| | encoding. |
318+-------------------------+-----------------------------------------------+
319| ``'xmlcharrefreplace'`` | Replace with the appropriate XML character |
320| | reference (only for encoding). |
321+-------------------------+-----------------------------------------------+
322| ``'backslashreplace'`` | Replace with backslashed escape sequences |
323| | (only for encoding). |
324+-------------------------+-----------------------------------------------+
Martin v. Löwis3d2eca02009-06-29 06:35:26 +0000325| ``'surrogateescape'`` | Replace byte with surrogate U+DCxx, as defined|
326| | in :pep:`383`. |
Martin v. Löwis011e8422009-05-05 04:43:17 +0000327+-------------------------+-----------------------------------------------+
Georg Brandl116aa622007-08-15 14:28:22 +0000328
Martin v. Löwisdb12d452009-05-02 18:52:14 +0000329In addition, the following error handlers are specific to a single codec:
330
Martin v. Löwise0a2b722009-05-10 08:08:56 +0000331+-------------------+---------+-------------------------------------------+
332| Value | Codec | Meaning |
333+===================+=========+===========================================+
334|``'surrogatepass'``| utf-8 | Allow encoding and decoding of surrogate |
335| | | codes in UTF-8. |
336+-------------------+---------+-------------------------------------------+
Martin v. Löwisdb12d452009-05-02 18:52:14 +0000337
338.. versionadded:: 3.1
Martin v. Löwis43c57782009-05-10 08:15:24 +0000339 The ``'surrogateescape'`` and ``'surrogatepass'`` error handlers.
Martin v. Löwisdb12d452009-05-02 18:52:14 +0000340
Georg Brandl116aa622007-08-15 14:28:22 +0000341The set of allowed values can be extended via :meth:`register_error`.
342
343
344.. _codec-objects:
345
346Codec Objects
347^^^^^^^^^^^^^
348
349The :class:`Codec` class defines these methods which also define the function
350interfaces of the stateless encoder and decoder:
351
352
353.. method:: Codec.encode(input[, errors])
354
355 Encodes the object *input* and returns a tuple (output object, length consumed).
Georg Brandl30c78d62008-05-11 14:52:00 +0000356 Encoding converts a string object to a bytes object using a particular
Georg Brandl116aa622007-08-15 14:28:22 +0000357 character set encoding (e.g., ``cp1252`` or ``iso-8859-1``).
358
359 *errors* defines the error handling to apply. It defaults to ``'strict'``
360 handling.
361
362 The method may not store state in the :class:`Codec` instance. Use
363 :class:`StreamCodec` for codecs which have to keep state in order to make
364 encoding/decoding efficient.
365
366 The encoder must be able to handle zero length input and return an empty object
367 of the output object type in this situation.
368
369
370.. method:: Codec.decode(input[, errors])
371
Georg Brandl30c78d62008-05-11 14:52:00 +0000372 Decodes the object *input* and returns a tuple (output object, length
373 consumed). Decoding converts a bytes object encoded using a particular
374 character set encoding to a string object.
Georg Brandl116aa622007-08-15 14:28:22 +0000375
Georg Brandl30c78d62008-05-11 14:52:00 +0000376 *input* must be a bytes object or one which provides the read-only character
377 buffer interface -- for example, buffer objects and memory mapped files.
Georg Brandl116aa622007-08-15 14:28:22 +0000378
379 *errors* defines the error handling to apply. It defaults to ``'strict'``
380 handling.
381
382 The method may not store state in the :class:`Codec` instance. Use
383 :class:`StreamCodec` for codecs which have to keep state in order to make
384 encoding/decoding efficient.
385
386 The decoder must be able to handle zero length input and return an empty object
387 of the output object type in this situation.
388
389The :class:`IncrementalEncoder` and :class:`IncrementalDecoder` classes provide
390the basic interface for incremental encoding and decoding. Encoding/decoding the
391input isn't done with one call to the stateless encoder/decoder function, but
392with multiple calls to the :meth:`encode`/:meth:`decode` method of the
393incremental encoder/decoder. The incremental encoder/decoder keeps track of the
394encoding/decoding process during method calls.
395
396The joined output of calls to the :meth:`encode`/:meth:`decode` method is the
397same as if all the single inputs were joined into one, and this input was
398encoded/decoded with the stateless encoder/decoder.
399
400
401.. _incremental-encoder-objects:
402
403IncrementalEncoder Objects
404^^^^^^^^^^^^^^^^^^^^^^^^^^
405
Georg Brandl116aa622007-08-15 14:28:22 +0000406The :class:`IncrementalEncoder` class is used for encoding an input in multiple
407steps. It defines the following methods which every incremental encoder must
408define in order to be compatible with the Python codec registry.
409
410
411.. class:: IncrementalEncoder([errors])
412
413 Constructor for an :class:`IncrementalEncoder` instance.
414
415 All incremental encoders must provide this constructor interface. They are free
416 to add additional keyword arguments, but only the ones defined here are used by
417 the Python codec registry.
418
419 The :class:`IncrementalEncoder` may implement different error handling schemes
420 by providing the *errors* keyword argument. These parameters are predefined:
421
422 * ``'strict'`` Raise :exc:`ValueError` (or a subclass); this is the default.
423
424 * ``'ignore'`` Ignore the character and continue with the next.
425
426 * ``'replace'`` Replace with a suitable replacement character
427
428 * ``'xmlcharrefreplace'`` Replace with the appropriate XML character reference
429
430 * ``'backslashreplace'`` Replace with backslashed escape sequences.
431
432 The *errors* argument will be assigned to an attribute of the same name.
433 Assigning to this attribute makes it possible to switch between different error
434 handling strategies during the lifetime of the :class:`IncrementalEncoder`
435 object.
436
437 The set of allowed values for the *errors* argument can be extended with
438 :func:`register_error`.
439
440
Benjamin Petersone41251e2008-04-25 01:59:09 +0000441 .. method:: encode(object[, final])
Georg Brandl116aa622007-08-15 14:28:22 +0000442
Benjamin Petersone41251e2008-04-25 01:59:09 +0000443 Encodes *object* (taking the current state of the encoder into account)
444 and returns the resulting encoded object. If this is the last call to
445 :meth:`encode` *final* must be true (the default is false).
Georg Brandl116aa622007-08-15 14:28:22 +0000446
447
Benjamin Petersone41251e2008-04-25 01:59:09 +0000448 .. method:: reset()
Georg Brandl116aa622007-08-15 14:28:22 +0000449
Benjamin Petersone41251e2008-04-25 01:59:09 +0000450 Reset the encoder to the initial state.
Georg Brandl116aa622007-08-15 14:28:22 +0000451
452
453.. method:: IncrementalEncoder.getstate()
454
455 Return the current state of the encoder which must be an integer. The
456 implementation should make sure that ``0`` is the most common state. (States
457 that are more complicated than integers can be converted into an integer by
458 marshaling/pickling the state and encoding the bytes of the resulting string
459 into an integer).
460
Georg Brandl116aa622007-08-15 14:28:22 +0000461
462.. method:: IncrementalEncoder.setstate(state)
463
464 Set the state of the encoder to *state*. *state* must be an encoder state
465 returned by :meth:`getstate`.
466
Georg Brandl116aa622007-08-15 14:28:22 +0000467
468.. _incremental-decoder-objects:
469
470IncrementalDecoder Objects
471^^^^^^^^^^^^^^^^^^^^^^^^^^
472
473The :class:`IncrementalDecoder` class is used for decoding an input in multiple
474steps. It defines the following methods which every incremental decoder must
475define in order to be compatible with the Python codec registry.
476
477
478.. class:: IncrementalDecoder([errors])
479
480 Constructor for an :class:`IncrementalDecoder` instance.
481
482 All incremental decoders must provide this constructor interface. They are free
483 to add additional keyword arguments, but only the ones defined here are used by
484 the Python codec registry.
485
486 The :class:`IncrementalDecoder` may implement different error handling schemes
487 by providing the *errors* keyword argument. These parameters are predefined:
488
489 * ``'strict'`` Raise :exc:`ValueError` (or a subclass); this is the default.
490
491 * ``'ignore'`` Ignore the character and continue with the next.
492
493 * ``'replace'`` Replace with a suitable replacement character.
494
495 The *errors* argument will be assigned to an attribute of the same name.
496 Assigning to this attribute makes it possible to switch between different error
Benjamin Peterson3e4f0552008-09-02 00:31:15 +0000497 handling strategies during the lifetime of the :class:`IncrementalDecoder`
Georg Brandl116aa622007-08-15 14:28:22 +0000498 object.
499
500 The set of allowed values for the *errors* argument can be extended with
501 :func:`register_error`.
502
503
Benjamin Petersone41251e2008-04-25 01:59:09 +0000504 .. method:: decode(object[, final])
Georg Brandl116aa622007-08-15 14:28:22 +0000505
Benjamin Petersone41251e2008-04-25 01:59:09 +0000506 Decodes *object* (taking the current state of the decoder into account)
507 and returns the resulting decoded object. If this is the last call to
508 :meth:`decode` *final* must be true (the default is false). If *final* is
509 true the decoder must decode the input completely and must flush all
510 buffers. If this isn't possible (e.g. because of incomplete byte sequences
511 at the end of the input) it must initiate error handling just like in the
512 stateless case (which might raise an exception).
Georg Brandl116aa622007-08-15 14:28:22 +0000513
514
Benjamin Petersone41251e2008-04-25 01:59:09 +0000515 .. method:: reset()
Georg Brandl116aa622007-08-15 14:28:22 +0000516
Benjamin Petersone41251e2008-04-25 01:59:09 +0000517 Reset the decoder to the initial state.
Georg Brandl116aa622007-08-15 14:28:22 +0000518
519
Benjamin Petersone41251e2008-04-25 01:59:09 +0000520 .. method:: getstate()
Georg Brandl116aa622007-08-15 14:28:22 +0000521
Benjamin Petersone41251e2008-04-25 01:59:09 +0000522 Return the current state of the decoder. This must be a tuple with two
523 items, the first must be the buffer containing the still undecoded
524 input. The second must be an integer and can be additional state
525 info. (The implementation should make sure that ``0`` is the most common
526 additional state info.) If this additional state info is ``0`` it must be
527 possible to set the decoder to the state which has no input buffered and
528 ``0`` as the additional state info, so that feeding the previously
529 buffered input to the decoder returns it to the previous state without
530 producing any output. (Additional state info that is more complicated than
531 integers can be converted into an integer by marshaling/pickling the info
532 and encoding the bytes of the resulting string into an integer.)
Georg Brandl116aa622007-08-15 14:28:22 +0000533
Georg Brandl116aa622007-08-15 14:28:22 +0000534
Benjamin Petersone41251e2008-04-25 01:59:09 +0000535 .. method:: setstate(state)
Georg Brandl116aa622007-08-15 14:28:22 +0000536
Benjamin Petersone41251e2008-04-25 01:59:09 +0000537 Set the state of the encoder to *state*. *state* must be a decoder state
538 returned by :meth:`getstate`.
539
Georg Brandl116aa622007-08-15 14:28:22 +0000540
Georg Brandl116aa622007-08-15 14:28:22 +0000541The :class:`StreamWriter` and :class:`StreamReader` classes provide generic
542working interfaces which can be used to implement new encoding submodules very
543easily. See :mod:`encodings.utf_8` for an example of how this is done.
544
545
546.. _stream-writer-objects:
547
548StreamWriter Objects
549^^^^^^^^^^^^^^^^^^^^
550
551The :class:`StreamWriter` class is a subclass of :class:`Codec` and defines the
552following methods which every stream writer must define in order to be
553compatible with the Python codec registry.
554
555
556.. class:: StreamWriter(stream[, errors])
557
558 Constructor for a :class:`StreamWriter` instance.
559
560 All stream writers must provide this constructor interface. They are free to add
561 additional keyword arguments, but only the ones defined here are used by the
562 Python codec registry.
563
564 *stream* must be a file-like object open for writing binary data.
565
566 The :class:`StreamWriter` may implement different error handling schemes by
567 providing the *errors* keyword argument. These parameters are predefined:
568
569 * ``'strict'`` Raise :exc:`ValueError` (or a subclass); this is the default.
570
571 * ``'ignore'`` Ignore the character and continue with the next.
572
573 * ``'replace'`` Replace with a suitable replacement character
574
575 * ``'xmlcharrefreplace'`` Replace with the appropriate XML character reference
576
577 * ``'backslashreplace'`` Replace with backslashed escape sequences.
578
579 The *errors* argument will be assigned to an attribute of the same name.
580 Assigning to this attribute makes it possible to switch between different error
581 handling strategies during the lifetime of the :class:`StreamWriter` object.
582
583 The set of allowed values for the *errors* argument can be extended with
584 :func:`register_error`.
585
586
Benjamin Petersone41251e2008-04-25 01:59:09 +0000587 .. method:: write(object)
Georg Brandl116aa622007-08-15 14:28:22 +0000588
Benjamin Petersone41251e2008-04-25 01:59:09 +0000589 Writes the object's contents encoded to the stream.
Georg Brandl116aa622007-08-15 14:28:22 +0000590
591
Benjamin Petersone41251e2008-04-25 01:59:09 +0000592 .. method:: writelines(list)
Georg Brandl116aa622007-08-15 14:28:22 +0000593
Benjamin Petersone41251e2008-04-25 01:59:09 +0000594 Writes the concatenated list of strings to the stream (possibly by reusing
595 the :meth:`write` method).
Georg Brandl116aa622007-08-15 14:28:22 +0000596
597
Benjamin Petersone41251e2008-04-25 01:59:09 +0000598 .. method:: reset()
Georg Brandl116aa622007-08-15 14:28:22 +0000599
Benjamin Petersone41251e2008-04-25 01:59:09 +0000600 Flushes and resets the codec buffers used for keeping state.
Georg Brandl116aa622007-08-15 14:28:22 +0000601
Benjamin Petersone41251e2008-04-25 01:59:09 +0000602 Calling this method should ensure that the data on the output is put into
603 a clean state that allows appending of new fresh data without having to
604 rescan the whole stream to recover state.
605
Georg Brandl116aa622007-08-15 14:28:22 +0000606
607In addition to the above methods, the :class:`StreamWriter` must also inherit
608all other methods and attributes from the underlying stream.
609
610
611.. _stream-reader-objects:
612
613StreamReader Objects
614^^^^^^^^^^^^^^^^^^^^
615
616The :class:`StreamReader` class is a subclass of :class:`Codec` and defines the
617following methods which every stream reader must define in order to be
618compatible with the Python codec registry.
619
620
621.. class:: StreamReader(stream[, errors])
622
623 Constructor for a :class:`StreamReader` instance.
624
625 All stream readers must provide this constructor interface. They are free to add
626 additional keyword arguments, but only the ones defined here are used by the
627 Python codec registry.
628
629 *stream* must be a file-like object open for reading (binary) data.
630
631 The :class:`StreamReader` may implement different error handling schemes by
632 providing the *errors* keyword argument. These parameters are defined:
633
634 * ``'strict'`` Raise :exc:`ValueError` (or a subclass); this is the default.
635
636 * ``'ignore'`` Ignore the character and continue with the next.
637
638 * ``'replace'`` Replace with a suitable replacement character.
639
640 The *errors* argument will be assigned to an attribute of the same name.
641 Assigning to this attribute makes it possible to switch between different error
642 handling strategies during the lifetime of the :class:`StreamReader` object.
643
644 The set of allowed values for the *errors* argument can be extended with
645 :func:`register_error`.
646
647
Benjamin Petersone41251e2008-04-25 01:59:09 +0000648 .. method:: read([size[, chars, [firstline]]])
Georg Brandl116aa622007-08-15 14:28:22 +0000649
Benjamin Petersone41251e2008-04-25 01:59:09 +0000650 Decodes data from the stream and returns the resulting object.
Georg Brandl116aa622007-08-15 14:28:22 +0000651
Benjamin Petersone41251e2008-04-25 01:59:09 +0000652 *chars* indicates the number of characters to read from the
653 stream. :func:`read` will never return more than *chars* characters, but
654 it might return less, if there are not enough characters available.
Georg Brandl116aa622007-08-15 14:28:22 +0000655
Benjamin Petersone41251e2008-04-25 01:59:09 +0000656 *size* indicates the approximate maximum number of bytes to read from the
657 stream for decoding purposes. The decoder can modify this setting as
658 appropriate. The default value -1 indicates to read and decode as much as
659 possible. *size* is intended to prevent having to decode huge files in
660 one step.
Georg Brandl116aa622007-08-15 14:28:22 +0000661
Benjamin Petersone41251e2008-04-25 01:59:09 +0000662 *firstline* indicates that it would be sufficient to only return the first
663 line, if there are decoding errors on later lines.
Georg Brandl116aa622007-08-15 14:28:22 +0000664
Benjamin Petersone41251e2008-04-25 01:59:09 +0000665 The method should use a greedy read strategy meaning that it should read
666 as much data as is allowed within the definition of the encoding and the
667 given size, e.g. if optional encoding endings or state markers are
668 available on the stream, these should be read too.
Georg Brandl116aa622007-08-15 14:28:22 +0000669
Georg Brandl116aa622007-08-15 14:28:22 +0000670
Benjamin Petersone41251e2008-04-25 01:59:09 +0000671 .. method:: readline([size[, keepends]])
Georg Brandl116aa622007-08-15 14:28:22 +0000672
Benjamin Petersone41251e2008-04-25 01:59:09 +0000673 Read one line from the input stream and return the decoded data.
Georg Brandl116aa622007-08-15 14:28:22 +0000674
Benjamin Petersone41251e2008-04-25 01:59:09 +0000675 *size*, if given, is passed as size argument to the stream's
676 :meth:`readline` method.
Georg Brandl116aa622007-08-15 14:28:22 +0000677
Benjamin Petersone41251e2008-04-25 01:59:09 +0000678 If *keepends* is false line-endings will be stripped from the lines
679 returned.
Georg Brandl116aa622007-08-15 14:28:22 +0000680
Georg Brandl116aa622007-08-15 14:28:22 +0000681
Benjamin Petersone41251e2008-04-25 01:59:09 +0000682 .. method:: readlines([sizehint[, keepends]])
Georg Brandl116aa622007-08-15 14:28:22 +0000683
Benjamin Petersone41251e2008-04-25 01:59:09 +0000684 Read all lines available on the input stream and return them as a list of
685 lines.
Georg Brandl116aa622007-08-15 14:28:22 +0000686
Benjamin Petersone41251e2008-04-25 01:59:09 +0000687 Line-endings are implemented using the codec's decoder method and are
688 included in the list entries if *keepends* is true.
Georg Brandl116aa622007-08-15 14:28:22 +0000689
Benjamin Petersone41251e2008-04-25 01:59:09 +0000690 *sizehint*, if given, is passed as the *size* argument to the stream's
691 :meth:`read` method.
Georg Brandl116aa622007-08-15 14:28:22 +0000692
693
Benjamin Petersone41251e2008-04-25 01:59:09 +0000694 .. method:: reset()
Georg Brandl116aa622007-08-15 14:28:22 +0000695
Benjamin Petersone41251e2008-04-25 01:59:09 +0000696 Resets the codec buffers used for keeping state.
Georg Brandl116aa622007-08-15 14:28:22 +0000697
Benjamin Petersone41251e2008-04-25 01:59:09 +0000698 Note that no stream repositioning should take place. This method is
699 primarily intended to be able to recover from decoding errors.
700
Georg Brandl116aa622007-08-15 14:28:22 +0000701
702In addition to the above methods, the :class:`StreamReader` must also inherit
703all other methods and attributes from the underlying stream.
704
705The next two base classes are included for convenience. They are not needed by
706the codec registry, but may provide useful in practice.
707
708
709.. _stream-reader-writer:
710
711StreamReaderWriter Objects
712^^^^^^^^^^^^^^^^^^^^^^^^^^
713
714The :class:`StreamReaderWriter` allows wrapping streams which work in both read
715and write modes.
716
717The design is such that one can use the factory functions returned by the
718:func:`lookup` function to construct the instance.
719
720
721.. class:: StreamReaderWriter(stream, Reader, Writer, errors)
722
723 Creates a :class:`StreamReaderWriter` instance. *stream* must be a file-like
724 object. *Reader* and *Writer* must be factory functions or classes providing the
725 :class:`StreamReader` and :class:`StreamWriter` interface resp. Error handling
726 is done in the same way as defined for the stream readers and writers.
727
728:class:`StreamReaderWriter` instances define the combined interfaces of
729:class:`StreamReader` and :class:`StreamWriter` classes. They inherit all other
730methods and attributes from the underlying stream.
731
732
733.. _stream-recoder-objects:
734
735StreamRecoder Objects
736^^^^^^^^^^^^^^^^^^^^^
737
738The :class:`StreamRecoder` provide a frontend - backend view of encoding data
739which is sometimes useful when dealing with different encoding environments.
740
741The design is such that one can use the factory functions returned by the
742:func:`lookup` function to construct the instance.
743
744
745.. class:: StreamRecoder(stream, encode, decode, Reader, Writer, errors)
746
747 Creates a :class:`StreamRecoder` instance which implements a two-way conversion:
748 *encode* and *decode* work on the frontend (the input to :meth:`read` and output
749 of :meth:`write`) while *Reader* and *Writer* work on the backend (reading and
750 writing to the stream).
751
752 You can use these objects to do transparent direct recodings from e.g. Latin-1
753 to UTF-8 and back.
754
755 *stream* must be a file-like object.
756
757 *encode*, *decode* must adhere to the :class:`Codec` interface. *Reader*,
758 *Writer* must be factory functions or classes providing objects of the
759 :class:`StreamReader` and :class:`StreamWriter` interface respectively.
760
761 *encode* and *decode* are needed for the frontend translation, *Reader* and
Georg Brandl30c78d62008-05-11 14:52:00 +0000762 *Writer* for the backend translation.
Georg Brandl116aa622007-08-15 14:28:22 +0000763
764 Error handling is done in the same way as defined for the stream readers and
765 writers.
766
Benjamin Petersone41251e2008-04-25 01:59:09 +0000767
Georg Brandl116aa622007-08-15 14:28:22 +0000768:class:`StreamRecoder` instances define the combined interfaces of
769:class:`StreamReader` and :class:`StreamWriter` classes. They inherit all other
770methods and attributes from the underlying stream.
771
772
773.. _encodings-overview:
774
775Encodings and Unicode
776---------------------
777
Georg Brandl30c78d62008-05-11 14:52:00 +0000778Strings are stored internally as sequences of codepoints (to be precise
Georg Brandl116aa622007-08-15 14:28:22 +0000779as :ctype:`Py_UNICODE` arrays). Depending on the way Python is compiled (either
Georg Brandl52d168a2008-01-07 18:10:24 +0000780via :option:`--without-wide-unicode` or :option:`--with-wide-unicode`, with the
Georg Brandl116aa622007-08-15 14:28:22 +0000781former being the default) :ctype:`Py_UNICODE` is either a 16-bit or 32-bit data
Georg Brandl30c78d62008-05-11 14:52:00 +0000782type. Once a string object is used outside of CPU and memory, CPU endianness
Georg Brandl116aa622007-08-15 14:28:22 +0000783and how these arrays are stored as bytes become an issue. Transforming a
Georg Brandl30c78d62008-05-11 14:52:00 +0000784string object into a sequence of bytes is called encoding and recreating the
785string object from the sequence of bytes is known as decoding. There are many
Georg Brandl116aa622007-08-15 14:28:22 +0000786different methods for how this transformation can be done (these methods are
787also called encodings). The simplest method is to map the codepoints 0-255 to
Georg Brandl30c78d62008-05-11 14:52:00 +0000788the bytes ``0x0``-``0xff``. This means that a string object that contains
Georg Brandl116aa622007-08-15 14:28:22 +0000789codepoints above ``U+00FF`` can't be encoded with this method (which is called
Georg Brandl30c78d62008-05-11 14:52:00 +0000790``'latin-1'`` or ``'iso-8859-1'``). :func:`str.encode` will raise a
Georg Brandl116aa622007-08-15 14:28:22 +0000791:exc:`UnicodeEncodeError` that looks like this: ``UnicodeEncodeError: 'latin-1'
Georg Brandl30c78d62008-05-11 14:52:00 +0000792codec can't encode character '\u1234' in position 3: ordinal not in
Georg Brandl116aa622007-08-15 14:28:22 +0000793range(256)``.
794
795There's another group of encodings (the so called charmap encodings) that choose
Georg Brandl30c78d62008-05-11 14:52:00 +0000796a different subset of all Unicode code points and how these codepoints are
Georg Brandl116aa622007-08-15 14:28:22 +0000797mapped to the bytes ``0x0``-``0xff``. To see how this is done simply open
798e.g. :file:`encodings/cp1252.py` (which is an encoding that is used primarily on
799Windows). There's a string constant with 256 characters that shows you which
800character is mapped to which byte value.
801
802All of these encodings can only encode 256 of the 65536 (or 1114111) codepoints
Georg Brandl30c78d62008-05-11 14:52:00 +0000803defined in Unicode. A simple and straightforward way that can store each Unicode
Georg Brandl116aa622007-08-15 14:28:22 +0000804code point, is to store each codepoint as two consecutive bytes. There are two
805possibilities: Store the bytes in big endian or in little endian order. These
806two encodings are called UTF-16-BE and UTF-16-LE respectively. Their
807disadvantage is that if e.g. you use UTF-16-BE on a little endian machine you
808will always have to swap bytes on encoding and decoding. UTF-16 avoids this
809problem: Bytes will always be in natural endianness. When these bytes are read
810by a CPU with a different endianness, then bytes have to be swapped though. To
811be able to detect the endianness of a UTF-16 byte sequence, there's the so
812called BOM (the "Byte Order Mark"). This is the Unicode character ``U+FEFF``.
813This character will be prepended to every UTF-16 byte sequence. The byte swapped
814version of this character (``0xFFFE``) is an illegal character that may not
815appear in a Unicode text. So when the first character in an UTF-16 byte sequence
816appears to be a ``U+FFFE`` the bytes have to be swapped on decoding.
817Unfortunately upto Unicode 4.0 the character ``U+FEFF`` had a second purpose as
818a ``ZERO WIDTH NO-BREAK SPACE``: A character that has no width and doesn't allow
819a word to be split. It can e.g. be used to give hints to a ligature algorithm.
820With Unicode 4.0 using ``U+FEFF`` as a ``ZERO WIDTH NO-BREAK SPACE`` has been
821deprecated (with ``U+2060`` (``WORD JOINER``) assuming this role). Nevertheless
822Unicode software still must be able to handle ``U+FEFF`` in both roles: As a BOM
823it's a device to determine the storage layout of the encoded bytes, and vanishes
Georg Brandl30c78d62008-05-11 14:52:00 +0000824once the byte sequence has been decoded into a string; as a ``ZERO WIDTH
Georg Brandl116aa622007-08-15 14:28:22 +0000825NO-BREAK SPACE`` it's a normal character that will be decoded like any other.
826
827There's another encoding that is able to encoding the full range of Unicode
828characters: UTF-8. UTF-8 is an 8-bit encoding, which means there are no issues
829with byte order in UTF-8. Each byte in a UTF-8 byte sequence consists of two
830parts: Marker bits (the most significant bits) and payload bits. The marker bits
831are a sequence of zero to six 1 bits followed by a 0 bit. Unicode characters are
832encoded like this (with x being payload bits, which when concatenated give the
833Unicode character):
834
835+-----------------------------------+----------------------------------------------+
836| Range | Encoding |
837+===================================+==============================================+
838| ``U-00000000`` ... ``U-0000007F`` | 0xxxxxxx |
839+-----------------------------------+----------------------------------------------+
840| ``U-00000080`` ... ``U-000007FF`` | 110xxxxx 10xxxxxx |
841+-----------------------------------+----------------------------------------------+
842| ``U-00000800`` ... ``U-0000FFFF`` | 1110xxxx 10xxxxxx 10xxxxxx |
843+-----------------------------------+----------------------------------------------+
844| ``U-00010000`` ... ``U-001FFFFF`` | 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx |
845+-----------------------------------+----------------------------------------------+
846| ``U-00200000`` ... ``U-03FFFFFF`` | 111110xx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx |
847+-----------------------------------+----------------------------------------------+
848| ``U-04000000`` ... ``U-7FFFFFFF`` | 1111110x 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx |
849| | 10xxxxxx |
850+-----------------------------------+----------------------------------------------+
851
852The least significant bit of the Unicode character is the rightmost x bit.
853
854As UTF-8 is an 8-bit encoding no BOM is required and any ``U+FEFF`` character in
Georg Brandl30c78d62008-05-11 14:52:00 +0000855the decoded string (even if it's the first character) is treated as a ``ZERO
856WIDTH NO-BREAK SPACE``.
Georg Brandl116aa622007-08-15 14:28:22 +0000857
858Without external information it's impossible to reliably determine which
Georg Brandl30c78d62008-05-11 14:52:00 +0000859encoding was used for encoding a string. Each charmap encoding can
Georg Brandl116aa622007-08-15 14:28:22 +0000860decode any random byte sequence. However that's not possible with UTF-8, as
861UTF-8 byte sequences have a structure that doesn't allow arbitrary byte
Thomas Wouters89d996e2007-09-08 17:39:28 +0000862sequences. To increase the reliability with which a UTF-8 encoding can be
Georg Brandl116aa622007-08-15 14:28:22 +0000863detected, Microsoft invented a variant of UTF-8 (that Python 2.5 calls
864``"utf-8-sig"``) for its Notepad program: Before any of the Unicode characters
865is written to the file, a UTF-8 encoded BOM (which looks like this as a byte
866sequence: ``0xef``, ``0xbb``, ``0xbf``) is written. As it's rather improbable
867that any charmap encoded file starts with these byte values (which would e.g.
868map to
869
870 | LATIN SMALL LETTER I WITH DIAERESIS
871 | RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK
872 | INVERTED QUESTION MARK
873
874in iso-8859-1), this increases the probability that a utf-8-sig encoding can be
875correctly guessed from the byte sequence. So here the BOM is not used to be able
876to determine the byte order used for generating the byte sequence, but as a
877signature that helps in guessing the encoding. On encoding the utf-8-sig codec
878will write ``0xef``, ``0xbb``, ``0xbf`` as the first three bytes to the file. On
879decoding utf-8-sig will skip those three bytes if they appear as the first three
880bytes in the file.
881
882
883.. _standard-encodings:
884
885Standard Encodings
886------------------
887
888Python comes with a number of codecs built-in, either implemented as C functions
889or with dictionaries as mapping tables. The following table lists the codecs by
890name, together with a few common aliases, and the languages for which the
891encoding is likely used. Neither the list of aliases nor the list of languages
892is meant to be exhaustive. Notice that spelling alternatives that only differ in
893case or use a hyphen instead of an underscore are also valid aliases.
894
895Many of the character sets support the same languages. They vary in individual
896characters (e.g. whether the EURO SIGN is supported or not), and in the
897assignment of characters to code positions. For the European languages in
898particular, the following variants typically exist:
899
900* an ISO 8859 codeset
901
902* a Microsoft Windows code page, which is typically derived from a 8859 codeset,
903 but replaces control characters with additional graphic characters
904
905* an IBM EBCDIC code page
906
907* an IBM PC code page, which is ASCII compatible
908
909+-----------------+--------------------------------+--------------------------------+
910| Codec | Aliases | Languages |
911+=================+================================+================================+
912| ascii | 646, us-ascii | English |
913+-----------------+--------------------------------+--------------------------------+
914| big5 | big5-tw, csbig5 | Traditional Chinese |
915+-----------------+--------------------------------+--------------------------------+
916| big5hkscs | big5-hkscs, hkscs | Traditional Chinese |
917+-----------------+--------------------------------+--------------------------------+
918| cp037 | IBM037, IBM039 | English |
919+-----------------+--------------------------------+--------------------------------+
920| cp424 | EBCDIC-CP-HE, IBM424 | Hebrew |
921+-----------------+--------------------------------+--------------------------------+
922| cp437 | 437, IBM437 | English |
923+-----------------+--------------------------------+--------------------------------+
924| cp500 | EBCDIC-CP-BE, EBCDIC-CP-CH, | Western Europe |
925| | IBM500 | |
926+-----------------+--------------------------------+--------------------------------+
927| cp737 | | Greek |
928+-----------------+--------------------------------+--------------------------------+
929| cp775 | IBM775 | Baltic languages |
930+-----------------+--------------------------------+--------------------------------+
931| cp850 | 850, IBM850 | Western Europe |
932+-----------------+--------------------------------+--------------------------------+
933| cp852 | 852, IBM852 | Central and Eastern Europe |
934+-----------------+--------------------------------+--------------------------------+
935| cp855 | 855, IBM855 | Bulgarian, Byelorussian, |
936| | | Macedonian, Russian, Serbian |
937+-----------------+--------------------------------+--------------------------------+
938| cp856 | | Hebrew |
939+-----------------+--------------------------------+--------------------------------+
940| cp857 | 857, IBM857 | Turkish |
941+-----------------+--------------------------------+--------------------------------+
942| cp860 | 860, IBM860 | Portuguese |
943+-----------------+--------------------------------+--------------------------------+
944| cp861 | 861, CP-IS, IBM861 | Icelandic |
945+-----------------+--------------------------------+--------------------------------+
946| cp862 | 862, IBM862 | Hebrew |
947+-----------------+--------------------------------+--------------------------------+
948| cp863 | 863, IBM863 | Canadian |
949+-----------------+--------------------------------+--------------------------------+
950| cp864 | IBM864 | Arabic |
951+-----------------+--------------------------------+--------------------------------+
952| cp865 | 865, IBM865 | Danish, Norwegian |
953+-----------------+--------------------------------+--------------------------------+
954| cp866 | 866, IBM866 | Russian |
955+-----------------+--------------------------------+--------------------------------+
956| cp869 | 869, CP-GR, IBM869 | Greek |
957+-----------------+--------------------------------+--------------------------------+
958| cp874 | | Thai |
959+-----------------+--------------------------------+--------------------------------+
960| cp875 | | Greek |
961+-----------------+--------------------------------+--------------------------------+
962| cp932 | 932, ms932, mskanji, ms-kanji | Japanese |
963+-----------------+--------------------------------+--------------------------------+
964| cp949 | 949, ms949, uhc | Korean |
965+-----------------+--------------------------------+--------------------------------+
966| cp950 | 950, ms950 | Traditional Chinese |
967+-----------------+--------------------------------+--------------------------------+
968| cp1006 | | Urdu |
969+-----------------+--------------------------------+--------------------------------+
970| cp1026 | ibm1026 | Turkish |
971+-----------------+--------------------------------+--------------------------------+
972| cp1140 | ibm1140 | Western Europe |
973+-----------------+--------------------------------+--------------------------------+
974| cp1250 | windows-1250 | Central and Eastern Europe |
975+-----------------+--------------------------------+--------------------------------+
976| cp1251 | windows-1251 | Bulgarian, Byelorussian, |
977| | | Macedonian, Russian, Serbian |
978+-----------------+--------------------------------+--------------------------------+
979| cp1252 | windows-1252 | Western Europe |
980+-----------------+--------------------------------+--------------------------------+
981| cp1253 | windows-1253 | Greek |
982+-----------------+--------------------------------+--------------------------------+
983| cp1254 | windows-1254 | Turkish |
984+-----------------+--------------------------------+--------------------------------+
985| cp1255 | windows-1255 | Hebrew |
986+-----------------+--------------------------------+--------------------------------+
987| cp1256 | windows1256 | Arabic |
988+-----------------+--------------------------------+--------------------------------+
989| cp1257 | windows-1257 | Baltic languages |
990+-----------------+--------------------------------+--------------------------------+
991| cp1258 | windows-1258 | Vietnamese |
992+-----------------+--------------------------------+--------------------------------+
993| euc_jp | eucjp, ujis, u-jis | Japanese |
994+-----------------+--------------------------------+--------------------------------+
995| euc_jis_2004 | jisx0213, eucjis2004 | Japanese |
996+-----------------+--------------------------------+--------------------------------+
997| euc_jisx0213 | eucjisx0213 | Japanese |
998+-----------------+--------------------------------+--------------------------------+
999| euc_kr | euckr, korean, ksc5601, | Korean |
1000| | ks_c-5601, ks_c-5601-1987, | |
1001| | ksx1001, ks_x-1001 | |
1002+-----------------+--------------------------------+--------------------------------+
1003| gb2312 | chinese, csiso58gb231280, euc- | Simplified Chinese |
1004| | cn, euccn, eucgb2312-cn, | |
1005| | gb2312-1980, gb2312-80, iso- | |
1006| | ir-58 | |
1007+-----------------+--------------------------------+--------------------------------+
1008| gbk | 936, cp936, ms936 | Unified Chinese |
1009+-----------------+--------------------------------+--------------------------------+
1010| gb18030 | gb18030-2000 | Unified Chinese |
1011+-----------------+--------------------------------+--------------------------------+
1012| hz | hzgb, hz-gb, hz-gb-2312 | Simplified Chinese |
1013+-----------------+--------------------------------+--------------------------------+
1014| iso2022_jp | csiso2022jp, iso2022jp, | Japanese |
1015| | iso-2022-jp | |
1016+-----------------+--------------------------------+--------------------------------+
1017| iso2022_jp_1 | iso2022jp-1, iso-2022-jp-1 | Japanese |
1018+-----------------+--------------------------------+--------------------------------+
1019| iso2022_jp_2 | iso2022jp-2, iso-2022-jp-2 | Japanese, Korean, Simplified |
1020| | | Chinese, Western Europe, Greek |
1021+-----------------+--------------------------------+--------------------------------+
1022| iso2022_jp_2004 | iso2022jp-2004, | Japanese |
1023| | iso-2022-jp-2004 | |
1024+-----------------+--------------------------------+--------------------------------+
1025| iso2022_jp_3 | iso2022jp-3, iso-2022-jp-3 | Japanese |
1026+-----------------+--------------------------------+--------------------------------+
1027| iso2022_jp_ext | iso2022jp-ext, iso-2022-jp-ext | Japanese |
1028+-----------------+--------------------------------+--------------------------------+
1029| iso2022_kr | csiso2022kr, iso2022kr, | Korean |
1030| | iso-2022-kr | |
1031+-----------------+--------------------------------+--------------------------------+
1032| latin_1 | iso-8859-1, iso8859-1, 8859, | West Europe |
1033| | cp819, latin, latin1, L1 | |
1034+-----------------+--------------------------------+--------------------------------+
1035| iso8859_2 | iso-8859-2, latin2, L2 | Central and Eastern Europe |
1036+-----------------+--------------------------------+--------------------------------+
1037| iso8859_3 | iso-8859-3, latin3, L3 | Esperanto, Maltese |
1038+-----------------+--------------------------------+--------------------------------+
Christian Heimesc3f30c42008-02-22 16:37:40 +00001039| iso8859_4 | iso-8859-4, latin4, L4 | Baltic languages |
Georg Brandl116aa622007-08-15 14:28:22 +00001040+-----------------+--------------------------------+--------------------------------+
1041| iso8859_5 | iso-8859-5, cyrillic | Bulgarian, Byelorussian, |
1042| | | Macedonian, Russian, Serbian |
1043+-----------------+--------------------------------+--------------------------------+
1044| iso8859_6 | iso-8859-6, arabic | Arabic |
1045+-----------------+--------------------------------+--------------------------------+
1046| iso8859_7 | iso-8859-7, greek, greek8 | Greek |
1047+-----------------+--------------------------------+--------------------------------+
1048| iso8859_8 | iso-8859-8, hebrew | Hebrew |
1049+-----------------+--------------------------------+--------------------------------+
1050| iso8859_9 | iso-8859-9, latin5, L5 | Turkish |
1051+-----------------+--------------------------------+--------------------------------+
1052| iso8859_10 | iso-8859-10, latin6, L6 | Nordic languages |
1053+-----------------+--------------------------------+--------------------------------+
1054| iso8859_13 | iso-8859-13 | Baltic languages |
1055+-----------------+--------------------------------+--------------------------------+
1056| iso8859_14 | iso-8859-14, latin8, L8 | Celtic languages |
1057+-----------------+--------------------------------+--------------------------------+
1058| iso8859_15 | iso-8859-15 | Western Europe |
1059+-----------------+--------------------------------+--------------------------------+
1060| johab | cp1361, ms1361 | Korean |
1061+-----------------+--------------------------------+--------------------------------+
1062| koi8_r | | Russian |
1063+-----------------+--------------------------------+--------------------------------+
1064| koi8_u | | Ukrainian |
1065+-----------------+--------------------------------+--------------------------------+
1066| mac_cyrillic | maccyrillic | Bulgarian, Byelorussian, |
1067| | | Macedonian, Russian, Serbian |
1068+-----------------+--------------------------------+--------------------------------+
1069| mac_greek | macgreek | Greek |
1070+-----------------+--------------------------------+--------------------------------+
1071| mac_iceland | maciceland | Icelandic |
1072+-----------------+--------------------------------+--------------------------------+
1073| mac_latin2 | maclatin2, maccentraleurope | Central and Eastern Europe |
1074+-----------------+--------------------------------+--------------------------------+
1075| mac_roman | macroman | Western Europe |
1076+-----------------+--------------------------------+--------------------------------+
1077| mac_turkish | macturkish | Turkish |
1078+-----------------+--------------------------------+--------------------------------+
1079| ptcp154 | csptcp154, pt154, cp154, | Kazakh |
1080| | cyrillic-asian | |
1081+-----------------+--------------------------------+--------------------------------+
1082| shift_jis | csshiftjis, shiftjis, sjis, | Japanese |
1083| | s_jis | |
1084+-----------------+--------------------------------+--------------------------------+
1085| shift_jis_2004 | shiftjis2004, sjis_2004, | Japanese |
1086| | sjis2004 | |
1087+-----------------+--------------------------------+--------------------------------+
1088| shift_jisx0213 | shiftjisx0213, sjisx0213, | Japanese |
1089| | s_jisx0213 | |
1090+-----------------+--------------------------------+--------------------------------+
Walter Dörwald41980ca2007-08-16 21:55:45 +00001091| utf_32 | U32, utf32 | all languages |
1092+-----------------+--------------------------------+--------------------------------+
1093| utf_32_be | UTF-32BE | all languages |
1094+-----------------+--------------------------------+--------------------------------+
1095| utf_32_le | UTF-32LE | all languages |
1096+-----------------+--------------------------------+--------------------------------+
Georg Brandl116aa622007-08-15 14:28:22 +00001097| utf_16 | U16, utf16 | all languages |
1098+-----------------+--------------------------------+--------------------------------+
1099| utf_16_be | UTF-16BE | all languages (BMP only) |
1100+-----------------+--------------------------------+--------------------------------+
1101| utf_16_le | UTF-16LE | all languages (BMP only) |
1102+-----------------+--------------------------------+--------------------------------+
1103| utf_7 | U7, unicode-1-1-utf-7 | all languages |
1104+-----------------+--------------------------------+--------------------------------+
1105| utf_8 | U8, UTF, utf8 | all languages |
1106+-----------------+--------------------------------+--------------------------------+
1107| utf_8_sig | | all languages |
1108+-----------------+--------------------------------+--------------------------------+
1109
Georg Brandl226878c2007-08-31 10:15:37 +00001110.. XXX fix here, should be in above table
1111
Georg Brandl30c78d62008-05-11 14:52:00 +00001112+--------------------+---------+---------------------------+
1113| Codec | Aliases | Purpose |
1114+====================+=========+===========================+
1115| idna | | Implements :rfc:`3490`, |
1116| | | see also |
1117| | | :mod:`encodings.idna` |
1118+--------------------+---------+---------------------------+
1119| mbcs | dbcs | Windows only: Encode |
1120| | | operand according to the |
1121| | | ANSI codepage (CP_ACP) |
1122+--------------------+---------+---------------------------+
1123| palmos | | Encoding of PalmOS 3.5 |
1124+--------------------+---------+---------------------------+
1125| punycode | | Implements :rfc:`3492` |
1126+--------------------+---------+---------------------------+
1127| raw_unicode_escape | | Produce a string that is |
1128| | | suitable as raw Unicode |
1129| | | literal in Python source |
1130| | | code |
1131+--------------------+---------+---------------------------+
1132| undefined | | Raise an exception for |
1133| | | all conversions. Can be |
1134| | | used as the system |
1135| | | encoding if no automatic |
1136| | | coercion between byte and |
1137| | | Unicode strings is |
1138| | | desired. |
1139+--------------------+---------+---------------------------+
1140| unicode_escape | | Produce a string that is |
1141| | | suitable as Unicode |
1142| | | literal in Python source |
1143| | | code |
1144+--------------------+---------+---------------------------+
1145| unicode_internal | | Return the internal |
1146| | | representation of the |
1147| | | operand |
1148+--------------------+---------+---------------------------+
Georg Brandl116aa622007-08-15 14:28:22 +00001149
Georg Brandl116aa622007-08-15 14:28:22 +00001150
1151:mod:`encodings.idna` --- Internationalized Domain Names in Applications
1152------------------------------------------------------------------------
1153
1154.. module:: encodings.idna
1155 :synopsis: Internationalized Domain Names implementation
1156.. moduleauthor:: Martin v. Löwis
1157
Georg Brandl116aa622007-08-15 14:28:22 +00001158This module implements :rfc:`3490` (Internationalized Domain Names in
1159Applications) and :rfc:`3492` (Nameprep: A Stringprep Profile for
1160Internationalized Domain Names (IDN)). It builds upon the ``punycode`` encoding
1161and :mod:`stringprep`.
1162
1163These RFCs together define a protocol to support non-ASCII characters in domain
1164names. A domain name containing non-ASCII characters (such as
1165``www.Alliancefrançaise.nu``) is converted into an ASCII-compatible encoding
1166(ACE, such as ``www.xn--alliancefranaise-npb.nu``). The ACE form of the domain
1167name is then used in all places where arbitrary characters are not allowed by
1168the protocol, such as DNS queries, HTTP :mailheader:`Host` fields, and so
1169on. This conversion is carried out in the application; if possible invisible to
1170the user: The application should transparently convert Unicode domain labels to
1171IDNA on the wire, and convert back ACE labels to Unicode before presenting them
1172to the user.
1173
1174Python supports this conversion in several ways: The ``idna`` codec allows to
1175convert between Unicode and the ACE. Furthermore, the :mod:`socket` module
1176transparently converts Unicode host names to ACE, so that applications need not
1177be concerned about converting host names themselves when they pass them to the
1178socket module. On top of that, modules that have host names as function
Georg Brandl24420152008-05-26 16:32:26 +00001179parameters, such as :mod:`http.client` and :mod:`ftplib`, accept Unicode host
1180names (:mod:`http.client` then also transparently sends an IDNA hostname in the
Georg Brandl116aa622007-08-15 14:28:22 +00001181:mailheader:`Host` field if it sends that field at all).
1182
1183When receiving host names from the wire (such as in reverse name lookup), no
1184automatic conversion to Unicode is performed: Applications wishing to present
1185such host names to the user should decode them to Unicode.
1186
1187The module :mod:`encodings.idna` also implements the nameprep procedure, which
1188performs certain normalizations on host names, to achieve case-insensitivity of
1189international domain names, and to unify similar characters. The nameprep
1190functions can be used directly if desired.
1191
1192
1193.. function:: nameprep(label)
1194
1195 Return the nameprepped version of *label*. The implementation currently assumes
1196 query strings, so ``AllowUnassigned`` is true.
1197
1198
1199.. function:: ToASCII(label)
1200
1201 Convert a label to ASCII, as specified in :rfc:`3490`. ``UseSTD3ASCIIRules`` is
1202 assumed to be false.
1203
1204
1205.. function:: ToUnicode(label)
1206
1207 Convert a label to Unicode, as specified in :rfc:`3490`.
1208
1209
1210:mod:`encodings.utf_8_sig` --- UTF-8 codec with BOM signature
1211-------------------------------------------------------------
1212
1213.. module:: encodings.utf_8_sig
1214 :synopsis: UTF-8 codec with BOM signature
1215.. moduleauthor:: Walter Dörwald
1216
Georg Brandl116aa622007-08-15 14:28:22 +00001217This module implements a variant of the UTF-8 codec: On encoding a UTF-8 encoded
1218BOM will be prepended to the UTF-8 encoded bytes. For the stateful encoder this
1219is only done once (on the first write to the byte stream). For decoding an
1220optional UTF-8 encoded BOM at the start of the data will be skipped.
1221