blob: d283edeb4cf2dd9e13cbfaec3a4a9e196f49b91f [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
Georg Brandl42dac472013-10-06 13:17:04 +020069 the base classes :class:`StreamReader` and :class:`StreamWriter`, respectively.
Georg Brandl8ec7f652007-08-15 14:28:01 +000070 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
Georg Brandl44ea77b2013-03-28 13:28:44 +0100323.. tabularcolumns:: |l|L|
324
Georg Brandl8ec7f652007-08-15 14:28:01 +0000325+-------------------------+-----------------------------------------------+
326| Value | Meaning |
327+=========================+===============================================+
328| ``'strict'`` | Raise :exc:`UnicodeError` (or a subclass); |
329| | this is the default. |
330+-------------------------+-----------------------------------------------+
331| ``'ignore'`` | Ignore the character and continue with the |
332| | next. |
333+-------------------------+-----------------------------------------------+
334| ``'replace'`` | Replace with a suitable replacement |
335| | character; Python will use the official |
336| | U+FFFD REPLACEMENT CHARACTER for the built-in |
337| | Unicode codecs on decoding and '?' on |
338| | encoding. |
339+-------------------------+-----------------------------------------------+
340| ``'xmlcharrefreplace'`` | Replace with the appropriate XML character |
341| | reference (only for encoding). |
342+-------------------------+-----------------------------------------------+
343| ``'backslashreplace'`` | Replace with backslashed escape sequences |
344| | (only for encoding). |
345+-------------------------+-----------------------------------------------+
346
347The set of allowed values can be extended via :meth:`register_error`.
348
349
350.. _codec-objects:
351
352Codec Objects
353^^^^^^^^^^^^^
354
355The :class:`Codec` class defines these methods which also define the function
356interfaces of the stateless encoder and decoder:
357
358
359.. method:: Codec.encode(input[, errors])
360
361 Encodes the object *input* and returns a tuple (output object, length consumed).
362 While codecs are not restricted to use with Unicode, in a Unicode context,
363 encoding converts a Unicode object to a plain string using a particular
364 character set encoding (e.g., ``cp1252`` or ``iso-8859-1``).
365
366 *errors* defines the error handling to apply. It defaults to ``'strict'``
367 handling.
368
369 The method may not store state in the :class:`Codec` instance. Use
370 :class:`StreamCodec` for codecs which have to keep state in order to make
371 encoding/decoding efficient.
372
373 The encoder must be able to handle zero length input and return an empty object
374 of the output object type in this situation.
375
376
377.. method:: Codec.decode(input[, errors])
378
379 Decodes the object *input* and returns a tuple (output object, length consumed).
380 In a Unicode context, decoding converts a plain string encoded using a
381 particular character set encoding to a Unicode object.
382
383 *input* must be an object which provides the ``bf_getreadbuf`` buffer slot.
384 Python strings, buffer objects and memory mapped files are examples of objects
385 providing this slot.
386
387 *errors* defines the error handling to apply. It defaults to ``'strict'``
388 handling.
389
390 The method may not store state in the :class:`Codec` instance. Use
391 :class:`StreamCodec` for codecs which have to keep state in order to make
392 encoding/decoding efficient.
393
394 The decoder must be able to handle zero length input and return an empty object
395 of the output object type in this situation.
396
397The :class:`IncrementalEncoder` and :class:`IncrementalDecoder` classes provide
398the basic interface for incremental encoding and decoding. Encoding/decoding the
399input isn't done with one call to the stateless encoder/decoder function, but
400with multiple calls to the :meth:`encode`/:meth:`decode` method of the
401incremental encoder/decoder. The incremental encoder/decoder keeps track of the
402encoding/decoding process during method calls.
403
404The joined output of calls to the :meth:`encode`/:meth:`decode` method is the
405same as if all the single inputs were joined into one, and this input was
406encoded/decoded with the stateless encoder/decoder.
407
408
409.. _incremental-encoder-objects:
410
411IncrementalEncoder Objects
412^^^^^^^^^^^^^^^^^^^^^^^^^^
413
414.. versionadded:: 2.5
415
416The :class:`IncrementalEncoder` class is used for encoding an input in multiple
417steps. It defines the following methods which every incremental encoder must
418define in order to be compatible with the Python codec registry.
419
420
421.. class:: IncrementalEncoder([errors])
422
423 Constructor for an :class:`IncrementalEncoder` instance.
424
425 All incremental encoders must provide this constructor interface. They are free
426 to add additional keyword arguments, but only the ones defined here are used by
427 the Python codec registry.
428
429 The :class:`IncrementalEncoder` may implement different error handling schemes
430 by providing the *errors* keyword argument. These parameters are predefined:
431
432 * ``'strict'`` Raise :exc:`ValueError` (or a subclass); this is the default.
433
434 * ``'ignore'`` Ignore the character and continue with the next.
435
436 * ``'replace'`` Replace with a suitable replacement character
437
438 * ``'xmlcharrefreplace'`` Replace with the appropriate XML character reference
439
440 * ``'backslashreplace'`` Replace with backslashed escape sequences.
441
442 The *errors* argument will be assigned to an attribute of the same name.
443 Assigning to this attribute makes it possible to switch between different error
444 handling strategies during the lifetime of the :class:`IncrementalEncoder`
445 object.
446
447 The set of allowed values for the *errors* argument can be extended with
448 :func:`register_error`.
449
450
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000451 .. method:: encode(object[, final])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000452
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000453 Encodes *object* (taking the current state of the encoder into account)
454 and returns the resulting encoded object. If this is the last call to
455 :meth:`encode` *final* must be true (the default is false).
Georg Brandl8ec7f652007-08-15 14:28:01 +0000456
457
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000458 .. method:: reset()
Georg Brandl8ec7f652007-08-15 14:28:01 +0000459
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000460 Reset the encoder to the initial state.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000461
462
463.. _incremental-decoder-objects:
464
465IncrementalDecoder Objects
466^^^^^^^^^^^^^^^^^^^^^^^^^^
467
468The :class:`IncrementalDecoder` class is used for decoding an input in multiple
469steps. It defines the following methods which every incremental decoder must
470define in order to be compatible with the Python codec registry.
471
472
473.. class:: IncrementalDecoder([errors])
474
475 Constructor for an :class:`IncrementalDecoder` instance.
476
477 All incremental decoders must provide this constructor interface. They are free
478 to add additional keyword arguments, but only the ones defined here are used by
479 the Python codec registry.
480
481 The :class:`IncrementalDecoder` may implement different error handling schemes
482 by providing the *errors* keyword argument. These parameters are predefined:
483
484 * ``'strict'`` Raise :exc:`ValueError` (or a subclass); this is the default.
485
486 * ``'ignore'`` Ignore the character and continue with the next.
487
488 * ``'replace'`` Replace with a suitable replacement character.
489
490 The *errors* argument will be assigned to an attribute of the same name.
491 Assigning to this attribute makes it possible to switch between different error
Georg Brandl2ba93212008-09-01 14:15:55 +0000492 handling strategies during the lifetime of the :class:`IncrementalDecoder`
Georg Brandl8ec7f652007-08-15 14:28:01 +0000493 object.
494
495 The set of allowed values for the *errors* argument can be extended with
496 :func:`register_error`.
497
498
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000499 .. method:: decode(object[, final])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000500
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000501 Decodes *object* (taking the current state of the decoder into account)
502 and returns the resulting decoded object. If this is the last call to
503 :meth:`decode` *final* must be true (the default is false). If *final* is
504 true the decoder must decode the input completely and must flush all
505 buffers. If this isn't possible (e.g. because of incomplete byte sequences
506 at the end of the input) it must initiate error handling just like in the
507 stateless case (which might raise an exception).
Georg Brandl8ec7f652007-08-15 14:28:01 +0000508
509
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000510 .. method:: reset()
Georg Brandl8ec7f652007-08-15 14:28:01 +0000511
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000512 Reset the decoder to the initial state.
513
Georg Brandl8ec7f652007-08-15 14:28:01 +0000514
515The :class:`StreamWriter` and :class:`StreamReader` classes provide generic
516working interfaces which can be used to implement new encoding submodules very
517easily. See :mod:`encodings.utf_8` for an example of how this is done.
518
519
520.. _stream-writer-objects:
521
522StreamWriter Objects
523^^^^^^^^^^^^^^^^^^^^
524
525The :class:`StreamWriter` class is a subclass of :class:`Codec` and defines the
526following methods which every stream writer must define in order to be
527compatible with the Python codec registry.
528
529
530.. class:: StreamWriter(stream[, errors])
531
532 Constructor for a :class:`StreamWriter` instance.
533
534 All stream writers must provide this constructor interface. They are free to add
535 additional keyword arguments, but only the ones defined here are used by the
536 Python codec registry.
537
538 *stream* must be a file-like object open for writing binary data.
539
540 The :class:`StreamWriter` may implement different error handling schemes by
541 providing the *errors* keyword argument. These parameters are predefined:
542
543 * ``'strict'`` Raise :exc:`ValueError` (or a subclass); this is the default.
544
545 * ``'ignore'`` Ignore the character and continue with the next.
546
547 * ``'replace'`` Replace with a suitable replacement character
548
549 * ``'xmlcharrefreplace'`` Replace with the appropriate XML character reference
550
551 * ``'backslashreplace'`` Replace with backslashed escape sequences.
552
553 The *errors* argument will be assigned to an attribute of the same name.
554 Assigning to this attribute makes it possible to switch between different error
555 handling strategies during the lifetime of the :class:`StreamWriter` object.
556
557 The set of allowed values for the *errors* argument can be extended with
558 :func:`register_error`.
559
560
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000561 .. method:: write(object)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000562
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000563 Writes the object's contents encoded to the stream.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000564
565
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000566 .. method:: writelines(list)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000567
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000568 Writes the concatenated list of strings to the stream (possibly by reusing
569 the :meth:`write` method).
Georg Brandl8ec7f652007-08-15 14:28:01 +0000570
571
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000572 .. method:: reset()
Georg Brandl8ec7f652007-08-15 14:28:01 +0000573
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000574 Flushes and resets the codec buffers used for keeping state.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000575
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000576 Calling this method should ensure that the data on the output is put into
577 a clean state that allows appending of new fresh data without having to
578 rescan the whole stream to recover state.
579
Georg Brandl8ec7f652007-08-15 14:28:01 +0000580
581In addition to the above methods, the :class:`StreamWriter` must also inherit
582all other methods and attributes from the underlying stream.
583
584
585.. _stream-reader-objects:
586
587StreamReader Objects
588^^^^^^^^^^^^^^^^^^^^
589
590The :class:`StreamReader` class is a subclass of :class:`Codec` and defines the
591following methods which every stream reader must define in order to be
592compatible with the Python codec registry.
593
594
595.. class:: StreamReader(stream[, errors])
596
597 Constructor for a :class:`StreamReader` instance.
598
599 All stream readers must provide this constructor interface. They are free to add
600 additional keyword arguments, but only the ones defined here are used by the
601 Python codec registry.
602
603 *stream* must be a file-like object open for reading (binary) data.
604
605 The :class:`StreamReader` may implement different error handling schemes by
606 providing the *errors* keyword argument. These parameters are defined:
607
608 * ``'strict'`` Raise :exc:`ValueError` (or a subclass); this is the default.
609
610 * ``'ignore'`` Ignore the character and continue with the next.
611
612 * ``'replace'`` Replace with a suitable replacement character.
613
614 The *errors* argument will be assigned to an attribute of the same name.
615 Assigning to this attribute makes it possible to switch between different error
616 handling strategies during the lifetime of the :class:`StreamReader` object.
617
618 The set of allowed values for the *errors* argument can be extended with
619 :func:`register_error`.
620
621
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000622 .. method:: read([size[, chars, [firstline]]])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000623
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000624 Decodes data from the stream and returns the resulting object.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000625
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000626 *chars* indicates the number of characters to read from the
627 stream. :func:`read` will never return more than *chars* characters, but
628 it might return less, if there are not enough characters available.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000629
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000630 *size* indicates the approximate maximum number of bytes to read from the
631 stream for decoding purposes. The decoder can modify this setting as
632 appropriate. The default value -1 indicates to read and decode as much as
633 possible. *size* is intended to prevent having to decode huge files in
634 one step.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000635
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000636 *firstline* indicates that it would be sufficient to only return the first
637 line, if there are decoding errors on later lines.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000638
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000639 The method should use a greedy read strategy meaning that it should read
640 as much data as is allowed within the definition of the encoding and the
641 given size, e.g. if optional encoding endings or state markers are
642 available on the stream, these should be read too.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000643
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000644 .. versionchanged:: 2.4
645 *chars* argument added.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000646
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000647 .. versionchanged:: 2.4.2
648 *firstline* argument added.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000649
650
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000651 .. method:: readline([size[, keepends]])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000652
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000653 Read one line from the input stream and return the decoded data.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000654
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000655 *size*, if given, is passed as size argument to the stream's
Serhiy Storchaka6cda0ad2013-07-11 18:25:19 +0300656 :meth:`read` method.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000657
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000658 If *keepends* is false line-endings will be stripped from the lines
659 returned.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000660
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000661 .. versionchanged:: 2.4
662 *keepends* argument added.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000663
664
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000665 .. method:: readlines([sizehint[, keepends]])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000666
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000667 Read all lines available on the input stream and return them as a list of
668 lines.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000669
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000670 Line-endings are implemented using the codec's decoder method and are
671 included in the list entries if *keepends* is true.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000672
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000673 *sizehint*, if given, is passed as the *size* argument to the stream's
674 :meth:`read` method.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000675
676
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000677 .. method:: reset()
Georg Brandl8ec7f652007-08-15 14:28:01 +0000678
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000679 Resets the codec buffers used for keeping state.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000680
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000681 Note that no stream repositioning should take place. This method is
682 primarily intended to be able to recover from decoding errors.
683
Georg Brandl8ec7f652007-08-15 14:28:01 +0000684
685In addition to the above methods, the :class:`StreamReader` must also inherit
686all other methods and attributes from the underlying stream.
687
688The next two base classes are included for convenience. They are not needed by
689the codec registry, but may provide useful in practice.
690
691
692.. _stream-reader-writer:
693
694StreamReaderWriter Objects
695^^^^^^^^^^^^^^^^^^^^^^^^^^
696
697The :class:`StreamReaderWriter` allows wrapping streams which work in both read
698and write modes.
699
700The design is such that one can use the factory functions returned by the
701:func:`lookup` function to construct the instance.
702
703
704.. class:: StreamReaderWriter(stream, Reader, Writer, errors)
705
706 Creates a :class:`StreamReaderWriter` instance. *stream* must be a file-like
707 object. *Reader* and *Writer* must be factory functions or classes providing the
708 :class:`StreamReader` and :class:`StreamWriter` interface resp. Error handling
709 is done in the same way as defined for the stream readers and writers.
710
711:class:`StreamReaderWriter` instances define the combined interfaces of
712:class:`StreamReader` and :class:`StreamWriter` classes. They inherit all other
713methods and attributes from the underlying stream.
714
715
716.. _stream-recoder-objects:
717
718StreamRecoder Objects
719^^^^^^^^^^^^^^^^^^^^^
720
721The :class:`StreamRecoder` provide a frontend - backend view of encoding data
722which is sometimes useful when dealing with different encoding environments.
723
724The design is such that one can use the factory functions returned by the
725:func:`lookup` function to construct the instance.
726
727
728.. class:: StreamRecoder(stream, encode, decode, Reader, Writer, errors)
729
730 Creates a :class:`StreamRecoder` instance which implements a two-way conversion:
731 *encode* and *decode* work on the frontend (the input to :meth:`read` and output
732 of :meth:`write`) while *Reader* and *Writer* work on the backend (reading and
733 writing to the stream).
734
735 You can use these objects to do transparent direct recodings from e.g. Latin-1
736 to UTF-8 and back.
737
738 *stream* must be a file-like object.
739
740 *encode*, *decode* must adhere to the :class:`Codec` interface. *Reader*,
741 *Writer* must be factory functions or classes providing objects of the
742 :class:`StreamReader` and :class:`StreamWriter` interface respectively.
743
744 *encode* and *decode* are needed for the frontend translation, *Reader* and
745 *Writer* for the backend translation. The intermediate format used is
746 determined by the two sets of codecs, e.g. the Unicode codecs will use Unicode
747 as the intermediate encoding.
748
749 Error handling is done in the same way as defined for the stream readers and
750 writers.
751
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000752
Georg Brandl8ec7f652007-08-15 14:28:01 +0000753:class:`StreamRecoder` instances define the combined interfaces of
754:class:`StreamReader` and :class:`StreamWriter` classes. They inherit all other
755methods and attributes from the underlying stream.
756
757
758.. _encodings-overview:
759
760Encodings and Unicode
761---------------------
762
763Unicode strings are stored internally as sequences of codepoints (to be precise
Sandro Tosi98ed08f2012-01-14 16:42:02 +0100764as :c:type:`Py_UNICODE` arrays). Depending on the way Python is compiled (either
Éric Araujoa8132ec2010-12-16 03:53:53 +0000765via ``--enable-unicode=ucs2`` or ``--enable-unicode=ucs4``, with the
Sandro Tosi98ed08f2012-01-14 16:42:02 +0100766former being the default) :c:type:`Py_UNICODE` is either a 16-bit or 32-bit data
Georg Brandl8ec7f652007-08-15 14:28:01 +0000767type. Once a Unicode object is used outside of CPU and memory, CPU endianness
768and how these arrays are stored as bytes become an issue. Transforming a
769unicode object into a sequence of bytes is called encoding and recreating the
770unicode object from the sequence of bytes is known as decoding. There are many
771different methods for how this transformation can be done (these methods are
772also called encodings). The simplest method is to map the codepoints 0-255 to
773the bytes ``0x0``-``0xff``. This means that a unicode object that contains
774codepoints above ``U+00FF`` can't be encoded with this method (which is called
775``'latin-1'`` or ``'iso-8859-1'``). :func:`unicode.encode` will raise a
776:exc:`UnicodeEncodeError` that looks like this: ``UnicodeEncodeError: 'latin-1'
777codec can't encode character u'\u1234' in position 3: ordinal not in
778range(256)``.
779
780There's another group of encodings (the so called charmap encodings) that choose
781a different subset of all unicode code points and how these codepoints are
782mapped to the bytes ``0x0``-``0xff``. To see how this is done simply open
783e.g. :file:`encodings/cp1252.py` (which is an encoding that is used primarily on
784Windows). There's a string constant with 256 characters that shows you which
785character is mapped to which byte value.
786
Ezio Melotti59b13f42011-10-25 10:46:22 +0300787All of these encodings can only encode 256 of the 1114112 codepoints
Georg Brandl8ec7f652007-08-15 14:28:01 +0000788defined in unicode. A simple and straightforward way that can store each Unicode
Ezio Melotti59b13f42011-10-25 10:46:22 +0300789code point, is to store each codepoint as four consecutive bytes. There are two
790possibilities: store the bytes in big endian or in little endian order. These
791two encodings are called ``UTF-32-BE`` and ``UTF-32-LE`` respectively. Their
792disadvantage is that if e.g. you use ``UTF-32-BE`` on a little endian machine you
793will always have to swap bytes on encoding and decoding. ``UTF-32`` avoids this
794problem: bytes will always be in natural endianness. When these bytes are read
Georg Brandl8ec7f652007-08-15 14:28:01 +0000795by a CPU with a different endianness, then bytes have to be swapped though. To
Ezio Melotti59b13f42011-10-25 10:46:22 +0300796be able to detect the endianness of a ``UTF-16`` or ``UTF-32`` byte sequence,
797there's the so called BOM ("Byte Order Mark"). This is the Unicode character
798``U+FEFF``. This character can be prepended to every ``UTF-16`` or ``UTF-32``
799byte sequence. The byte swapped version of this character (``0xFFFE``) is an
800illegal character that may not appear in a Unicode text. So when the
801first character in an ``UTF-16`` or ``UTF-32`` byte sequence
Georg Brandl8ec7f652007-08-15 14:28:01 +0000802appears to be a ``U+FFFE`` the bytes have to be swapped on decoding.
Ezio Melotti59b13f42011-10-25 10:46:22 +0300803Unfortunately the character ``U+FEFF`` had a second purpose as
804a ``ZERO WIDTH NO-BREAK SPACE``: a character that has no width and doesn't allow
Georg Brandl8ec7f652007-08-15 14:28:01 +0000805a word to be split. It can e.g. be used to give hints to a ligature algorithm.
806With Unicode 4.0 using ``U+FEFF`` as a ``ZERO WIDTH NO-BREAK SPACE`` has been
807deprecated (with ``U+2060`` (``WORD JOINER``) assuming this role). Nevertheless
Ezio Melotti59b13f42011-10-25 10:46:22 +0300808Unicode software still must be able to handle ``U+FEFF`` in both roles: as a BOM
Georg Brandl8ec7f652007-08-15 14:28:01 +0000809it's a device to determine the storage layout of the encoded bytes, and vanishes
810once the byte sequence has been decoded into a Unicode string; as a ``ZERO WIDTH
811NO-BREAK SPACE`` it's a normal character that will be decoded like any other.
812
813There's another encoding that is able to encoding the full range of Unicode
814characters: UTF-8. UTF-8 is an 8-bit encoding, which means there are no issues
815with byte order in UTF-8. Each byte in a UTF-8 byte sequence consists of two
Ezio Melotti59b13f42011-10-25 10:46:22 +0300816parts: marker bits (the most significant bits) and payload bits. The marker bits
Ezio Melotti4f14a1f2011-09-01 08:19:01 +0300817are a sequence of zero to four ``1`` bits followed by a ``0`` bit. Unicode characters are
Georg Brandl8ec7f652007-08-15 14:28:01 +0000818encoded like this (with x being payload bits, which when concatenated give the
819Unicode character):
820
821+-----------------------------------+----------------------------------------------+
822| Range | Encoding |
823+===================================+==============================================+
824| ``U-00000000`` ... ``U-0000007F`` | 0xxxxxxx |
825+-----------------------------------+----------------------------------------------+
826| ``U-00000080`` ... ``U-000007FF`` | 110xxxxx 10xxxxxx |
827+-----------------------------------+----------------------------------------------+
828| ``U-00000800`` ... ``U-0000FFFF`` | 1110xxxx 10xxxxxx 10xxxxxx |
829+-----------------------------------+----------------------------------------------+
Ezio Melotti4f14a1f2011-09-01 08:19:01 +0300830| ``U-00010000`` ... ``U-0010FFFF`` | 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx |
Georg Brandl8ec7f652007-08-15 14:28:01 +0000831+-----------------------------------+----------------------------------------------+
832
833The least significant bit of the Unicode character is the rightmost x bit.
834
835As UTF-8 is an 8-bit encoding no BOM is required and any ``U+FEFF`` character in
836the decoded Unicode string (even if it's the first character) is treated as a
837``ZERO WIDTH NO-BREAK SPACE``.
838
839Without external information it's impossible to reliably determine which
840encoding was used for encoding a Unicode string. Each charmap encoding can
841decode any random byte sequence. However that's not possible with UTF-8, as
842UTF-8 byte sequences have a structure that doesn't allow arbitrary byte
Walter Dörwald73f83d22007-09-01 18:34:05 +0000843sequences. To increase the reliability with which a UTF-8 encoding can be
Georg Brandl8ec7f652007-08-15 14:28:01 +0000844detected, Microsoft invented a variant of UTF-8 (that Python 2.5 calls
845``"utf-8-sig"``) for its Notepad program: Before any of the Unicode characters
846is written to the file, a UTF-8 encoded BOM (which looks like this as a byte
847sequence: ``0xef``, ``0xbb``, ``0xbf``) is written. As it's rather improbable
848that any charmap encoded file starts with these byte values (which would e.g.
849map to
850
851 | LATIN SMALL LETTER I WITH DIAERESIS
852 | RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK
853 | INVERTED QUESTION MARK
854
Ezio Melotti59b13f42011-10-25 10:46:22 +0300855in iso-8859-1), this increases the probability that a ``utf-8-sig`` encoding can be
Georg Brandl8ec7f652007-08-15 14:28:01 +0000856correctly guessed from the byte sequence. So here the BOM is not used to be able
857to determine the byte order used for generating the byte sequence, but as a
858signature that helps in guessing the encoding. On encoding the utf-8-sig codec
859will write ``0xef``, ``0xbb``, ``0xbf`` as the first three bytes to the file. On
Ezio Melotti59b13f42011-10-25 10:46:22 +0300860decoding ``utf-8-sig`` will skip those three bytes if they appear as the first
861three bytes in the file. In UTF-8, the use of the BOM is discouraged and
862should generally be avoided.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000863
864
865.. _standard-encodings:
866
867Standard Encodings
868------------------
869
870Python comes with a number of codecs built-in, either implemented as C functions
871or with dictionaries as mapping tables. The following table lists the codecs by
872name, together with a few common aliases, and the languages for which the
873encoding is likely used. Neither the list of aliases nor the list of languages
874is meant to be exhaustive. Notice that spelling alternatives that only differ in
Georg Brandl87296622009-08-24 17:14:29 +0000875case or use a hyphen instead of an underscore are also valid aliases; therefore,
876e.g. ``'utf-8'`` is a valid alias for the ``'utf_8'`` codec.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000877
878Many of the character sets support the same languages. They vary in individual
879characters (e.g. whether the EURO SIGN is supported or not), and in the
880assignment of characters to code positions. For the European languages in
881particular, the following variants typically exist:
882
883* an ISO 8859 codeset
884
885* a Microsoft Windows code page, which is typically derived from a 8859 codeset,
886 but replaces control characters with additional graphic characters
887
888* an IBM EBCDIC code page
889
890* an IBM PC code page, which is ASCII compatible
891
Georg Brandl44ea77b2013-03-28 13:28:44 +0100892.. tabularcolumns:: |l|p{0.3\linewidth}|p{0.3\linewidth}|
893
Georg Brandl8ec7f652007-08-15 14:28:01 +0000894+-----------------+--------------------------------+--------------------------------+
895| Codec | Aliases | Languages |
896+=================+================================+================================+
897| ascii | 646, us-ascii | English |
898+-----------------+--------------------------------+--------------------------------+
899| big5 | big5-tw, csbig5 | Traditional Chinese |
900+-----------------+--------------------------------+--------------------------------+
901| big5hkscs | big5-hkscs, hkscs | Traditional Chinese |
902+-----------------+--------------------------------+--------------------------------+
903| cp037 | IBM037, IBM039 | English |
904+-----------------+--------------------------------+--------------------------------+
905| cp424 | EBCDIC-CP-HE, IBM424 | Hebrew |
906+-----------------+--------------------------------+--------------------------------+
907| cp437 | 437, IBM437 | English |
908+-----------------+--------------------------------+--------------------------------+
909| cp500 | EBCDIC-CP-BE, EBCDIC-CP-CH, | Western Europe |
910| | IBM500 | |
911+-----------------+--------------------------------+--------------------------------+
Amaury Forgeot d'Arc78c06bd2009-07-13 23:11:54 +0000912| cp720 | | Arabic |
913+-----------------+--------------------------------+--------------------------------+
Georg Brandl8ec7f652007-08-15 14:28:01 +0000914| cp737 | | Greek |
915+-----------------+--------------------------------+--------------------------------+
916| cp775 | IBM775 | Baltic languages |
917+-----------------+--------------------------------+--------------------------------+
918| cp850 | 850, IBM850 | Western Europe |
919+-----------------+--------------------------------+--------------------------------+
920| cp852 | 852, IBM852 | Central and Eastern Europe |
921+-----------------+--------------------------------+--------------------------------+
922| cp855 | 855, IBM855 | Bulgarian, Byelorussian, |
923| | | Macedonian, Russian, Serbian |
924+-----------------+--------------------------------+--------------------------------+
925| cp856 | | Hebrew |
926+-----------------+--------------------------------+--------------------------------+
927| cp857 | 857, IBM857 | Turkish |
928+-----------------+--------------------------------+--------------------------------+
Georg Brandlf0757a22010-05-24 21:29:07 +0000929| cp858 | 858, IBM858 | Western Europe |
930+-----------------+--------------------------------+--------------------------------+
Georg Brandl8ec7f652007-08-15 14:28:01 +0000931| cp860 | 860, IBM860 | Portuguese |
932+-----------------+--------------------------------+--------------------------------+
933| cp861 | 861, CP-IS, IBM861 | Icelandic |
934+-----------------+--------------------------------+--------------------------------+
935| cp862 | 862, IBM862 | Hebrew |
936+-----------------+--------------------------------+--------------------------------+
937| cp863 | 863, IBM863 | Canadian |
938+-----------------+--------------------------------+--------------------------------+
939| cp864 | IBM864 | Arabic |
940+-----------------+--------------------------------+--------------------------------+
941| cp865 | 865, IBM865 | Danish, Norwegian |
942+-----------------+--------------------------------+--------------------------------+
943| cp866 | 866, IBM866 | Russian |
944+-----------------+--------------------------------+--------------------------------+
945| cp869 | 869, CP-GR, IBM869 | Greek |
946+-----------------+--------------------------------+--------------------------------+
947| cp874 | | Thai |
948+-----------------+--------------------------------+--------------------------------+
949| cp875 | | Greek |
950+-----------------+--------------------------------+--------------------------------+
951| cp932 | 932, ms932, mskanji, ms-kanji | Japanese |
952+-----------------+--------------------------------+--------------------------------+
953| cp949 | 949, ms949, uhc | Korean |
954+-----------------+--------------------------------+--------------------------------+
955| cp950 | 950, ms950 | Traditional Chinese |
956+-----------------+--------------------------------+--------------------------------+
957| cp1006 | | Urdu |
958+-----------------+--------------------------------+--------------------------------+
959| cp1026 | ibm1026 | Turkish |
960+-----------------+--------------------------------+--------------------------------+
961| cp1140 | ibm1140 | Western Europe |
962+-----------------+--------------------------------+--------------------------------+
963| cp1250 | windows-1250 | Central and Eastern Europe |
964+-----------------+--------------------------------+--------------------------------+
965| cp1251 | windows-1251 | Bulgarian, Byelorussian, |
966| | | Macedonian, Russian, Serbian |
967+-----------------+--------------------------------+--------------------------------+
968| cp1252 | windows-1252 | Western Europe |
969+-----------------+--------------------------------+--------------------------------+
970| cp1253 | windows-1253 | Greek |
971+-----------------+--------------------------------+--------------------------------+
972| cp1254 | windows-1254 | Turkish |
973+-----------------+--------------------------------+--------------------------------+
974| cp1255 | windows-1255 | Hebrew |
975+-----------------+--------------------------------+--------------------------------+
Georg Brandlac870772009-09-22 10:55:08 +0000976| cp1256 | windows-1256 | Arabic |
Georg Brandl8ec7f652007-08-15 14:28:01 +0000977+-----------------+--------------------------------+--------------------------------+
978| cp1257 | windows-1257 | Baltic languages |
979+-----------------+--------------------------------+--------------------------------+
980| cp1258 | windows-1258 | Vietnamese |
981+-----------------+--------------------------------+--------------------------------+
982| euc_jp | eucjp, ujis, u-jis | Japanese |
983+-----------------+--------------------------------+--------------------------------+
984| euc_jis_2004 | jisx0213, eucjis2004 | Japanese |
985+-----------------+--------------------------------+--------------------------------+
986| euc_jisx0213 | eucjisx0213 | Japanese |
987+-----------------+--------------------------------+--------------------------------+
988| euc_kr | euckr, korean, ksc5601, | Korean |
989| | ks_c-5601, ks_c-5601-1987, | |
990| | ksx1001, ks_x-1001 | |
991+-----------------+--------------------------------+--------------------------------+
992| gb2312 | chinese, csiso58gb231280, euc- | Simplified Chinese |
993| | cn, euccn, eucgb2312-cn, | |
994| | gb2312-1980, gb2312-80, iso- | |
995| | ir-58 | |
996+-----------------+--------------------------------+--------------------------------+
997| gbk | 936, cp936, ms936 | Unified Chinese |
998+-----------------+--------------------------------+--------------------------------+
999| gb18030 | gb18030-2000 | Unified Chinese |
1000+-----------------+--------------------------------+--------------------------------+
1001| hz | hzgb, hz-gb, hz-gb-2312 | Simplified Chinese |
1002+-----------------+--------------------------------+--------------------------------+
1003| iso2022_jp | csiso2022jp, iso2022jp, | Japanese |
1004| | iso-2022-jp | |
1005+-----------------+--------------------------------+--------------------------------+
1006| iso2022_jp_1 | iso2022jp-1, iso-2022-jp-1 | Japanese |
1007+-----------------+--------------------------------+--------------------------------+
1008| iso2022_jp_2 | iso2022jp-2, iso-2022-jp-2 | Japanese, Korean, Simplified |
1009| | | Chinese, Western Europe, Greek |
1010+-----------------+--------------------------------+--------------------------------+
1011| iso2022_jp_2004 | iso2022jp-2004, | Japanese |
1012| | iso-2022-jp-2004 | |
1013+-----------------+--------------------------------+--------------------------------+
1014| iso2022_jp_3 | iso2022jp-3, iso-2022-jp-3 | Japanese |
1015+-----------------+--------------------------------+--------------------------------+
1016| iso2022_jp_ext | iso2022jp-ext, iso-2022-jp-ext | Japanese |
1017+-----------------+--------------------------------+--------------------------------+
1018| iso2022_kr | csiso2022kr, iso2022kr, | Korean |
1019| | iso-2022-kr | |
1020+-----------------+--------------------------------+--------------------------------+
1021| latin_1 | iso-8859-1, iso8859-1, 8859, | West Europe |
1022| | cp819, latin, latin1, L1 | |
1023+-----------------+--------------------------------+--------------------------------+
1024| iso8859_2 | iso-8859-2, latin2, L2 | Central and Eastern Europe |
1025+-----------------+--------------------------------+--------------------------------+
1026| iso8859_3 | iso-8859-3, latin3, L3 | Esperanto, Maltese |
1027+-----------------+--------------------------------+--------------------------------+
Georg Brandl907a7202008-02-22 12:31:45 +00001028| iso8859_4 | iso-8859-4, latin4, L4 | Baltic languages |
Georg Brandl8ec7f652007-08-15 14:28:01 +00001029+-----------------+--------------------------------+--------------------------------+
1030| iso8859_5 | iso-8859-5, cyrillic | Bulgarian, Byelorussian, |
1031| | | Macedonian, Russian, Serbian |
1032+-----------------+--------------------------------+--------------------------------+
1033| iso8859_6 | iso-8859-6, arabic | Arabic |
1034+-----------------+--------------------------------+--------------------------------+
1035| iso8859_7 | iso-8859-7, greek, greek8 | Greek |
1036+-----------------+--------------------------------+--------------------------------+
1037| iso8859_8 | iso-8859-8, hebrew | Hebrew |
1038+-----------------+--------------------------------+--------------------------------+
1039| iso8859_9 | iso-8859-9, latin5, L5 | Turkish |
1040+-----------------+--------------------------------+--------------------------------+
1041| iso8859_10 | iso-8859-10, latin6, L6 | Nordic languages |
1042+-----------------+--------------------------------+--------------------------------+
Georg Brandl65db5872010-03-14 09:55:08 +00001043| iso8859_13 | iso-8859-13, latin7, L7 | Baltic languages |
Georg Brandl8ec7f652007-08-15 14:28:01 +00001044+-----------------+--------------------------------+--------------------------------+
1045| iso8859_14 | iso-8859-14, latin8, L8 | Celtic languages |
1046+-----------------+--------------------------------+--------------------------------+
Georg Brandl65db5872010-03-14 09:55:08 +00001047| iso8859_15 | iso-8859-15, latin9, L9 | Western Europe |
1048+-----------------+--------------------------------+--------------------------------+
1049| iso8859_16 | iso-8859-16, latin10, L10 | South-Eastern Europe |
Georg Brandl8ec7f652007-08-15 14:28:01 +00001050+-----------------+--------------------------------+--------------------------------+
1051| johab | cp1361, ms1361 | Korean |
1052+-----------------+--------------------------------+--------------------------------+
1053| koi8_r | | Russian |
1054+-----------------+--------------------------------+--------------------------------+
1055| koi8_u | | Ukrainian |
1056+-----------------+--------------------------------+--------------------------------+
1057| mac_cyrillic | maccyrillic | Bulgarian, Byelorussian, |
1058| | | Macedonian, Russian, Serbian |
1059+-----------------+--------------------------------+--------------------------------+
1060| mac_greek | macgreek | Greek |
1061+-----------------+--------------------------------+--------------------------------+
1062| mac_iceland | maciceland | Icelandic |
1063+-----------------+--------------------------------+--------------------------------+
1064| mac_latin2 | maclatin2, maccentraleurope | Central and Eastern Europe |
1065+-----------------+--------------------------------+--------------------------------+
1066| mac_roman | macroman | Western Europe |
1067+-----------------+--------------------------------+--------------------------------+
1068| mac_turkish | macturkish | Turkish |
1069+-----------------+--------------------------------+--------------------------------+
1070| ptcp154 | csptcp154, pt154, cp154, | Kazakh |
1071| | cyrillic-asian | |
1072+-----------------+--------------------------------+--------------------------------+
1073| shift_jis | csshiftjis, shiftjis, sjis, | Japanese |
1074| | s_jis | |
1075+-----------------+--------------------------------+--------------------------------+
1076| shift_jis_2004 | shiftjis2004, sjis_2004, | Japanese |
1077| | sjis2004 | |
1078+-----------------+--------------------------------+--------------------------------+
1079| shift_jisx0213 | shiftjisx0213, sjisx0213, | Japanese |
1080| | s_jisx0213 | |
1081+-----------------+--------------------------------+--------------------------------+
Walter Dörwald6e390802007-08-17 16:41:28 +00001082| utf_32 | U32, utf32 | all languages |
1083+-----------------+--------------------------------+--------------------------------+
1084| utf_32_be | UTF-32BE | all languages |
1085+-----------------+--------------------------------+--------------------------------+
1086| utf_32_le | UTF-32LE | all languages |
1087+-----------------+--------------------------------+--------------------------------+
Georg Brandl8ec7f652007-08-15 14:28:01 +00001088| utf_16 | U16, utf16 | all languages |
1089+-----------------+--------------------------------+--------------------------------+
1090| utf_16_be | UTF-16BE | all languages (BMP only) |
1091+-----------------+--------------------------------+--------------------------------+
1092| utf_16_le | UTF-16LE | all languages (BMP only) |
1093+-----------------+--------------------------------+--------------------------------+
1094| utf_7 | U7, unicode-1-1-utf-7 | all languages |
1095+-----------------+--------------------------------+--------------------------------+
1096| utf_8 | U8, UTF, utf8 | all languages |
1097+-----------------+--------------------------------+--------------------------------+
1098| utf_8_sig | | all languages |
1099+-----------------+--------------------------------+--------------------------------+
1100
Serhiy Storchaka54f70922013-05-22 15:28:30 +03001101Python Specific Encodings
1102-------------------------
Georg Brandl8ec7f652007-08-15 14:28:01 +00001103
Serhiy Storchaka54f70922013-05-22 15:28:30 +03001104A number of predefined codecs are specific to Python, so their codec names have
1105no meaning outside Python. These are listed in the tables below based on the
1106expected input and output types (note that while text encodings are the most
1107common use case for codecs, the underlying codec infrastructure supports
1108arbitrary data transforms rather than just text encodings). For asymmetric
1109codecs, the stated purpose describes the encoding direction.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001110
Serhiy Storchaka54f70922013-05-22 15:28:30 +03001111The following codecs provide unicode-to-str encoding [#encoding-note]_ and
1112str-to-unicode decoding [#decoding-note]_, similar to the Unicode text
1113encodings.
Georg Brandl116aa622007-08-15 14:28:22 +00001114
Serhiy Storchaka54f70922013-05-22 15:28:30 +03001115.. tabularcolumns:: |l|L|L|
1116
1117+--------------------+---------------------------+---------------------------+
1118| Codec | Aliases | Purpose |
1119+====================+===========================+===========================+
1120| idna | | Implements :rfc:`3490`, |
1121| | | see also |
1122| | | :mod:`encodings.idna` |
1123+--------------------+---------------------------+---------------------------+
1124| mbcs | dbcs | Windows only: Encode |
1125| | | operand according to the |
1126| | | ANSI codepage (CP_ACP) |
1127+--------------------+---------------------------+---------------------------+
1128| palmos | | Encoding of PalmOS 3.5 |
1129+--------------------+---------------------------+---------------------------+
1130| punycode | | Implements :rfc:`3492` |
1131+--------------------+---------------------------+---------------------------+
1132| raw_unicode_escape | | Produce a string that is |
1133| | | suitable as raw Unicode |
1134| | | literal in Python source |
1135| | | code |
1136+--------------------+---------------------------+---------------------------+
1137| rot_13 | rot13 | Returns the Caesar-cypher |
1138| | | encryption of the operand |
1139+--------------------+---------------------------+---------------------------+
1140| undefined | | Raise an exception for |
1141| | | all conversions. Can be |
1142| | | used as the system |
1143| | | encoding if no automatic |
1144| | | :term:`coercion` between |
1145| | | byte and Unicode strings |
1146| | | is desired. |
1147+--------------------+---------------------------+---------------------------+
1148| unicode_escape | | Produce a string that is |
1149| | | suitable as Unicode |
1150| | | literal in Python source |
1151| | | code |
1152+--------------------+---------------------------+---------------------------+
1153| unicode_internal | | Return the internal |
1154| | | representation of the |
1155| | | operand |
1156+--------------------+---------------------------+---------------------------+
Georg Brandl8ec7f652007-08-15 14:28:01 +00001157
1158.. versionadded:: 2.3
1159 The ``idna`` and ``punycode`` encodings.
1160
Serhiy Storchaka54f70922013-05-22 15:28:30 +03001161The following codecs provide str-to-str encoding and decoding
1162[#decoding-note]_.
1163
1164.. tabularcolumns:: |l|L|L|L|
1165
1166+--------------------+---------------------------+---------------------------+------------------------------+
1167| Codec | Aliases | Purpose | Encoder/decoder |
1168+====================+===========================+===========================+==============================+
1169| base64_codec | base64, base-64 | Convert operand to MIME | :meth:`base64.b64encode`, |
1170| | | base64 (the result always | :meth:`base64.b64decode` |
1171| | | includes a trailing | |
1172| | | ``'\n'``) | |
1173+--------------------+---------------------------+---------------------------+------------------------------+
1174| bz2_codec | bz2 | Compress the operand | :meth:`bz2.compress`, |
1175| | | using bz2 | :meth:`bz2.decompress` |
1176+--------------------+---------------------------+---------------------------+------------------------------+
1177| hex_codec | hex | Convert operand to | :meth:`base64.b16encode`, |
1178| | | hexadecimal | :meth:`base64.b16decode` |
1179| | | representation, with two | |
1180| | | digits per byte | |
1181+--------------------+---------------------------+---------------------------+------------------------------+
1182| quopri_codec | quopri, quoted-printable, | Convert operand to MIME | :meth:`quopri.encodestring`, |
1183| | quotedprintable | quoted printable | :meth:`quopri.decodestring` |
1184+--------------------+---------------------------+---------------------------+------------------------------+
1185| string_escape | | Produce a string that is | |
1186| | | suitable as string | |
1187| | | literal in Python source | |
1188| | | code | |
1189+--------------------+---------------------------+---------------------------+------------------------------+
1190| uu_codec | uu | Convert the operand using | :meth:`uu.encode`, |
1191| | | uuencode | :meth:`uu.decode` |
1192+--------------------+---------------------------+---------------------------+------------------------------+
1193| zlib_codec | zip, zlib | Compress the operand | :meth:`zlib.compress`, |
1194| | | using gzip | :meth:`zlib.decompress` |
1195+--------------------+---------------------------+---------------------------+------------------------------+
1196
1197.. [#encoding-note] str objects are also accepted as input in place of unicode
1198 objects. They are implicitly converted to unicode by decoding them using
1199 the default encoding. If this conversion fails, it may lead to encoding
1200 operations raising :exc:`UnicodeDecodeError`.
1201
1202.. [#decoding-note] unicode objects are also accepted as input in place of str
1203 objects. They are implicitly converted to str by encoding them using the
1204 default encoding. If this conversion fails, it may lead to decoding
1205 operations raising :exc:`UnicodeEncodeError`.
1206
Georg Brandl8ec7f652007-08-15 14:28:01 +00001207
1208:mod:`encodings.idna` --- Internationalized Domain Names in Applications
1209------------------------------------------------------------------------
1210
1211.. module:: encodings.idna
1212 :synopsis: Internationalized Domain Names implementation
1213.. moduleauthor:: Martin v. Löwis
1214
1215.. versionadded:: 2.3
1216
1217This module implements :rfc:`3490` (Internationalized Domain Names in
1218Applications) and :rfc:`3492` (Nameprep: A Stringprep Profile for
1219Internationalized Domain Names (IDN)). It builds upon the ``punycode`` encoding
1220and :mod:`stringprep`.
1221
1222These RFCs together define a protocol to support non-ASCII characters in domain
1223names. A domain name containing non-ASCII characters (such as
1224``www.Alliancefrançaise.nu``) is converted into an ASCII-compatible encoding
1225(ACE, such as ``www.xn--alliancefranaise-npb.nu``). The ACE form of the domain
1226name is then used in all places where arbitrary characters are not allowed by
1227the protocol, such as DNS queries, HTTP :mailheader:`Host` fields, and so
1228on. This conversion is carried out in the application; if possible invisible to
1229the user: The application should transparently convert Unicode domain labels to
1230IDNA on the wire, and convert back ACE labels to Unicode before presenting them
1231to the user.
1232
R David Murraya2472d22011-04-13 14:20:30 -04001233Python supports this conversion in several ways: the ``idna`` codec performs
1234conversion between Unicode and ACE, separating an input string into labels
1235based on the separator characters defined in `section 3.1`_ (1) of :rfc:`3490`
1236and converting each label to ACE as required, and conversely separating an input
1237byte string into labels based on the ``.`` separator and converting any ACE
1238labels found into unicode. Furthermore, the :mod:`socket` module
Georg Brandl8ec7f652007-08-15 14:28:01 +00001239transparently converts Unicode host names to ACE, so that applications need not
1240be concerned about converting host names themselves when they pass them to the
1241socket module. On top of that, modules that have host names as function
1242parameters, such as :mod:`httplib` and :mod:`ftplib`, accept Unicode host names
1243(:mod:`httplib` then also transparently sends an IDNA hostname in the
1244:mailheader:`Host` field if it sends that field at all).
1245
R David Murraya2472d22011-04-13 14:20:30 -04001246.. _section 3.1: http://tools.ietf.org/html/rfc3490#section-3.1
1247
Georg Brandl8ec7f652007-08-15 14:28:01 +00001248When receiving host names from the wire (such as in reverse name lookup), no
1249automatic conversion to Unicode is performed: Applications wishing to present
1250such host names to the user should decode them to Unicode.
1251
1252The module :mod:`encodings.idna` also implements the nameprep procedure, which
1253performs certain normalizations on host names, to achieve case-insensitivity of
1254international domain names, and to unify similar characters. The nameprep
1255functions can be used directly if desired.
1256
1257
1258.. function:: nameprep(label)
1259
1260 Return the nameprepped version of *label*. The implementation currently assumes
1261 query strings, so ``AllowUnassigned`` is true.
1262
1263
1264.. function:: ToASCII(label)
1265
1266 Convert a label to ASCII, as specified in :rfc:`3490`. ``UseSTD3ASCIIRules`` is
1267 assumed to be false.
1268
1269
1270.. function:: ToUnicode(label)
1271
1272 Convert a label to Unicode, as specified in :rfc:`3490`.
1273
1274
1275:mod:`encodings.utf_8_sig` --- UTF-8 codec with BOM signature
1276-------------------------------------------------------------
1277
1278.. module:: encodings.utf_8_sig
1279 :synopsis: UTF-8 codec with BOM signature
1280.. moduleauthor:: Walter Dörwald
1281
1282.. versionadded:: 2.5
1283
1284This module implements a variant of the UTF-8 codec: On encoding a UTF-8 encoded
1285BOM will be prepended to the UTF-8 encoded bytes. For the stateful encoder this
1286is only done once (on the first write to the byte stream). For decoding an
1287optional UTF-8 encoded BOM at the start of the data will be skipped.
1288