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