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