blob: 13b466564f77f3a72299d3ecb85e0c35df86cc30 [file] [log] [blame]
Georg Brandl8ec7f652007-08-15 14:28:01 +00001
2:mod:`codecs` --- Codec registry and base classes
3=================================================
4
5.. module:: codecs
6 :synopsis: Encode and decode data and streams.
7.. moduleauthor:: Marc-Andre Lemburg <mal@lemburg.com>
8.. sectionauthor:: Marc-Andre Lemburg <mal@lemburg.com>
9.. sectionauthor:: Martin v. Löwis <martin@v.loewis.de>
10
11
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
26
27.. function:: register(search_function)
28
29 Register a codec search function. Search functions are expected to take one
30 argument, the encoding name in all lower case letters, and return a
31 :class:`CodecInfo` object having the following attributes:
32
33 * ``name`` The name of the encoding;
34
Walter Dörwald611e48c2008-10-23 13:11:39 +000035 * ``encode`` The stateless encoding function;
Georg Brandl8ec7f652007-08-15 14:28:01 +000036
Walter Dörwald611e48c2008-10-23 13:11:39 +000037 * ``decode`` The stateless decoding function;
Georg Brandl8ec7f652007-08-15 14:28:01 +000038
39 * ``incrementalencoder`` An incremental encoder class or factory function;
40
41 * ``incrementaldecoder`` An incremental decoder class or factory function;
42
43 * ``streamwriter`` A stream writer class or factory function;
44
45 * ``streamreader`` A stream reader class or factory function.
46
47 The various functions or classes take the following arguments:
48
Walter Dörwald611e48c2008-10-23 13:11:39 +000049 *encode* and *decode*: These must be functions or methods which have the same
Georg Brandl8ec7f652007-08-15 14:28:01 +000050 interface as the :meth:`encode`/:meth:`decode` methods of Codec instances (see
51 Codec Interface). The functions/methods are expected to work in a stateless
52 mode.
53
Georg Brandl2ba93212008-09-01 14:15:55 +000054 *incrementalencoder* and *incrementaldecoder*: These have to be factory
Georg Brandl8ec7f652007-08-15 14:28:01 +000055 functions providing the following interface:
56
Georg Brandlf4ffae22009-10-22 15:42:32 +000057 ``factory(errors='strict')``
Georg Brandl8ec7f652007-08-15 14:28:01 +000058
59 The factory functions must return objects providing the interfaces defined by
Georg Brandl2ba93212008-09-01 14:15:55 +000060 the base classes :class:`IncrementalEncoder` and :class:`IncrementalDecoder`,
Georg Brandl8ec7f652007-08-15 14:28:01 +000061 respectively. Incremental codecs can maintain state.
62
63 *streamreader* and *streamwriter*: These have to be factory functions providing
64 the following interface:
65
Georg Brandlf4ffae22009-10-22 15:42:32 +000066 ``factory(stream, errors='strict')``
Georg Brandl8ec7f652007-08-15 14:28:01 +000067
68 The factory functions must return objects providing the interfaces defined by
69 the base classes :class:`StreamWriter` and :class:`StreamReader`, respectively.
70 Stream codecs can maintain state.
71
Georg Brandlf4ffae22009-10-22 15:42:32 +000072 Possible values for errors are
73
74 * ``'strict'``: raise an exception in case of an encoding error
75 * ``'replace'``: replace malformed data with a suitable replacement marker,
76 such as ``'?'`` or ``'\ufffd'``
77 * ``'ignore'``: ignore malformed data and continue without further notice
78 * ``'xmlcharrefreplace'``: replace with the appropriate XML character
79 reference (for encoding only)
80 * ``'backslashreplace'``: replace with backslashed escape sequences (for
Ezio Melotti8dd547f2010-02-27 13:50:35 +000081 encoding only)
Georg Brandlf4ffae22009-10-22 15:42:32 +000082
83 as well as any other error handling name defined via :func:`register_error`.
Georg Brandl8ec7f652007-08-15 14:28:01 +000084
85 In case a search function cannot find a given encoding, it should return
86 ``None``.
87
88
89.. function:: lookup(encoding)
90
91 Looks up the codec info in the Python codec registry and returns a
92 :class:`CodecInfo` object as defined above.
93
94 Encodings are first looked up in the registry's cache. If not found, the list of
95 registered search functions is scanned. If no :class:`CodecInfo` object is
96 found, a :exc:`LookupError` is raised. Otherwise, the :class:`CodecInfo` object
97 is stored in the cache and returned to the caller.
98
99To simplify access to the various codecs, the module provides these additional
100functions which use :func:`lookup` for the codec lookup:
101
102
103.. function:: getencoder(encoding)
104
105 Look up the codec for the given encoding and return its encoder function.
106
107 Raises a :exc:`LookupError` in case the encoding cannot be found.
108
109
110.. function:: getdecoder(encoding)
111
112 Look up the codec for the given encoding and return its decoder function.
113
114 Raises a :exc:`LookupError` in case the encoding cannot be found.
115
116
117.. function:: getincrementalencoder(encoding)
118
119 Look up the codec for the given encoding and return its incremental encoder
120 class or factory function.
121
122 Raises a :exc:`LookupError` in case the encoding cannot be found or the codec
123 doesn't support an incremental encoder.
124
125 .. versionadded:: 2.5
126
127
128.. function:: getincrementaldecoder(encoding)
129
130 Look up the codec for the given encoding and return its incremental decoder
131 class or factory function.
132
133 Raises a :exc:`LookupError` in case the encoding cannot be found or the codec
134 doesn't support an incremental decoder.
135
136 .. versionadded:: 2.5
137
138
139.. function:: getreader(encoding)
140
141 Look up the codec for the given encoding and return its StreamReader class or
142 factory function.
143
144 Raises a :exc:`LookupError` in case the encoding cannot be found.
145
146
147.. function:: getwriter(encoding)
148
149 Look up the codec for the given encoding and return its StreamWriter class or
150 factory function.
151
152 Raises a :exc:`LookupError` in case the encoding cannot be found.
153
154
155.. function:: register_error(name, error_handler)
156
157 Register the error handling function *error_handler* under the name *name*.
158 *error_handler* will be called during encoding and decoding in case of an error,
159 when *name* is specified as the errors parameter.
160
161 For encoding *error_handler* will be called with a :exc:`UnicodeEncodeError`
162 instance, which contains information about the location of the error. The error
163 handler must either raise this or a different exception or return a tuple with a
164 replacement for the unencodable part of the input and a position where encoding
165 should continue. The encoder will encode the replacement and continue encoding
166 the original input at the specified position. Negative position values will be
167 treated as being relative to the end of the input string. If the resulting
168 position is out of bound an :exc:`IndexError` will be raised.
169
170 Decoding and translating works similar, except :exc:`UnicodeDecodeError` or
171 :exc:`UnicodeTranslateError` will be passed to the handler and that the
172 replacement from the error handler will be put into the output directly.
173
174
175.. function:: lookup_error(name)
176
177 Return the error handler previously registered under the name *name*.
178
179 Raises a :exc:`LookupError` in case the handler cannot be found.
180
181
182.. function:: strict_errors(exception)
183
Georg Brandlf4ffae22009-10-22 15:42:32 +0000184 Implements the ``strict`` error handling: each encoding or decoding error
185 raises a :exc:`UnicodeError`.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000186
187
188.. function:: replace_errors(exception)
189
Georg Brandlf4ffae22009-10-22 15:42:32 +0000190 Implements the ``replace`` error handling: malformed data is replaced with a
191 suitable replacement character such as ``'?'`` in bytestrings and
192 ``'\ufffd'`` in Unicode strings.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000193
194
195.. function:: ignore_errors(exception)
196
Georg Brandlf4ffae22009-10-22 15:42:32 +0000197 Implements the ``ignore`` error handling: malformed data is ignored and
198 encoding or decoding is continued without further notice.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000199
200
Walter Dörwald90014e02007-09-01 18:18:09 +0000201.. function:: xmlcharrefreplace_errors(exception)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000202
Georg Brandlf4ffae22009-10-22 15:42:32 +0000203 Implements the ``xmlcharrefreplace`` error handling (for encoding only): the
204 unencodable character is replaced by an appropriate XML character reference.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000205
206
Walter Dörwald90014e02007-09-01 18:18:09 +0000207.. function:: backslashreplace_errors(exception)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000208
Georg Brandlf4ffae22009-10-22 15:42:32 +0000209 Implements the ``backslashreplace`` error handling (for encoding only): the
210 unencodable character is replaced by a backslashed escape sequence.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000211
212To simplify working with encoded files or stream, the module also defines these
213utility functions:
214
215
216.. function:: open(filename, mode[, encoding[, errors[, buffering]]])
217
218 Open an encoded file using the given *mode* and return a wrapped version
Georg Brandl5e203f52008-02-17 11:33:38 +0000219 providing transparent encoding/decoding. The default file mode is ``'r'``
220 meaning to open the file in read mode.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000221
222 .. note::
223
224 The wrapped version will only accept the object format defined by the codecs,
225 i.e. Unicode objects for most built-in codecs. Output is also codec-dependent
226 and will usually be Unicode as well.
227
Georg Brandl5e203f52008-02-17 11:33:38 +0000228 .. note::
229
230 Files are always opened in binary mode, even if no binary mode was
231 specified. This is done to avoid data loss due to encodings using 8-bit
232 values. This means that no automatic conversion of ``'\n'`` is done
233 on reading and writing.
234
Georg Brandl8ec7f652007-08-15 14:28:01 +0000235 *encoding* specifies the encoding which is to be used for the file.
236
237 *errors* may be given to define the error handling. It defaults to ``'strict'``
238 which causes a :exc:`ValueError` to be raised in case an encoding error occurs.
239
240 *buffering* has the same meaning as for the built-in :func:`open` function. It
241 defaults to line buffered.
242
243
244.. function:: EncodedFile(file, input[, output[, errors]])
245
246 Return a wrapped version of file which provides transparent encoding
247 translation.
248
249 Strings written to the wrapped file are interpreted according to the given
250 *input* encoding and then written to the original file as strings using the
251 *output* encoding. The intermediate encoding will usually be Unicode but depends
252 on the specified codecs.
253
254 If *output* is not given, it defaults to *input*.
255
256 *errors* may be given to define the error handling. It defaults to ``'strict'``,
257 which causes :exc:`ValueError` to be raised in case an encoding error occurs.
258
259
260.. function:: iterencode(iterable, encoding[, errors])
261
262 Uses an incremental encoder to iteratively encode the input provided by
Georg Brandlcf3fb252007-10-21 10:52:38 +0000263 *iterable*. This function is a :term:`generator`. *errors* (as well as any
264 other keyword argument) is passed through to the incremental encoder.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000265
266 .. versionadded:: 2.5
267
268
269.. function:: iterdecode(iterable, encoding[, errors])
270
271 Uses an incremental decoder to iteratively decode the input provided by
Georg Brandlcf3fb252007-10-21 10:52:38 +0000272 *iterable*. This function is a :term:`generator`. *errors* (as well as any
273 other keyword argument) is passed through to the incremental decoder.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000274
275 .. versionadded:: 2.5
276
277The module also provides the following constants which are useful for reading
278and writing to platform dependent files:
279
280
281.. data:: BOM
282 BOM_BE
283 BOM_LE
284 BOM_UTF8
285 BOM_UTF16
286 BOM_UTF16_BE
287 BOM_UTF16_LE
288 BOM_UTF32
289 BOM_UTF32_BE
290 BOM_UTF32_LE
291
292 These constants define various encodings of the Unicode byte order mark (BOM)
293 used in UTF-16 and UTF-32 data streams to indicate the byte order used in the
294 stream or file and in UTF-8 as a Unicode signature. :const:`BOM_UTF16` is either
295 :const:`BOM_UTF16_BE` or :const:`BOM_UTF16_LE` depending on the platform's
296 native byte order, :const:`BOM` is an alias for :const:`BOM_UTF16`,
297 :const:`BOM_LE` for :const:`BOM_UTF16_LE` and :const:`BOM_BE` for
298 :const:`BOM_UTF16_BE`. The others represent the BOM in UTF-8 and UTF-32
299 encodings.
300
301
302.. _codec-base-classes:
303
304Codec Base Classes
305------------------
306
307The :mod:`codecs` module defines a set of base classes which define the
Benjamin Peterson06abba32008-05-26 20:43:24 +0000308interface and can also be used to easily write your own codecs for use in
309Python.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000310
311Each codec has to define four interfaces to make it usable as codec in Python:
312stateless encoder, stateless decoder, stream reader and stream writer. The
313stream reader and writers typically reuse the stateless encoder/decoder to
314implement the file protocols.
315
316The :class:`Codec` class defines the interface for stateless encoders/decoders.
317
318To simplify and standardize error handling, the :meth:`encode` and
319:meth:`decode` methods may implement different error handling schemes by
320providing the *errors* string argument. The following string values are defined
321and implemented by all standard Python codecs:
322
323+-------------------------+-----------------------------------------------+
324| Value | Meaning |
325+=========================+===============================================+
326| ``'strict'`` | Raise :exc:`UnicodeError` (or a subclass); |
327| | this is the default. |
328+-------------------------+-----------------------------------------------+
329| ``'ignore'`` | Ignore the character and continue with the |
330| | next. |
331+-------------------------+-----------------------------------------------+
332| ``'replace'`` | Replace with a suitable replacement |
333| | character; Python will use the official |
334| | U+FFFD REPLACEMENT CHARACTER for the built-in |
335| | Unicode codecs on decoding and '?' on |
336| | encoding. |
337+-------------------------+-----------------------------------------------+
338| ``'xmlcharrefreplace'`` | Replace with the appropriate XML character |
339| | reference (only for encoding). |
340+-------------------------+-----------------------------------------------+
341| ``'backslashreplace'`` | Replace with backslashed escape sequences |
342| | (only for encoding). |
343+-------------------------+-----------------------------------------------+
344
345The set of allowed values can be extended via :meth:`register_error`.
346
347
348.. _codec-objects:
349
350Codec Objects
351^^^^^^^^^^^^^
352
353The :class:`Codec` class defines these methods which also define the function
354interfaces of the stateless encoder and decoder:
355
356
357.. method:: Codec.encode(input[, errors])
358
359 Encodes the object *input* and returns a tuple (output object, length consumed).
360 While codecs are not restricted to use with Unicode, in a Unicode context,
361 encoding converts a Unicode object to a plain string using a particular
362 character set encoding (e.g., ``cp1252`` or ``iso-8859-1``).
363
364 *errors* defines the error handling to apply. It defaults to ``'strict'``
365 handling.
366
367 The method may not store state in the :class:`Codec` instance. Use
368 :class:`StreamCodec` for codecs which have to keep state in order to make
369 encoding/decoding efficient.
370
371 The encoder must be able to handle zero length input and return an empty object
372 of the output object type in this situation.
373
374
375.. method:: Codec.decode(input[, errors])
376
377 Decodes the object *input* and returns a tuple (output object, length consumed).
378 In a Unicode context, decoding converts a plain string encoded using a
379 particular character set encoding to a Unicode object.
380
381 *input* must be an object which provides the ``bf_getreadbuf`` buffer slot.
382 Python strings, buffer objects and memory mapped files are examples of objects
383 providing this slot.
384
385 *errors* defines the error handling to apply. It defaults to ``'strict'``
386 handling.
387
388 The method may not store state in the :class:`Codec` instance. Use
389 :class:`StreamCodec` for codecs which have to keep state in order to make
390 encoding/decoding efficient.
391
392 The decoder must be able to handle zero length input and return an empty object
393 of the output object type in this situation.
394
395The :class:`IncrementalEncoder` and :class:`IncrementalDecoder` classes provide
396the basic interface for incremental encoding and decoding. Encoding/decoding the
397input isn't done with one call to the stateless encoder/decoder function, but
398with multiple calls to the :meth:`encode`/:meth:`decode` method of the
399incremental encoder/decoder. The incremental encoder/decoder keeps track of the
400encoding/decoding process during method calls.
401
402The joined output of calls to the :meth:`encode`/:meth:`decode` method is the
403same as if all the single inputs were joined into one, and this input was
404encoded/decoded with the stateless encoder/decoder.
405
406
407.. _incremental-encoder-objects:
408
409IncrementalEncoder Objects
410^^^^^^^^^^^^^^^^^^^^^^^^^^
411
412.. versionadded:: 2.5
413
414The :class:`IncrementalEncoder` class is used for encoding an input in multiple
415steps. It defines the following methods which every incremental encoder must
416define in order to be compatible with the Python codec registry.
417
418
419.. class:: IncrementalEncoder([errors])
420
421 Constructor for an :class:`IncrementalEncoder` instance.
422
423 All incremental encoders must provide this constructor interface. They are free
424 to add additional keyword arguments, but only the ones defined here are used by
425 the Python codec registry.
426
427 The :class:`IncrementalEncoder` may implement different error handling schemes
428 by providing the *errors* keyword argument. These parameters are predefined:
429
430 * ``'strict'`` Raise :exc:`ValueError` (or a subclass); this is the default.
431
432 * ``'ignore'`` Ignore the character and continue with the next.
433
434 * ``'replace'`` Replace with a suitable replacement character
435
436 * ``'xmlcharrefreplace'`` Replace with the appropriate XML character reference
437
438 * ``'backslashreplace'`` Replace with backslashed escape sequences.
439
440 The *errors* argument will be assigned to an attribute of the same name.
441 Assigning to this attribute makes it possible to switch between different error
442 handling strategies during the lifetime of the :class:`IncrementalEncoder`
443 object.
444
445 The set of allowed values for the *errors* argument can be extended with
446 :func:`register_error`.
447
448
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000449 .. method:: encode(object[, final])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000450
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000451 Encodes *object* (taking the current state of the encoder into account)
452 and returns the resulting encoded object. If this is the last call to
453 :meth:`encode` *final* must be true (the default is false).
Georg Brandl8ec7f652007-08-15 14:28:01 +0000454
455
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000456 .. method:: reset()
Georg Brandl8ec7f652007-08-15 14:28:01 +0000457
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000458 Reset the encoder to the initial state.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000459
460
461.. _incremental-decoder-objects:
462
463IncrementalDecoder Objects
464^^^^^^^^^^^^^^^^^^^^^^^^^^
465
466The :class:`IncrementalDecoder` class is used for decoding an input in multiple
467steps. It defines the following methods which every incremental decoder must
468define in order to be compatible with the Python codec registry.
469
470
471.. class:: IncrementalDecoder([errors])
472
473 Constructor for an :class:`IncrementalDecoder` instance.
474
475 All incremental decoders must provide this constructor interface. They are free
476 to add additional keyword arguments, but only the ones defined here are used by
477 the Python codec registry.
478
479 The :class:`IncrementalDecoder` may implement different error handling schemes
480 by providing the *errors* keyword argument. These parameters are predefined:
481
482 * ``'strict'`` Raise :exc:`ValueError` (or a subclass); this is the default.
483
484 * ``'ignore'`` Ignore the character and continue with the next.
485
486 * ``'replace'`` Replace with a suitable replacement character.
487
488 The *errors* argument will be assigned to an attribute of the same name.
489 Assigning to this attribute makes it possible to switch between different error
Georg Brandl2ba93212008-09-01 14:15:55 +0000490 handling strategies during the lifetime of the :class:`IncrementalDecoder`
Georg Brandl8ec7f652007-08-15 14:28:01 +0000491 object.
492
493 The set of allowed values for the *errors* argument can be extended with
494 :func:`register_error`.
495
496
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000497 .. method:: decode(object[, final])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000498
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000499 Decodes *object* (taking the current state of the decoder into account)
500 and returns the resulting decoded object. If this is the last call to
501 :meth:`decode` *final* must be true (the default is false). If *final* is
502 true the decoder must decode the input completely and must flush all
503 buffers. If this isn't possible (e.g. because of incomplete byte sequences
504 at the end of the input) it must initiate error handling just like in the
505 stateless case (which might raise an exception).
Georg Brandl8ec7f652007-08-15 14:28:01 +0000506
507
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000508 .. method:: reset()
Georg Brandl8ec7f652007-08-15 14:28:01 +0000509
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000510 Reset the decoder to the initial state.
511
Georg Brandl8ec7f652007-08-15 14:28:01 +0000512
513The :class:`StreamWriter` and :class:`StreamReader` classes provide generic
514working interfaces which can be used to implement new encoding submodules very
515easily. See :mod:`encodings.utf_8` for an example of how this is done.
516
517
518.. _stream-writer-objects:
519
520StreamWriter Objects
521^^^^^^^^^^^^^^^^^^^^
522
523The :class:`StreamWriter` class is a subclass of :class:`Codec` and defines the
524following methods which every stream writer must define in order to be
525compatible with the Python codec registry.
526
527
528.. class:: StreamWriter(stream[, errors])
529
530 Constructor for a :class:`StreamWriter` instance.
531
532 All stream writers must provide this constructor interface. They are free to add
533 additional keyword arguments, but only the ones defined here are used by the
534 Python codec registry.
535
536 *stream* must be a file-like object open for writing binary data.
537
538 The :class:`StreamWriter` may implement different error handling schemes by
539 providing the *errors* keyword argument. These parameters are predefined:
540
541 * ``'strict'`` Raise :exc:`ValueError` (or a subclass); this is the default.
542
543 * ``'ignore'`` Ignore the character and continue with the next.
544
545 * ``'replace'`` Replace with a suitable replacement character
546
547 * ``'xmlcharrefreplace'`` Replace with the appropriate XML character reference
548
549 * ``'backslashreplace'`` Replace with backslashed escape sequences.
550
551 The *errors* argument will be assigned to an attribute of the same name.
552 Assigning to this attribute makes it possible to switch between different error
553 handling strategies during the lifetime of the :class:`StreamWriter` object.
554
555 The set of allowed values for the *errors* argument can be extended with
556 :func:`register_error`.
557
558
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000559 .. method:: write(object)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000560
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000561 Writes the object's contents encoded to the stream.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000562
563
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000564 .. method:: writelines(list)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000565
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000566 Writes the concatenated list of strings to the stream (possibly by reusing
567 the :meth:`write` method).
Georg Brandl8ec7f652007-08-15 14:28:01 +0000568
569
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000570 .. method:: reset()
Georg Brandl8ec7f652007-08-15 14:28:01 +0000571
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000572 Flushes and resets the codec buffers used for keeping state.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000573
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000574 Calling this method should ensure that the data on the output is put into
575 a clean state that allows appending of new fresh data without having to
576 rescan the whole stream to recover state.
577
Georg Brandl8ec7f652007-08-15 14:28:01 +0000578
579In addition to the above methods, the :class:`StreamWriter` must also inherit
580all other methods and attributes from the underlying stream.
581
582
583.. _stream-reader-objects:
584
585StreamReader Objects
586^^^^^^^^^^^^^^^^^^^^
587
588The :class:`StreamReader` class is a subclass of :class:`Codec` and defines the
589following methods which every stream reader must define in order to be
590compatible with the Python codec registry.
591
592
593.. class:: StreamReader(stream[, errors])
594
595 Constructor for a :class:`StreamReader` instance.
596
597 All stream readers must provide this constructor interface. They are free to add
598 additional keyword arguments, but only the ones defined here are used by the
599 Python codec registry.
600
601 *stream* must be a file-like object open for reading (binary) data.
602
603 The :class:`StreamReader` may implement different error handling schemes by
604 providing the *errors* keyword argument. These parameters are defined:
605
606 * ``'strict'`` Raise :exc:`ValueError` (or a subclass); this is the default.
607
608 * ``'ignore'`` Ignore the character and continue with the next.
609
610 * ``'replace'`` Replace with a suitable replacement character.
611
612 The *errors* argument will be assigned to an attribute of the same name.
613 Assigning to this attribute makes it possible to switch between different error
614 handling strategies during the lifetime of the :class:`StreamReader` object.
615
616 The set of allowed values for the *errors* argument can be extended with
617 :func:`register_error`.
618
619
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000620 .. method:: read([size[, chars, [firstline]]])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000621
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000622 Decodes data from the stream and returns the resulting object.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000623
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000624 *chars* indicates the number of characters to read from the
625 stream. :func:`read` will never return more than *chars* characters, but
626 it might return less, if there are not enough characters available.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000627
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000628 *size* indicates the approximate maximum number of bytes to read from the
629 stream for decoding purposes. The decoder can modify this setting as
630 appropriate. The default value -1 indicates to read and decode as much as
631 possible. *size* is intended to prevent having to decode huge files in
632 one step.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000633
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000634 *firstline* indicates that it would be sufficient to only return the first
635 line, if there are decoding errors on later lines.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000636
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000637 The method should use a greedy read strategy meaning that it should read
638 as much data as is allowed within the definition of the encoding and the
639 given size, e.g. if optional encoding endings or state markers are
640 available on the stream, these should be read too.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000641
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000642 .. versionchanged:: 2.4
643 *chars* argument added.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000644
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000645 .. versionchanged:: 2.4.2
646 *firstline* argument added.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000647
648
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000649 .. method:: readline([size[, keepends]])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000650
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000651 Read one line from the input stream and return the decoded data.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000652
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000653 *size*, if given, is passed as size argument to the stream's
654 :meth:`readline` method.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000655
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000656 If *keepends* is false line-endings will be stripped from the lines
657 returned.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000658
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000659 .. versionchanged:: 2.4
660 *keepends* argument added.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000661
662
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000663 .. method:: readlines([sizehint[, keepends]])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000664
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000665 Read all lines available on the input stream and return them as a list of
666 lines.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000667
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000668 Line-endings are implemented using the codec's decoder method and are
669 included in the list entries if *keepends* is true.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000670
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000671 *sizehint*, if given, is passed as the *size* argument to the stream's
672 :meth:`read` method.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000673
674
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000675 .. method:: reset()
Georg Brandl8ec7f652007-08-15 14:28:01 +0000676
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000677 Resets the codec buffers used for keeping state.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000678
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000679 Note that no stream repositioning should take place. This method is
680 primarily intended to be able to recover from decoding errors.
681
Georg Brandl8ec7f652007-08-15 14:28:01 +0000682
683In addition to the above methods, the :class:`StreamReader` must also inherit
684all other methods and attributes from the underlying stream.
685
686The next two base classes are included for convenience. They are not needed by
687the codec registry, but may provide useful in practice.
688
689
690.. _stream-reader-writer:
691
692StreamReaderWriter Objects
693^^^^^^^^^^^^^^^^^^^^^^^^^^
694
695The :class:`StreamReaderWriter` allows wrapping streams which work in both read
696and write modes.
697
698The design is such that one can use the factory functions returned by the
699:func:`lookup` function to construct the instance.
700
701
702.. class:: StreamReaderWriter(stream, Reader, Writer, errors)
703
704 Creates a :class:`StreamReaderWriter` instance. *stream* must be a file-like
705 object. *Reader* and *Writer* must be factory functions or classes providing the
706 :class:`StreamReader` and :class:`StreamWriter` interface resp. Error handling
707 is done in the same way as defined for the stream readers and writers.
708
709:class:`StreamReaderWriter` instances define the combined interfaces of
710:class:`StreamReader` and :class:`StreamWriter` classes. They inherit all other
711methods and attributes from the underlying stream.
712
713
714.. _stream-recoder-objects:
715
716StreamRecoder Objects
717^^^^^^^^^^^^^^^^^^^^^
718
719The :class:`StreamRecoder` provide a frontend - backend view of encoding data
720which is sometimes useful when dealing with different encoding environments.
721
722The design is such that one can use the factory functions returned by the
723:func:`lookup` function to construct the instance.
724
725
726.. class:: StreamRecoder(stream, encode, decode, Reader, Writer, errors)
727
728 Creates a :class:`StreamRecoder` instance which implements a two-way conversion:
729 *encode* and *decode* work on the frontend (the input to :meth:`read` and output
730 of :meth:`write`) while *Reader* and *Writer* work on the backend (reading and
731 writing to the stream).
732
733 You can use these objects to do transparent direct recodings from e.g. Latin-1
734 to UTF-8 and back.
735
736 *stream* must be a file-like object.
737
738 *encode*, *decode* must adhere to the :class:`Codec` interface. *Reader*,
739 *Writer* must be factory functions or classes providing objects of the
740 :class:`StreamReader` and :class:`StreamWriter` interface respectively.
741
742 *encode* and *decode* are needed for the frontend translation, *Reader* and
743 *Writer* for the backend translation. The intermediate format used is
744 determined by the two sets of codecs, e.g. the Unicode codecs will use Unicode
745 as the intermediate encoding.
746
747 Error handling is done in the same way as defined for the stream readers and
748 writers.
749
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000750
Georg Brandl8ec7f652007-08-15 14:28:01 +0000751:class:`StreamRecoder` instances define the combined interfaces of
752:class:`StreamReader` and :class:`StreamWriter` classes. They inherit all other
753methods and attributes from the underlying stream.
754
755
756.. _encodings-overview:
757
758Encodings and Unicode
759---------------------
760
761Unicode strings are stored internally as sequences of codepoints (to be precise
762as :ctype:`Py_UNICODE` arrays). Depending on the way Python is compiled (either
763via :option:`--enable-unicode=ucs2` or :option:`--enable-unicode=ucs4`, with the
764former being the default) :ctype:`Py_UNICODE` is either a 16-bit or 32-bit data
765type. Once a Unicode object is used outside of CPU and memory, CPU endianness
766and how these arrays are stored as bytes become an issue. Transforming a
767unicode object into a sequence of bytes is called encoding and recreating the
768unicode object from the sequence of bytes is known as decoding. There are many
769different methods for how this transformation can be done (these methods are
770also called encodings). The simplest method is to map the codepoints 0-255 to
771the bytes ``0x0``-``0xff``. This means that a unicode object that contains
772codepoints above ``U+00FF`` can't be encoded with this method (which is called
773``'latin-1'`` or ``'iso-8859-1'``). :func:`unicode.encode` will raise a
774:exc:`UnicodeEncodeError` that looks like this: ``UnicodeEncodeError: 'latin-1'
775codec can't encode character u'\u1234' in position 3: ordinal not in
776range(256)``.
777
778There's another group of encodings (the so called charmap encodings) that choose
779a different subset of all unicode code points and how these codepoints are
780mapped to the bytes ``0x0``-``0xff``. To see how this is done simply open
781e.g. :file:`encodings/cp1252.py` (which is an encoding that is used primarily on
782Windows). There's a string constant with 256 characters that shows you which
783character is mapped to which byte value.
784
785All of these encodings can only encode 256 of the 65536 (or 1114111) codepoints
786defined in unicode. A simple and straightforward way that can store each Unicode
787code point, is to store each codepoint as two consecutive bytes. There are two
788possibilities: Store the bytes in big endian or in little endian order. These
789two encodings are called UTF-16-BE and UTF-16-LE respectively. Their
790disadvantage is that if e.g. you use UTF-16-BE on a little endian machine you
791will always have to swap bytes on encoding and decoding. UTF-16 avoids this
792problem: Bytes will always be in natural endianness. When these bytes are read
793by a CPU with a different endianness, then bytes have to be swapped though. To
794be able to detect the endianness of a UTF-16 byte sequence, there's the so
795called BOM (the "Byte Order Mark"). This is the Unicode character ``U+FEFF``.
796This character will be prepended to every UTF-16 byte sequence. The byte swapped
797version of this character (``0xFFFE``) is an illegal character that may not
798appear in a Unicode text. So when the first character in an UTF-16 byte sequence
799appears to be a ``U+FFFE`` the bytes have to be swapped on decoding.
800Unfortunately upto Unicode 4.0 the character ``U+FEFF`` had a second purpose as
801a ``ZERO WIDTH NO-BREAK SPACE``: A character that has no width and doesn't allow
802a word to be split. It can e.g. be used to give hints to a ligature algorithm.
803With Unicode 4.0 using ``U+FEFF`` as a ``ZERO WIDTH NO-BREAK SPACE`` has been
804deprecated (with ``U+2060`` (``WORD JOINER``) assuming this role). Nevertheless
805Unicode software still must be able to handle ``U+FEFF`` in both roles: As a BOM
806it's a device to determine the storage layout of the encoded bytes, and vanishes
807once the byte sequence has been decoded into a Unicode string; as a ``ZERO WIDTH
808NO-BREAK SPACE`` it's a normal character that will be decoded like any other.
809
810There's another encoding that is able to encoding the full range of Unicode
811characters: UTF-8. UTF-8 is an 8-bit encoding, which means there are no issues
812with byte order in UTF-8. Each byte in a UTF-8 byte sequence consists of two
813parts: Marker bits (the most significant bits) and payload bits. The marker bits
814are a sequence of zero to six 1 bits followed by a 0 bit. Unicode characters are
815encoded like this (with x being payload bits, which when concatenated give the
816Unicode character):
817
818+-----------------------------------+----------------------------------------------+
819| Range | Encoding |
820+===================================+==============================================+
821| ``U-00000000`` ... ``U-0000007F`` | 0xxxxxxx |
822+-----------------------------------+----------------------------------------------+
823| ``U-00000080`` ... ``U-000007FF`` | 110xxxxx 10xxxxxx |
824+-----------------------------------+----------------------------------------------+
825| ``U-00000800`` ... ``U-0000FFFF`` | 1110xxxx 10xxxxxx 10xxxxxx |
826+-----------------------------------+----------------------------------------------+
827| ``U-00010000`` ... ``U-001FFFFF`` | 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx |
828+-----------------------------------+----------------------------------------------+
829| ``U-00200000`` ... ``U-03FFFFFF`` | 111110xx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx |
830+-----------------------------------+----------------------------------------------+
831| ``U-04000000`` ... ``U-7FFFFFFF`` | 1111110x 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx |
832| | 10xxxxxx |
833+-----------------------------------+----------------------------------------------+
834
835The least significant bit of the Unicode character is the rightmost x bit.
836
837As UTF-8 is an 8-bit encoding no BOM is required and any ``U+FEFF`` character in
838the decoded Unicode string (even if it's the first character) is treated as a
839``ZERO WIDTH NO-BREAK SPACE``.
840
841Without external information it's impossible to reliably determine which
842encoding was used for encoding a Unicode string. Each charmap encoding can
843decode any random byte sequence. However that's not possible with UTF-8, as
844UTF-8 byte sequences have a structure that doesn't allow arbitrary byte
Walter Dörwald73f83d22007-09-01 18:34:05 +0000845sequences. To increase the reliability with which a UTF-8 encoding can be
Georg Brandl8ec7f652007-08-15 14:28:01 +0000846detected, Microsoft invented a variant of UTF-8 (that Python 2.5 calls
847``"utf-8-sig"``) for its Notepad program: Before any of the Unicode characters
848is written to the file, a UTF-8 encoded BOM (which looks like this as a byte
849sequence: ``0xef``, ``0xbb``, ``0xbf``) is written. As it's rather improbable
850that any charmap encoded file starts with these byte values (which would e.g.
851map to
852
853 | LATIN SMALL LETTER I WITH DIAERESIS
854 | RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK
855 | INVERTED QUESTION MARK
856
857in iso-8859-1), this increases the probability that a utf-8-sig encoding can be
858correctly guessed from the byte sequence. So here the BOM is not used to be able
859to determine the byte order used for generating the byte sequence, but as a
860signature that helps in guessing the encoding. On encoding the utf-8-sig codec
861will write ``0xef``, ``0xbb``, ``0xbf`` as the first three bytes to the file. On
862decoding utf-8-sig will skip those three bytes if they appear as the first three
863bytes in the file.
864
865
866.. _standard-encodings:
867
868Standard Encodings
869------------------
870
871Python comes with a number of codecs built-in, either implemented as C functions
872or with dictionaries as mapping tables. The following table lists the codecs by
873name, together with a few common aliases, and the languages for which the
874encoding is likely used. Neither the list of aliases nor the list of languages
875is meant to be exhaustive. Notice that spelling alternatives that only differ in
Georg Brandl87296622009-08-24 17:14:29 +0000876case or use a hyphen instead of an underscore are also valid aliases; therefore,
877e.g. ``'utf-8'`` is a valid alias for the ``'utf_8'`` codec.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000878
879Many of the character sets support the same languages. They vary in individual
880characters (e.g. whether the EURO SIGN is supported or not), and in the
881assignment of characters to code positions. For the European languages in
882particular, the following variants typically exist:
883
884* an ISO 8859 codeset
885
886* a Microsoft Windows code page, which is typically derived from a 8859 codeset,
887 but replaces control characters with additional graphic characters
888
889* an IBM EBCDIC code page
890
891* an IBM PC code page, which is ASCII compatible
892
893+-----------------+--------------------------------+--------------------------------+
894| Codec | Aliases | Languages |
895+=================+================================+================================+
896| ascii | 646, us-ascii | English |
897+-----------------+--------------------------------+--------------------------------+
898| big5 | big5-tw, csbig5 | Traditional Chinese |
899+-----------------+--------------------------------+--------------------------------+
900| big5hkscs | big5-hkscs, hkscs | Traditional Chinese |
901+-----------------+--------------------------------+--------------------------------+
902| cp037 | IBM037, IBM039 | English |
903+-----------------+--------------------------------+--------------------------------+
904| cp424 | EBCDIC-CP-HE, IBM424 | Hebrew |
905+-----------------+--------------------------------+--------------------------------+
906| cp437 | 437, IBM437 | English |
907+-----------------+--------------------------------+--------------------------------+
908| cp500 | EBCDIC-CP-BE, EBCDIC-CP-CH, | Western Europe |
909| | IBM500 | |
910+-----------------+--------------------------------+--------------------------------+
Amaury Forgeot d'Arc78c06bd2009-07-13 23:11:54 +0000911| cp720 | | Arabic |
912+-----------------+--------------------------------+--------------------------------+
Georg Brandl8ec7f652007-08-15 14:28:01 +0000913| cp737 | | Greek |
914+-----------------+--------------------------------+--------------------------------+
915| cp775 | IBM775 | Baltic languages |
916+-----------------+--------------------------------+--------------------------------+
917| cp850 | 850, IBM850 | Western Europe |
918+-----------------+--------------------------------+--------------------------------+
919| cp852 | 852, IBM852 | Central and Eastern Europe |
920+-----------------+--------------------------------+--------------------------------+
921| cp855 | 855, IBM855 | Bulgarian, Byelorussian, |
922| | | Macedonian, Russian, Serbian |
923+-----------------+--------------------------------+--------------------------------+
924| cp856 | | Hebrew |
925+-----------------+--------------------------------+--------------------------------+
926| cp857 | 857, IBM857 | Turkish |
927+-----------------+--------------------------------+--------------------------------+
928| cp860 | 860, IBM860 | Portuguese |
929+-----------------+--------------------------------+--------------------------------+
930| cp861 | 861, CP-IS, IBM861 | Icelandic |
931+-----------------+--------------------------------+--------------------------------+
932| cp862 | 862, IBM862 | Hebrew |
933+-----------------+--------------------------------+--------------------------------+
934| cp863 | 863, IBM863 | Canadian |
935+-----------------+--------------------------------+--------------------------------+
936| cp864 | IBM864 | Arabic |
937+-----------------+--------------------------------+--------------------------------+
938| cp865 | 865, IBM865 | Danish, Norwegian |
939+-----------------+--------------------------------+--------------------------------+
940| cp866 | 866, IBM866 | Russian |
941+-----------------+--------------------------------+--------------------------------+
942| cp869 | 869, CP-GR, IBM869 | Greek |
943+-----------------+--------------------------------+--------------------------------+
944| cp874 | | Thai |
945+-----------------+--------------------------------+--------------------------------+
946| cp875 | | Greek |
947+-----------------+--------------------------------+--------------------------------+
948| cp932 | 932, ms932, mskanji, ms-kanji | Japanese |
949+-----------------+--------------------------------+--------------------------------+
950| cp949 | 949, ms949, uhc | Korean |
951+-----------------+--------------------------------+--------------------------------+
952| cp950 | 950, ms950 | Traditional Chinese |
953+-----------------+--------------------------------+--------------------------------+
954| cp1006 | | Urdu |
955+-----------------+--------------------------------+--------------------------------+
956| cp1026 | ibm1026 | Turkish |
957+-----------------+--------------------------------+--------------------------------+
958| cp1140 | ibm1140 | Western Europe |
959+-----------------+--------------------------------+--------------------------------+
960| cp1250 | windows-1250 | Central and Eastern Europe |
961+-----------------+--------------------------------+--------------------------------+
962| cp1251 | windows-1251 | Bulgarian, Byelorussian, |
963| | | Macedonian, Russian, Serbian |
964+-----------------+--------------------------------+--------------------------------+
965| cp1252 | windows-1252 | Western Europe |
966+-----------------+--------------------------------+--------------------------------+
967| cp1253 | windows-1253 | Greek |
968+-----------------+--------------------------------+--------------------------------+
969| cp1254 | windows-1254 | Turkish |
970+-----------------+--------------------------------+--------------------------------+
971| cp1255 | windows-1255 | Hebrew |
972+-----------------+--------------------------------+--------------------------------+
Georg Brandlac870772009-09-22 10:55:08 +0000973| cp1256 | windows-1256 | Arabic |
Georg Brandl8ec7f652007-08-15 14:28:01 +0000974+-----------------+--------------------------------+--------------------------------+
975| cp1257 | windows-1257 | Baltic languages |
976+-----------------+--------------------------------+--------------------------------+
977| cp1258 | windows-1258 | Vietnamese |
978+-----------------+--------------------------------+--------------------------------+
979| euc_jp | eucjp, ujis, u-jis | Japanese |
980+-----------------+--------------------------------+--------------------------------+
981| euc_jis_2004 | jisx0213, eucjis2004 | Japanese |
982+-----------------+--------------------------------+--------------------------------+
983| euc_jisx0213 | eucjisx0213 | Japanese |
984+-----------------+--------------------------------+--------------------------------+
985| euc_kr | euckr, korean, ksc5601, | Korean |
986| | ks_c-5601, ks_c-5601-1987, | |
987| | ksx1001, ks_x-1001 | |
988+-----------------+--------------------------------+--------------------------------+
989| gb2312 | chinese, csiso58gb231280, euc- | Simplified Chinese |
990| | cn, euccn, eucgb2312-cn, | |
991| | gb2312-1980, gb2312-80, iso- | |
992| | ir-58 | |
993+-----------------+--------------------------------+--------------------------------+
994| gbk | 936, cp936, ms936 | Unified Chinese |
995+-----------------+--------------------------------+--------------------------------+
996| gb18030 | gb18030-2000 | Unified Chinese |
997+-----------------+--------------------------------+--------------------------------+
998| hz | hzgb, hz-gb, hz-gb-2312 | Simplified Chinese |
999+-----------------+--------------------------------+--------------------------------+
1000| iso2022_jp | csiso2022jp, iso2022jp, | Japanese |
1001| | iso-2022-jp | |
1002+-----------------+--------------------------------+--------------------------------+
1003| iso2022_jp_1 | iso2022jp-1, iso-2022-jp-1 | Japanese |
1004+-----------------+--------------------------------+--------------------------------+
1005| iso2022_jp_2 | iso2022jp-2, iso-2022-jp-2 | Japanese, Korean, Simplified |
1006| | | Chinese, Western Europe, Greek |
1007+-----------------+--------------------------------+--------------------------------+
1008| iso2022_jp_2004 | iso2022jp-2004, | Japanese |
1009| | iso-2022-jp-2004 | |
1010+-----------------+--------------------------------+--------------------------------+
1011| iso2022_jp_3 | iso2022jp-3, iso-2022-jp-3 | Japanese |
1012+-----------------+--------------------------------+--------------------------------+
1013| iso2022_jp_ext | iso2022jp-ext, iso-2022-jp-ext | Japanese |
1014+-----------------+--------------------------------+--------------------------------+
1015| iso2022_kr | csiso2022kr, iso2022kr, | Korean |
1016| | iso-2022-kr | |
1017+-----------------+--------------------------------+--------------------------------+
1018| latin_1 | iso-8859-1, iso8859-1, 8859, | West Europe |
1019| | cp819, latin, latin1, L1 | |
1020+-----------------+--------------------------------+--------------------------------+
1021| iso8859_2 | iso-8859-2, latin2, L2 | Central and Eastern Europe |
1022+-----------------+--------------------------------+--------------------------------+
1023| iso8859_3 | iso-8859-3, latin3, L3 | Esperanto, Maltese |
1024+-----------------+--------------------------------+--------------------------------+
Georg Brandl907a7202008-02-22 12:31:45 +00001025| iso8859_4 | iso-8859-4, latin4, L4 | Baltic languages |
Georg Brandl8ec7f652007-08-15 14:28:01 +00001026+-----------------+--------------------------------+--------------------------------+
1027| iso8859_5 | iso-8859-5, cyrillic | Bulgarian, Byelorussian, |
1028| | | Macedonian, Russian, Serbian |
1029+-----------------+--------------------------------+--------------------------------+
1030| iso8859_6 | iso-8859-6, arabic | Arabic |
1031+-----------------+--------------------------------+--------------------------------+
1032| iso8859_7 | iso-8859-7, greek, greek8 | Greek |
1033+-----------------+--------------------------------+--------------------------------+
1034| iso8859_8 | iso-8859-8, hebrew | Hebrew |
1035+-----------------+--------------------------------+--------------------------------+
1036| iso8859_9 | iso-8859-9, latin5, L5 | Turkish |
1037+-----------------+--------------------------------+--------------------------------+
1038| iso8859_10 | iso-8859-10, latin6, L6 | Nordic languages |
1039+-----------------+--------------------------------+--------------------------------+
1040| iso8859_13 | iso-8859-13 | Baltic languages |
1041+-----------------+--------------------------------+--------------------------------+
1042| iso8859_14 | iso-8859-14, latin8, L8 | Celtic languages |
1043+-----------------+--------------------------------+--------------------------------+
1044| iso8859_15 | iso-8859-15 | Western Europe |
1045+-----------------+--------------------------------+--------------------------------+
1046| johab | cp1361, ms1361 | Korean |
1047+-----------------+--------------------------------+--------------------------------+
1048| koi8_r | | Russian |
1049+-----------------+--------------------------------+--------------------------------+
1050| koi8_u | | Ukrainian |
1051+-----------------+--------------------------------+--------------------------------+
1052| mac_cyrillic | maccyrillic | Bulgarian, Byelorussian, |
1053| | | Macedonian, Russian, Serbian |
1054+-----------------+--------------------------------+--------------------------------+
1055| mac_greek | macgreek | Greek |
1056+-----------------+--------------------------------+--------------------------------+
1057| mac_iceland | maciceland | Icelandic |
1058+-----------------+--------------------------------+--------------------------------+
1059| mac_latin2 | maclatin2, maccentraleurope | Central and Eastern Europe |
1060+-----------------+--------------------------------+--------------------------------+
1061| mac_roman | macroman | Western Europe |
1062+-----------------+--------------------------------+--------------------------------+
1063| mac_turkish | macturkish | Turkish |
1064+-----------------+--------------------------------+--------------------------------+
1065| ptcp154 | csptcp154, pt154, cp154, | Kazakh |
1066| | cyrillic-asian | |
1067+-----------------+--------------------------------+--------------------------------+
1068| shift_jis | csshiftjis, shiftjis, sjis, | Japanese |
1069| | s_jis | |
1070+-----------------+--------------------------------+--------------------------------+
1071| shift_jis_2004 | shiftjis2004, sjis_2004, | Japanese |
1072| | sjis2004 | |
1073+-----------------+--------------------------------+--------------------------------+
1074| shift_jisx0213 | shiftjisx0213, sjisx0213, | Japanese |
1075| | s_jisx0213 | |
1076+-----------------+--------------------------------+--------------------------------+
Walter Dörwald6e390802007-08-17 16:41:28 +00001077| utf_32 | U32, utf32 | all languages |
1078+-----------------+--------------------------------+--------------------------------+
1079| utf_32_be | UTF-32BE | all languages |
1080+-----------------+--------------------------------+--------------------------------+
1081| utf_32_le | UTF-32LE | all languages |
1082+-----------------+--------------------------------+--------------------------------+
Georg Brandl8ec7f652007-08-15 14:28:01 +00001083| utf_16 | U16, utf16 | all languages |
1084+-----------------+--------------------------------+--------------------------------+
1085| utf_16_be | UTF-16BE | all languages (BMP only) |
1086+-----------------+--------------------------------+--------------------------------+
1087| utf_16_le | UTF-16LE | all languages (BMP only) |
1088+-----------------+--------------------------------+--------------------------------+
1089| utf_7 | U7, unicode-1-1-utf-7 | all languages |
1090+-----------------+--------------------------------+--------------------------------+
1091| utf_8 | U8, UTF, utf8 | all languages |
1092+-----------------+--------------------------------+--------------------------------+
1093| utf_8_sig | | all languages |
1094+-----------------+--------------------------------+--------------------------------+
1095
1096A number of codecs are specific to Python, so their codec names have no meaning
1097outside Python. Some of them don't convert from Unicode strings to byte strings,
1098but instead use the property of the Python codecs machinery that any bijective
1099function with one argument can be considered as an encoding.
1100
1101For the codecs listed below, the result in the "encoding" direction is always a
1102byte string. The result of the "decoding" direction is listed as operand type in
1103the table.
1104
1105+--------------------+---------------------------+----------------+---------------------------+
1106| Codec | Aliases | Operand type | Purpose |
1107+====================+===========================+================+===========================+
1108| base64_codec | base64, base-64 | byte string | Convert operand to MIME |
1109| | | | base64 |
1110+--------------------+---------------------------+----------------+---------------------------+
1111| bz2_codec | bz2 | byte string | Compress the operand |
1112| | | | using bz2 |
1113+--------------------+---------------------------+----------------+---------------------------+
1114| hex_codec | hex | byte string | Convert operand to |
1115| | | | hexadecimal |
1116| | | | representation, with two |
1117| | | | digits per byte |
1118+--------------------+---------------------------+----------------+---------------------------+
1119| idna | | Unicode string | Implements :rfc:`3490`, |
1120| | | | see also |
1121| | | | :mod:`encodings.idna` |
1122+--------------------+---------------------------+----------------+---------------------------+
1123| mbcs | dbcs | Unicode string | Windows only: Encode |
1124| | | | operand according to the |
1125| | | | ANSI codepage (CP_ACP) |
1126+--------------------+---------------------------+----------------+---------------------------+
1127| palmos | | Unicode string | Encoding of PalmOS 3.5 |
1128+--------------------+---------------------------+----------------+---------------------------+
1129| punycode | | Unicode string | Implements :rfc:`3492` |
1130+--------------------+---------------------------+----------------+---------------------------+
1131| quopri_codec | quopri, quoted-printable, | byte string | Convert operand to MIME |
1132| | quotedprintable | | quoted printable |
1133+--------------------+---------------------------+----------------+---------------------------+
1134| raw_unicode_escape | | Unicode string | Produce a string that is |
1135| | | | suitable as raw Unicode |
1136| | | | literal in Python source |
1137| | | | code |
1138+--------------------+---------------------------+----------------+---------------------------+
1139| rot_13 | rot13 | Unicode string | Returns the Caesar-cypher |
1140| | | | encryption of the operand |
1141+--------------------+---------------------------+----------------+---------------------------+
1142| string_escape | | byte string | Produce a string that is |
1143| | | | suitable as string |
1144| | | | literal in Python source |
1145| | | | code |
1146+--------------------+---------------------------+----------------+---------------------------+
1147| undefined | | any | Raise an exception for |
1148| | | | all conversions. Can be |
1149| | | | used as the system |
1150| | | | encoding if no automatic |
Georg Brandl584265b2007-12-02 14:58:50 +00001151| | | | :term:`coercion` between |
1152| | | | byte and Unicode strings |
1153| | | | is desired. |
Georg Brandl8ec7f652007-08-15 14:28:01 +00001154+--------------------+---------------------------+----------------+---------------------------+
1155| unicode_escape | | Unicode string | Produce a string that is |
1156| | | | suitable as Unicode |
1157| | | | literal in Python source |
1158| | | | code |
1159+--------------------+---------------------------+----------------+---------------------------+
1160| unicode_internal | | Unicode string | Return the internal |
1161| | | | representation of the |
1162| | | | operand |
1163+--------------------+---------------------------+----------------+---------------------------+
1164| uu_codec | uu | byte string | Convert the operand using |
1165| | | | uuencode |
1166+--------------------+---------------------------+----------------+---------------------------+
1167| zlib_codec | zip, zlib | byte string | Compress the operand |
1168| | | | using gzip |
1169+--------------------+---------------------------+----------------+---------------------------+
1170
1171.. versionadded:: 2.3
1172 The ``idna`` and ``punycode`` encodings.
1173
1174
1175:mod:`encodings.idna` --- Internationalized Domain Names in Applications
1176------------------------------------------------------------------------
1177
1178.. module:: encodings.idna
1179 :synopsis: Internationalized Domain Names implementation
1180.. moduleauthor:: Martin v. Löwis
1181
1182.. versionadded:: 2.3
1183
1184This module implements :rfc:`3490` (Internationalized Domain Names in
1185Applications) and :rfc:`3492` (Nameprep: A Stringprep Profile for
1186Internationalized Domain Names (IDN)). It builds upon the ``punycode`` encoding
1187and :mod:`stringprep`.
1188
1189These RFCs together define a protocol to support non-ASCII characters in domain
1190names. A domain name containing non-ASCII characters (such as
1191``www.Alliancefrançaise.nu``) is converted into an ASCII-compatible encoding
1192(ACE, such as ``www.xn--alliancefranaise-npb.nu``). The ACE form of the domain
1193name is then used in all places where arbitrary characters are not allowed by
1194the protocol, such as DNS queries, HTTP :mailheader:`Host` fields, and so
1195on. This conversion is carried out in the application; if possible invisible to
1196the user: The application should transparently convert Unicode domain labels to
1197IDNA on the wire, and convert back ACE labels to Unicode before presenting them
1198to the user.
1199
1200Python supports this conversion in several ways: The ``idna`` codec allows to
1201convert between Unicode and the ACE. Furthermore, the :mod:`socket` module
1202transparently converts Unicode host names to ACE, so that applications need not
1203be concerned about converting host names themselves when they pass them to the
1204socket module. On top of that, modules that have host names as function
1205parameters, such as :mod:`httplib` and :mod:`ftplib`, accept Unicode host names
1206(:mod:`httplib` then also transparently sends an IDNA hostname in the
1207:mailheader:`Host` field if it sends that field at all).
1208
1209When receiving host names from the wire (such as in reverse name lookup), no
1210automatic conversion to Unicode is performed: Applications wishing to present
1211such host names to the user should decode them to Unicode.
1212
1213The module :mod:`encodings.idna` also implements the nameprep procedure, which
1214performs certain normalizations on host names, to achieve case-insensitivity of
1215international domain names, and to unify similar characters. The nameprep
1216functions can be used directly if desired.
1217
1218
1219.. function:: nameprep(label)
1220
1221 Return the nameprepped version of *label*. The implementation currently assumes
1222 query strings, so ``AllowUnassigned`` is true.
1223
1224
1225.. function:: ToASCII(label)
1226
1227 Convert a label to ASCII, as specified in :rfc:`3490`. ``UseSTD3ASCIIRules`` is
1228 assumed to be false.
1229
1230
1231.. function:: ToUnicode(label)
1232
1233 Convert a label to Unicode, as specified in :rfc:`3490`.
1234
1235
1236:mod:`encodings.utf_8_sig` --- UTF-8 codec with BOM signature
1237-------------------------------------------------------------
1238
1239.. module:: encodings.utf_8_sig
1240 :synopsis: UTF-8 codec with BOM signature
1241.. moduleauthor:: Walter Dörwald
1242
1243.. versionadded:: 2.5
1244
1245This module implements a variant of the UTF-8 codec: On encoding a UTF-8 encoded
1246BOM will be prepended to the UTF-8 encoded bytes. For the stateful encoder this
1247is only done once (on the first write to the byte stream). For decoding an
1248optional UTF-8 encoded BOM at the start of the data will be skipped.
1249