Debian Codegraph @

Doc/library/codecs.rst

raw
1 :mod:`!codecs` --- Codec registry and base classes
2 ==================================================
3
4 .. module:: codecs
5 :synopsis: Encode and decode data and streams.
6
7 .. moduleauthor:: Marc-André Lemburg <[email protected]>
8 .. sectionauthor:: Marc-André Lemburg <[email protected]>
9 .. sectionauthor:: Martin v. Löwis <[email protected]>
10
11 **Source code:** :source:`Lib/codecs.py`
12
13 .. index::
14 single: Unicode
15 single: Codecs
16 pair: Codecs; encode
17 pair: Codecs; decode
18 single: streams
19 pair: stackable; streams
20
21 --------------
22
23 This module defines base classes for standard Python codecs (encoders and
24 decoders) and provides access to the internal Python codec registry, which
25 manages the codec and error handling lookup process. Most standard codecs
26 are :term:`text encodings <text encoding>`, which encode text to bytes (and
27 decode bytes to text), but there are also codecs provided that encode text to
28 text, and bytes to bytes. Custom codecs may encode and decode between arbitrary
29 types, but some module features are restricted to be used specifically with
30 :term:`text encodings <text encoding>` or with codecs that encode to
31 :class:`bytes`.
32
33 The module defines the following functions for encoding and decoding with
34 any codec:
35
36 .. function:: encode(obj, encoding='utf-8', errors='strict')
37
38 Encodes *obj* using the codec registered for *encoding*.
39
40 *Errors* may be given to set the desired error handling scheme. The
41 default error handler is ``'strict'`` meaning that encoding errors raise
42 :exc:`ValueError` (or a more codec specific subclass, such as
43 :exc:`UnicodeEncodeError`). Refer to :ref:`codec-base-classes` for more
44 information on codec error handling.
45
46 .. function:: decode(obj, encoding='utf-8', errors='strict')
47
48 Decodes *obj* using the codec registered for *encoding*.
49
50 *Errors* may be given to set the desired error handling scheme. The
51 default error handler is ``'strict'`` meaning that decoding errors raise
52 :exc:`ValueError` (or a more codec specific subclass, such as
53 :exc:`UnicodeDecodeError`). Refer to :ref:`codec-base-classes` for more
54 information on codec error handling.
55
56 .. function:: charmap_build(string)
57
58 Return a mapping suitable for encoding with a custom single-byte encoding.
59 Given a :class:`str` *string* of up to 256 characters representing a
60 decoding table, returns either a compact internal mapping object
61 ``EncodingMap`` or a :class:`dictionary <dict>` mapping character ordinals
62 to byte values. Raises a :exc:`TypeError` on invalid input.
63
64 The full details for each codec can also be looked up directly:
65
66 .. function:: lookup(encoding)
67
68 Looks up the codec info in the Python codec registry and returns a
69 :class:`CodecInfo` object as defined below.
70
71 Encodings are first looked up in the registry's cache. If not found, the list of
72 registered search functions is scanned. If no :class:`CodecInfo` object is
73 found, a :exc:`LookupError` is raised. Otherwise, the :class:`CodecInfo` object
74 is stored in the cache and returned to the caller.
75
76 .. class:: CodecInfo(encode, decode, streamreader=None, streamwriter=None, incrementalencoder=None, incrementaldecoder=None, name=None)
77
78 Codec details when looking up the codec registry. The constructor
79 arguments are stored in attributes of the same name:
80
81
82 .. attribute:: name
83
84 The name of the encoding.
85
86
87 .. attribute:: encode
88 decode
89
90 The stateless encoding and decoding functions. These must be
91 functions or methods which have the same interface as
92 the :meth:`~Codec.encode` and :meth:`~Codec.decode` methods of Codec
93 instances (see :ref:`Codec Interface <codec-objects>`).
94 The functions or methods are expected to work in a stateless mode.
95
96
97 .. attribute:: incrementalencoder
98 incrementaldecoder
99
100 Incremental encoder and decoder classes or factory functions.
101 These have to provide the interface defined by the base classes
102 :class:`IncrementalEncoder` and :class:`IncrementalDecoder`,
103 respectively. Incremental codecs can maintain state.
104
105
106 .. attribute:: streamwriter
107 streamreader
108
109 Stream writer and reader classes or factory functions. These have to
110 provide the interface defined by the base classes
111 :class:`StreamWriter` and :class:`StreamReader`, respectively.
112 Stream codecs can maintain state.
113
114 To simplify access to the various codec components, the module provides
115 these additional functions which use :func:`lookup` for the codec lookup:
116
117 .. function:: getencoder(encoding)
118
119 Look up the codec for the given encoding and return its encoder function.
120
121 Raises a :exc:`LookupError` in case the encoding cannot be found.
122
123
124 .. function:: getdecoder(encoding)
125
126 Look up the codec for the given encoding and return its decoder function.
127
128 Raises a :exc:`LookupError` in case the encoding cannot be found.
129
130
131 .. function:: getincrementalencoder(encoding)
132
133 Look up the codec for the given encoding and return its incremental encoder
134 class or factory function.
135
136 Raises a :exc:`LookupError` in case the encoding cannot be found or the codec
137 doesn't support an incremental encoder.
138
139
140 .. function:: getincrementaldecoder(encoding)
141
142 Look up the codec for the given encoding and return its incremental decoder
143 class or factory function.
144
145 Raises a :exc:`LookupError` in case the encoding cannot be found or the codec
146 doesn't support an incremental decoder.
147
148
149 .. function:: getreader(encoding)
150
151 Look up the codec for the given encoding and return its :class:`StreamReader`
152 class or factory function.
153
154 Raises a :exc:`LookupError` in case the encoding cannot be found.
155
156
157 .. function:: getwriter(encoding)
158
159 Look up the codec for the given encoding and return its :class:`StreamWriter`
160 class or factory function.
161
162 Raises a :exc:`LookupError` in case the encoding cannot be found.
163
164 Custom codecs are made available by registering a suitable codec search
165 function:
166
167 .. function:: register(search_function)
168
169 Register a codec search function. Search functions are expected to take one
170 argument, being the encoding name in all lower case letters with hyphens
171 and spaces converted to underscores, and return a :class:`CodecInfo` object.
172 In case a search function cannot find a given encoding, it should return
173 ``None``.
174
175 .. versionchanged:: 3.9
176 Hyphens and spaces are converted to underscore.
177
178
179 .. function:: unregister(search_function)
180
181 Unregister a codec search function and clear the registry's cache.
182 If the search function is not registered, do nothing.
183
184 .. versionadded:: 3.10
185
186
187 While the builtin :func:`open` and the associated :mod:`io` module are the
188 recommended approach for working with encoded text files, this module
189 provides additional utility functions and classes that allow the use of a
190 wider range of codecs when working with binary files:
191
192 .. function:: open(filename, mode='r', encoding=None, errors='strict', buffering=-1)
193
194 Open an encoded file using the given *mode* and return an instance of
195 :class:`StreamReaderWriter`, providing transparent encoding/decoding.
196 The default file mode is ``'r'``, meaning to open the file in read mode.
197
198 .. note::
199
200 If *encoding* is not ``None``, then the
201 underlying encoded files are always opened in binary mode.
202 No automatic conversion of ``'\n'`` is done on reading and writing.
203 The *mode* argument may be any binary mode acceptable to the built-in
204 :func:`open` function; the ``'b'`` is automatically added.
205
206 *encoding* specifies the encoding which is to be used for the file.
207 Any encoding that encodes to and decodes from bytes is allowed, and
208 the data types supported by the file methods depend on the codec used.
209
210 *errors* may be given to define the error handling. It defaults to ``'strict'``
211 which causes a :exc:`ValueError` to be raised in case an encoding error occurs.
212
213 *buffering* has the same meaning as for the built-in :func:`open` function.
214 It defaults to -1 which means that the default buffer size will be used.
215
216 .. versionchanged:: 3.11
217 The ``'U'`` mode has been removed.
218
219
220 .. function:: EncodedFile(file, data_encoding, file_encoding=None, errors='strict')
221
222 Return a :class:`StreamRecoder` instance, a wrapped version of *file*
223 which provides transparent transcoding. The original file is closed
224 when the wrapped version is closed.
225
226 Data written to the wrapped file is decoded according to the given
227 *data_encoding* and then written to the original file as bytes using
228 *file_encoding*. Bytes read from the original file are decoded
229 according to *file_encoding*, and the result is encoded
230 using *data_encoding*.
231
232 If *file_encoding* is not given, it defaults to *data_encoding*.
233
234 *errors* may be given to define the error handling. It defaults to
235 ``'strict'``, which causes :exc:`ValueError` to be raised in case an encoding
236 error occurs.
237
238
239 .. function:: iterencode(iterator, encoding, errors='strict', **kwargs)
240
241 Uses an incremental encoder to iteratively encode the input provided by
242 *iterator*. *iterator* must yield :class:`str` objects.
243 This function is a :term:`generator`. The *errors* argument (as well as any
244 other keyword argument) is passed through to the incremental encoder.
245
246 This function requires that the codec accept text :class:`str` objects
247 to encode. Therefore it does not support bytes-to-bytes encoders such as
248 ``base64_codec``.
249
250
251 .. function:: iterdecode(iterator, encoding, errors='strict', **kwargs)
252
253 Uses an incremental decoder to iteratively decode the input provided by
254 *iterator*. *iterator* must yield :class:`bytes` objects.
255 This function is a :term:`generator`. The *errors* argument (as well as any
256 other keyword argument) is passed through to the incremental decoder.
257
258 This function requires that the codec accept :class:`bytes` objects
259 to decode. Therefore it does not support text-to-text encoders such as
260 ``rot_13``, although ``rot_13`` may be used equivalently with
261 :func:`iterencode`.
262
263
264 .. function:: readbuffer_encode(buffer, errors=None, /)
265
266 Return a :class:`tuple` containing the raw bytes of *buffer*, a
267 :ref:`buffer-compatible object <bufferobjects>` or :class:`str`
268 (encoded to UTF-8 before processing), and their length in bytes.
269
270 The *errors* argument is ignored.
271
272 .. code-block:: pycon
273
274 >>> codecs.readbuffer_encode(b"Zito")
275 (b'Zito', 4)
276
277
278 The module also provides the following constants which are useful for reading
279 and writing to platform dependent files:
280
281
282 .. data:: BOM
283 BOM_BE
284 BOM_LE
285 BOM_UTF8
286 BOM_UTF16
287 BOM_UTF16_BE
288 BOM_UTF16_LE
289 BOM_UTF32
290 BOM_UTF32_BE
291 BOM_UTF32_LE
292
293 These constants define various byte sequences,
294 being Unicode byte order marks (BOMs) for several encodings. They are
295 used in UTF-16 and UTF-32 data streams to indicate the byte order used,
296 and in UTF-8 as a Unicode signature. :const:`BOM_UTF16` is either
297 :const:`BOM_UTF16_BE` or :const:`BOM_UTF16_LE` depending on the platform's
298 native byte order, :const:`BOM` is an alias for :const:`BOM_UTF16`,
299 :const:`BOM_LE` for :const:`BOM_UTF16_LE` and :const:`BOM_BE` for
300 :const:`BOM_UTF16_BE`. The others represent the BOM in UTF-8 and UTF-32
301 encodings.
302
303
304 .. _codec-base-classes:
305
306 Codec Base Classes
307 ------------------
308
309 The :mod:`codecs` module defines a set of base classes which define the
310 interfaces for working with codec objects, and can also be used as the basis
311 for custom codec implementations.
312
313 Each codec has to define four interfaces to make it usable as codec in Python:
314 stateless encoder, stateless decoder, stream reader and stream writer. The
315 stream reader and writers typically reuse the stateless encoder/decoder to
316 implement the file protocols. Codec authors also need to define how the
317 codec will handle encoding and decoding errors.
318
319
320 .. _surrogateescape:
321 .. _error-handlers:
322
323 Error Handlers
324 ^^^^^^^^^^^^^^
325
326 To simplify and standardize error handling, codecs may implement different
327 error handling schemes by accepting the *errors* string argument:
328
329 >>> 'German ß, ♬'.encode(encoding='ascii', errors='backslashreplace')
330 b'German \\xdf, \\u266c'
331 >>> 'German ß, ♬'.encode(encoding='ascii', errors='xmlcharrefreplace')
332 b'German &#223;, &#9836;'
333
334 .. index::
335 pair: strict; error handler's name
336 pair: ignore; error handler's name
337 pair: replace; error handler's name
338 pair: backslashreplace; error handler's name
339 pair: surrogateescape; error handler's name
340 single: ? (question mark); replacement character
341 single: \ (backslash); escape sequence
342 single: \x; escape sequence
343 single: \u; escape sequence
344 single: \U; escape sequence
345
346 The following error handlers can be used with all Python
347 :ref:`standard-encodings` codecs:
348
349 .. tabularcolumns:: |l|L|
350
351 +-------------------------+-----------------------------------------------+
352 | Value | Meaning |
353 +=========================+===============================================+
354 | ``'strict'`` | Raise :exc:`UnicodeError` (or a subclass), |
355 | | this is the default. Implemented in |
356 | | :func:`strict_errors`. |
357 +-------------------------+-----------------------------------------------+
358 | ``'ignore'`` | Ignore the malformed data and continue without|
359 | | further notice. Implemented in |
360 | | :func:`ignore_errors`. |
361 +-------------------------+-----------------------------------------------+
362 | ``'replace'`` | Replace with a replacement marker. On |
363 | | encoding, use ``?`` (ASCII character). On |
364 | | decoding, use ``�`` (U+FFFD, the official |
365 | | REPLACEMENT CHARACTER). Implemented in |
366 | | :func:`replace_errors`. |
367 +-------------------------+-----------------------------------------------+
368 | ``'backslashreplace'`` | Replace with backslashed escape sequences. |
369 | | On encoding, use hexadecimal form of Unicode |
370 | | code point with formats :samp:`\\x{hh}` |
371 | | :samp:`\\u{xxxx}` :samp:`\\U{xxxxxxxx}`. |
372 | | On decoding, use hexadecimal form of byte |
373 | | value with format :samp:`\\x{hh}`. |
374 | | Implemented in |
375 | | :func:`backslashreplace_errors`. |
376 +-------------------------+-----------------------------------------------+
377 | ``'surrogateescape'`` | On decoding, replace byte with individual |
378 | | surrogate code ranging from ``U+DC80`` to |
379 | | ``U+DCFF``. This code will then be turned |
380 | | back into the same byte when the |
381 | | ``'surrogateescape'`` error handler is used |
382 | | when encoding the data. (See :pep:`383` for |
383 | | more.) |
384 +-------------------------+-----------------------------------------------+
385
386 .. index::
387 pair: xmlcharrefreplace; error handler's name
388 pair: namereplace; error handler's name
389 single: \N; escape sequence
390
391 The following error handlers are only applicable to encoding (within
392 :term:`text encodings <text encoding>`):
393
394 +-------------------------+-----------------------------------------------+
395 | Value | Meaning |
396 +=========================+===============================================+
397 | ``'xmlcharrefreplace'`` | Replace with XML/HTML numeric character |
398 | | reference, which is a decimal form of Unicode |
399 | | code point with format :samp:`&#{num};`. |
400 | | Implemented in |
401 | | :func:`xmlcharrefreplace_errors`. |
402 +-------------------------+-----------------------------------------------+
403 | ``'namereplace'`` | Replace with ``\N{...}`` escape sequences, |
404 | | what appears in the braces is the Name |
405 | | property from Unicode Character Database. |
406 | | Implemented in :func:`namereplace_errors`. |
407 +-------------------------+-----------------------------------------------+
408
409 .. index::
410 pair: surrogatepass; error handler's name
411
412 In addition, the following error handler is specific to the given codecs:
413
414 +-------------------+------------------------+-------------------------------------------+
415 | Value | Codecs | Meaning |
416 +===================+========================+===========================================+
417 |``'surrogatepass'``| utf-8, utf-16, utf-32, | Allow encoding and decoding surrogate code|
418 | | utf-16-be, utf-16-le, | point (``U+D800`` - ``U+DFFF``) as normal |
419 | | utf-32-be, utf-32-le | code point. Otherwise these codecs treat |
420 | | | the presence of surrogate code point in |
421 | | | :class:`str` as an error. |
422 +-------------------+------------------------+-------------------------------------------+
423
424 .. versionadded:: 3.1
425 The ``'surrogateescape'`` and ``'surrogatepass'`` error handlers.
426
427 .. versionchanged:: 3.4
428 The ``'surrogatepass'`` error handler now works with utf-16\* and utf-32\*
429 codecs.
430
431 .. versionadded:: 3.5
432 The ``'namereplace'`` error handler.
433
434 .. versionchanged:: 3.5
435 The ``'backslashreplace'`` error handler now works with decoding and
436 translating.
437
438 The set of allowed values can be extended by registering a new named error
439 handler:
440
441 .. function:: register_error(name, error_handler)
442
443 Register the error handling function *error_handler* under the name *name*.
444 The *error_handler* argument will be called during encoding and decoding
445 in case of an error, when *name* is specified as the errors parameter.
446
447 For encoding, *error_handler* will be called with a :exc:`UnicodeEncodeError`
448 instance, which contains information about the location of the error. The
449 error handler must either raise this or a different exception, or return a
450 tuple with a replacement for the unencodable part of the input and a position
451 where encoding should continue. The replacement may be either :class:`str` or
452 :class:`bytes`. If the replacement is bytes, the encoder will simply copy
453 them into the output buffer. If the replacement is a string, the encoder will
454 encode the replacement. Encoding continues on original input at the
455 specified position. Negative position values will be treated as being
456 relative to the end of the input string. If the resulting position is out of
457 bound an :exc:`IndexError` will be raised.
458
459 Decoding and translating works similarly, except :exc:`UnicodeDecodeError` or
460 :exc:`UnicodeTranslateError` will be passed to the handler and that the
461 replacement from the error handler will be put into the output directly.
462
463
464 Previously registered error handlers (including the standard error handlers)
465 can be looked up by name:
466
467 .. function:: lookup_error(name)
468
469 Return the error handler previously registered under the name *name*.
470
471 Raises a :exc:`LookupError` in case the handler cannot be found.
472
473 The following standard error handlers are also made available as module level
474 functions:
475
476 .. function:: strict_errors(exception)
477
478 Implements the ``'strict'`` error handling.
479
480 Each encoding or decoding error raises a :exc:`UnicodeError`.
481
482
483 .. function:: ignore_errors(exception)
484
485 Implements the ``'ignore'`` error handling.
486
487 Malformed data is ignored; encoding or decoding is continued without
488 further notice.
489
490
491 .. function:: replace_errors(exception)
492
493 Implements the ``'replace'`` error handling.
494
495 Substitutes ``?`` (ASCII character) for encoding errors or ``�`` (U+FFFD,
496 the official REPLACEMENT CHARACTER) for decoding errors.
497
498
499 .. function:: backslashreplace_errors(exception)
500
501 Implements the ``'backslashreplace'`` error handling.
502
503 Malformed data is replaced by a backslashed escape sequence.
504 On encoding, use the hexadecimal form of Unicode code point with formats
505 :samp:`\\x{hh}` :samp:`\\u{xxxx}` :samp:`\\U{xxxxxxxx}`.
506 On decoding, use the hexadecimal form of
507 byte value with format :samp:`\\x{hh}`.
508
509 .. versionchanged:: 3.5
510 Works with decoding and translating.
511
512
513 .. function:: xmlcharrefreplace_errors(exception)
514
515 Implements the ``'xmlcharrefreplace'`` error handling (for encoding within
516 :term:`text encoding` only).
517
518 The unencodable character is replaced by an appropriate XML/HTML numeric
519 character reference, which is a decimal form of Unicode code point with
520 format :samp:`&#{num};` .
521
522
523 .. function:: namereplace_errors(exception)
524
525 Implements the ``'namereplace'`` error handling (for encoding within
526 :term:`text encoding` only).
527
528 The unencodable character is replaced by a ``\N{...}`` escape sequence. The
529 set of characters that appear in the braces is the Name property from
530 Unicode Character Database. For example, the German lowercase letter ``'ß'``
531 will be converted to byte sequence ``\N{LATIN SMALL LETTER SHARP S}`` .
532
533 .. versionadded:: 3.5
534
535
536 .. _codec-objects:
537
538 Stateless Encoding and Decoding
539 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
540
541 The base :class:`Codec` class defines these methods which also define the
542 function interfaces of the stateless encoder and decoder:
543
544
545 .. class:: Codec
546
547 .. method:: encode(input, errors='strict')
548
549 Encodes the object *input* and returns a tuple (output object, length consumed).
550 For instance, :term:`text encoding` converts
551 a string object to a bytes object using a particular
552 character set encoding (e.g., ``cp1252`` or ``iso-8859-1``).
553
554 The *errors* argument defines the error handling to apply.
555 It defaults to ``'strict'`` handling.
556
557 The method may not store state in the :class:`Codec` instance. Use
558 :class:`StreamWriter` for codecs which have to keep state in order to make
559 encoding efficient.
560
561 The encoder must be able to handle zero length input and return an empty object
562 of the output object type in this situation.
563
564
565 .. method:: decode(input, errors='strict')
566
567 Decodes the object *input* and returns a tuple (output object, length
568 consumed). For instance, for a :term:`text encoding`, decoding converts
569 a bytes object encoded using a particular
570 character set encoding to a string object.
571
572 For text encodings and bytes-to-bytes codecs,
573 *input* must be a bytes object or one which provides the read-only
574 buffer interface -- for example, buffer objects and memory mapped files.
575
576 The *errors* argument defines the error handling to apply.
577 It defaults to ``'strict'`` handling.
578
579 The method may not store state in the :class:`Codec` instance. Use
580 :class:`StreamReader` for codecs which have to keep state in order to make
581 decoding efficient.
582
583 The decoder must be able to handle zero length input and return an empty object
584 of the output object type in this situation.
585
586
587 Incremental Encoding and Decoding
588 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
589
590 The :class:`IncrementalEncoder` and :class:`IncrementalDecoder` classes provide
591 the basic interface for incremental encoding and decoding. Encoding/decoding the
592 input isn't done with one call to the stateless encoder/decoder function, but
593 with multiple calls to the
594 :meth:`~IncrementalEncoder.encode`/:meth:`~IncrementalDecoder.decode` method of
595 the incremental encoder/decoder. The incremental encoder/decoder keeps track of
596 the encoding/decoding process during method calls.
597
598 The joined output of calls to the
599 :meth:`~IncrementalEncoder.encode`/:meth:`~IncrementalDecoder.decode` method is
600 the same as if all the single inputs were joined into one, and this input was
601 encoded/decoded with the stateless encoder/decoder.
602
603
604 .. _incremental-encoder-objects:
605
606 IncrementalEncoder Objects
607 ~~~~~~~~~~~~~~~~~~~~~~~~~~
608
609 The :class:`IncrementalEncoder` class is used for encoding an input in multiple
610 steps. It defines the following methods which every incremental encoder must
611 define in order to be compatible with the Python codec registry.
612
613
614 .. class:: IncrementalEncoder(errors='strict')
615
616 Constructor for an :class:`IncrementalEncoder` instance.
617
618 All incremental encoders must provide this constructor interface. They are free
619 to add additional keyword arguments, but only the ones defined here are used by
620 the Python codec registry.
621
622 The :class:`IncrementalEncoder` may implement different error handling schemes
623 by providing the *errors* keyword argument. See :ref:`error-handlers` for
624 possible values.
625
626 The *errors* argument will be assigned to an attribute of the same name.
627 Assigning to this attribute makes it possible to switch between different error
628 handling strategies during the lifetime of the :class:`IncrementalEncoder`
629 object.
630
631
632 .. method:: encode(object, final=False)
633
634 Encodes *object* (taking the current state of the encoder into account)
635 and returns the resulting encoded object. If this is the last call to
636 :meth:`encode` *final* must be true (the default is false).
637
638
639 .. method:: reset()
640
641 Reset the encoder to the initial state. The output is discarded: call
642 ``.encode(object, final=True)``, passing an empty byte or text string
643 if necessary, to reset the encoder and to get the output.
644
645
646 .. method:: getstate()
647
648 Return the current state of the encoder which must be an integer. The
649 implementation should make sure that ``0`` is the most common
650 state. (States that are more complicated than integers can be converted
651 into an integer by marshaling/pickling the state and encoding the bytes
652 of the resulting string into an integer.)
653
654
655 .. method:: setstate(state)
656
657 Set the state of the encoder to *state*. *state* must be an encoder state
658 returned by :meth:`getstate`.
659
660
661 .. _incremental-decoder-objects:
662
663 IncrementalDecoder Objects
664 ~~~~~~~~~~~~~~~~~~~~~~~~~~
665
666 The :class:`IncrementalDecoder` class is used for decoding an input in multiple
667 steps. It defines the following methods which every incremental decoder must
668 define in order to be compatible with the Python codec registry.
669
670
671 .. class:: IncrementalDecoder(errors='strict')
672
673 Constructor for an :class:`IncrementalDecoder` instance.
674
675 All incremental decoders must provide this constructor interface. They are free
676 to add additional keyword arguments, but only the ones defined here are used by
677 the Python codec registry.
678
679 The :class:`IncrementalDecoder` may implement different error handling schemes
680 by providing the *errors* keyword argument. See :ref:`error-handlers` for
681 possible values.
682
683 The *errors* argument will be assigned to an attribute of the same name.
684 Assigning to this attribute makes it possible to switch between different error
685 handling strategies during the lifetime of the :class:`IncrementalDecoder`
686 object.
687
688
689 .. method:: decode(object, final=False)
690
691 Decodes *object* (taking the current state of the decoder into account)
692 and returns the resulting decoded object. If this is the last call to
693 :meth:`decode` *final* must be true (the default is false). If *final* is
694 true the decoder must decode the input completely and must flush all
695 buffers. If this isn't possible (e.g. because of incomplete byte sequences
696 at the end of the input) it must initiate error handling just like in the
697 stateless case (which might raise an exception).
698
699
700 .. method:: reset()
701
702 Reset the decoder to the initial state.
703
704
705 .. method:: getstate()
706
707 Return the current state of the decoder. This must be a tuple with two
708 items, the first must be the buffer containing the still undecoded
709 input. The second must be an integer and can be additional state
710 info. (The implementation should make sure that ``0`` is the most common
711 additional state info.) If this additional state info is ``0`` it must be
712 possible to set the decoder to the state which has no input buffered and
713 ``0`` as the additional state info, so that feeding the previously
714 buffered input to the decoder returns it to the previous state without
715 producing any output. (Additional state info that is more complicated than
716 integers can be converted into an integer by marshaling/pickling the info
717 and encoding the bytes of the resulting string into an integer.)
718
719
720 .. method:: setstate(state)
721
722 Set the state of the decoder to *state*. *state* must be a decoder state
723 returned by :meth:`getstate`.
724
725
726 Stream Encoding and Decoding
727 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
728
729
730 The :class:`StreamWriter` and :class:`StreamReader` classes provide generic
731 working interfaces which can be used to implement new encoding submodules very
732 easily. See :mod:`!encodings.utf_8` for an example of how this is done.
733
734
735 .. _stream-writer-objects:
736
737 StreamWriter Objects
738 ~~~~~~~~~~~~~~~~~~~~
739
740 The :class:`StreamWriter` class is a subclass of :class:`Codec` and defines the
741 following methods which every stream writer must define in order to be
742 compatible with the Python codec registry.
743
744
745 .. class:: StreamWriter(stream, errors='strict')
746
747 Constructor for a :class:`StreamWriter` instance.
748
749 All stream writers must provide this constructor interface. They are free to add
750 additional keyword arguments, but only the ones defined here are used by the
751 Python codec registry.
752
753 The *stream* argument must be a file-like object open for writing
754 text or binary data, as appropriate for the specific codec.
755
756 The :class:`StreamWriter` may implement different error handling schemes by
757 providing the *errors* keyword argument. See :ref:`error-handlers` for
758 the standard error handlers the underlying stream codec may support.
759
760 The *errors* argument will be assigned to an attribute of the same name.
761 Assigning to this attribute makes it possible to switch between different error
762 handling strategies during the lifetime of the :class:`StreamWriter` object.
763
764 .. method:: write(object)
765
766 Writes the object's contents encoded to the stream.
767
768
769 .. method:: writelines(list)
770
771 Writes the concatenated iterable of strings to the stream (possibly by reusing
772 the :meth:`write` method). Infinite or
773 very large iterables are not supported. The standard bytes-to-bytes codecs
774 do not support this method.
775
776
777 .. method:: reset()
778
779 Resets the codec buffers used for keeping internal state.
780
781 Calling this method should ensure that the data on the output is put into
782 a clean state that allows appending of new fresh data without having to
783 rescan the whole stream to recover state.
784
785
786 In addition to the above methods, the :class:`StreamWriter` must also inherit
787 all other methods and attributes from the underlying stream.
788
789
790 .. _stream-reader-objects:
791
792 StreamReader Objects
793 ~~~~~~~~~~~~~~~~~~~~
794
795 The :class:`StreamReader` class is a subclass of :class:`Codec` and defines the
796 following methods which every stream reader must define in order to be
797 compatible with the Python codec registry.
798
799
800 .. class:: StreamReader(stream, errors='strict')
801
802 Constructor for a :class:`StreamReader` instance.
803
804 All stream readers must provide this constructor interface. They are free to add
805 additional keyword arguments, but only the ones defined here are used by the
806 Python codec registry.
807
808 The *stream* argument must be a file-like object open for reading
809 text or binary data, as appropriate for the specific codec.
810
811 The :class:`StreamReader` may implement different error handling schemes by
812 providing the *errors* keyword argument. See :ref:`error-handlers` for
813 the standard error handlers the underlying stream codec may support.
814
815 The *errors* argument will be assigned to an attribute of the same name.
816 Assigning to this attribute makes it possible to switch between different error
817 handling strategies during the lifetime of the :class:`StreamReader` object.
818
819 The set of allowed values for the *errors* argument can be extended with
820 :func:`register_error`.
821
822
823 .. method:: read(size=-1, chars=-1, firstline=False)
824
825 Decodes data from the stream and returns the resulting object.
826
827 The *chars* argument indicates the number of decoded
828 code points or bytes to return. The :func:`read` method will
829 never return more data than requested, but it might return less,
830 if there is not enough available.
831
832 The *size* argument indicates the approximate maximum
833 number of encoded bytes or code points to read
834 for decoding. The decoder can modify this setting as
835 appropriate. The default value -1 indicates to read and decode as much as
836 possible. This parameter is intended to
837 prevent having to decode huge files in one step.
838
839 The *firstline* flag indicates that
840 it would be sufficient to only return the first
841 line, if there are decoding errors on later lines.
842
843 The method should use a greedy read strategy meaning that it should read
844 as much data as is allowed within the definition of the encoding and the
845 given size, e.g. if optional encoding endings or state markers are
846 available on the stream, these should be read too.
847
848
849 .. method:: readline(size=None, keepends=True)
850
851 Read one line from the input stream and return the decoded data.
852
853 *size*, if given, is passed as size argument to the stream's
854 :meth:`read` method.
855
856 If *keepends* is false line-endings will be stripped from the lines
857 returned.
858
859
860 .. method:: readlines(sizehint=None, keepends=True)
861
862 Read all lines available on the input stream and return them as a list of
863 lines.
864
865 Line-endings are implemented using the codec's :meth:`decode` method and
866 are included in the list entries if *keepends* is true.
867
868 *sizehint*, if given, is passed as the *size* argument to the stream's
869 :meth:`read` method.
870
871
872 .. method:: reset()
873
874 Resets the codec buffers used for keeping internal state.
875
876 Note that no stream repositioning should take place. This method is
877 primarily intended to be able to recover from decoding errors.
878
879
880 In addition to the above methods, the :class:`StreamReader` must also inherit
881 all other methods and attributes from the underlying stream.
882
883 .. _stream-reader-writer:
884
885 StreamReaderWriter Objects
886 ~~~~~~~~~~~~~~~~~~~~~~~~~~
887
888 The :class:`StreamReaderWriter` is a convenience class that allows wrapping
889 streams which work in both read and write modes.
890
891 The design is such that one can use the factory functions returned by the
892 :func:`lookup` function to construct the instance.
893
894
895 .. class:: StreamReaderWriter(stream, Reader, Writer, errors='strict')
896
897 Creates a :class:`StreamReaderWriter` instance. *stream* must be a file-like
898 object. *Reader* and *Writer* must be factory functions or classes providing the
899 :class:`StreamReader` and :class:`StreamWriter` interface resp. Error handling
900 is done in the same way as defined for the stream readers and writers.
901
902 :class:`StreamReaderWriter` instances define the combined interfaces of
903 :class:`StreamReader` and :class:`StreamWriter` classes. They inherit all other
904 methods and attributes from the underlying stream.
905
906
907 .. _stream-recoder-objects:
908
909 StreamRecoder Objects
910 ~~~~~~~~~~~~~~~~~~~~~
911
912 The :class:`StreamRecoder` translates data from one encoding to another,
913 which is sometimes useful when dealing with different encoding environments.
914
915 The design is such that one can use the factory functions returned by the
916 :func:`lookup` function to construct the instance.
917
918
919 .. class:: StreamRecoder(stream, encode, decode, Reader, Writer, errors='strict')
920
921 Creates a :class:`StreamRecoder` instance which implements a two-way conversion:
922 *encode* and *decode* work on the frontend — the data visible to
923 code calling :meth:`~StreamReader.read` and :meth:`~StreamWriter.write`,
924 while *Reader* and *Writer*
925 work on the backend — the data in *stream*.
926
927 You can use these objects to do transparent transcodings, e.g., from Latin-1
928 to UTF-8 and back.
929
930 The *stream* argument must be a file-like object.
931
932 The *encode* and *decode* arguments must
933 adhere to the :class:`Codec` interface. *Reader* and
934 *Writer* must be factory functions or classes providing objects of the
935 :class:`StreamReader` and :class:`StreamWriter` interface respectively.
936
937 Error handling is done in the same way as defined for the stream readers and
938 writers.
939
940
941 :class:`StreamRecoder` instances define the combined interfaces of
942 :class:`StreamReader` and :class:`StreamWriter` classes. They inherit all other
943 methods and attributes from the underlying stream.
944
945
946 .. _encodings-overview:
947
948 Encodings and Unicode
949 ---------------------
950
951 Strings are stored internally as sequences of code points in
952 range ``U+0000``--``U+10FFFF``. (See :pep:`393` for
953 more details about the implementation.)
954 Once a string object is used outside of CPU and memory, endianness
955 and how these arrays are stored as bytes become an issue. As with other
956 codecs, serialising a string into a sequence of bytes is known as *encoding*,
957 and recreating the string from the sequence of bytes is known as *decoding*.
958 There are a variety of different text serialisation codecs, which are
959 collectivity referred to as :term:`text encodings <text encoding>`.
960
961 The simplest text encoding (called ``'latin-1'`` or ``'iso-8859-1'``) maps
962 the code points 0--255 to the bytes ``0x0``--``0xff``, which means that a string
963 object that contains code points above ``U+00FF`` can't be encoded with this
964 codec. Doing so will raise a :exc:`UnicodeEncodeError` that looks
965 like the following (although the details of the error message may differ):
966 ``UnicodeEncodeError: 'latin-1' codec can't encode character '\u1234' in
967 position 3: ordinal not in range(256)``.
968
969 There's another group of encodings (the so called charmap encodings) that choose
970 a different subset of all Unicode code points and how these code points are
971 mapped to the bytes ``0x0``--``0xff``. To see how this is done simply open
972 e.g. :file:`encodings/cp1252.py` (which is an encoding that is used primarily on
973 Windows). There's a string constant with 256 characters that shows you which
974 character is mapped to which byte value.
975
976 All of these encodings can only encode 256 of the 1114112 code points
977 defined in Unicode. A simple and straightforward way that can store each Unicode
978 code point, is to store each code point as four consecutive bytes. There are two
979 possibilities: store the bytes in big endian or in little endian order. These
980 two encodings are called ``UTF-32-BE`` and ``UTF-32-LE`` respectively. Their
981 disadvantage is that if, for example, you use ``UTF-32-BE`` on a little endian
982 machine you will always have to swap bytes on encoding and decoding.
983 Python's ``UTF-16`` and ``UTF-32`` codecs avoid this problem by using the
984 platform's native byte order when no BOM is present.
985 Python follows prevailing platform
986 practice, so native-endian data round-trips without redundant byte swapping,
987 even though the Unicode Standard defaults to big-endian when the byte order is
988 unspecified. When these bytes are read by a CPU with a different endianness,
989 the bytes have to be swapped. To be able to detect the endianness of a
990 ``UTF-16`` or ``UTF-32`` byte sequence, a BOM ("Byte Order Mark") is used.
991 This is the Unicode character ``U+FEFF``. This character can be prepended to every
992 ``UTF-16`` or ``UTF-32`` byte sequence. The byte swapped version of this character
993 (``0xFFFE``) is an illegal character that may not appear in a Unicode text.
994 When the first character of a ``UTF-16`` or ``UTF-32`` byte sequence is
995 ``U+FFFE``, the bytes have to be swapped on decoding.
996
997 Unfortunately the character ``U+FEFF`` had a second purpose as
998 a ``ZERO WIDTH NO-BREAK SPACE``: a character that has no width and doesn't allow
999 a word to be split. It can e.g. be used to give hints to a ligature algorithm.
1000 With Unicode 4.0 using ``U+FEFF`` as a ``ZERO WIDTH NO-BREAK SPACE`` has been
1001 deprecated (with ``U+2060`` (``WORD JOINER``) assuming this role). Nevertheless
1002 Unicode software still must be able to handle ``U+FEFF`` in both roles: as a BOM
1003 it's a device to determine the storage layout of the encoded bytes, and vanishes
1004 once the byte sequence has been decoded into a string; as a ``ZERO WIDTH
1005 NO-BREAK SPACE`` it's a normal character that will be decoded like any other.
1006
1007 There's another encoding that is able to encode the full range of Unicode
1008 characters: UTF-8. UTF-8 is an 8-bit encoding, which means there are no issues
1009 with byte order in UTF-8. Each byte in a UTF-8 byte sequence consists of two
1010 parts: marker bits (the most significant bits) and payload bits. The marker bits
1011 are a sequence of zero to four ``1`` bits followed by a ``0`` bit. Unicode characters are
1012 encoded like this (with x being payload bits, which when concatenated give the
1013 Unicode character):
1014
1015 +-----------------------------------+----------------------------------------------+
1016 | Range | Encoding |
1017 +===================================+==============================================+
1018 | ``U-00000000`` ... ``U-0000007F`` | 0xxxxxxx |
1019 +-----------------------------------+----------------------------------------------+
1020 | ``U-00000080`` ... ``U-000007FF`` | 110xxxxx 10xxxxxx |
1021 +-----------------------------------+----------------------------------------------+
1022 | ``U-00000800`` ... ``U-0000FFFF`` | 1110xxxx 10xxxxxx 10xxxxxx |
1023 +-----------------------------------+----------------------------------------------+
1024 | ``U-00010000`` ... ``U-0010FFFF`` | 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx |
1025 +-----------------------------------+----------------------------------------------+
1026
1027 The least significant bit of the Unicode character is the rightmost x bit.
1028
1029 As UTF-8 is an 8-bit encoding no BOM is required and any ``U+FEFF`` character in
1030 the decoded string (even if it's the first character) is treated as a ``ZERO
1031 WIDTH NO-BREAK SPACE``.
1032
1033 Without external information it's impossible to reliably determine which
1034 encoding was used for encoding a string. Each charmap encoding can
1035 decode any random byte sequence. However that's not possible with UTF-8, as
1036 UTF-8 byte sequences have a structure that doesn't allow arbitrary byte
1037 sequences. To increase the reliability with which a UTF-8 encoding can be
1038 detected, Microsoft invented a variant of UTF-8 (that Python calls
1039 ``"utf-8-sig"``) for its Notepad program: Before any of the Unicode characters
1040 is written to the file, a UTF-8 encoded BOM (which looks like this as a byte
1041 sequence: ``0xef``, ``0xbb``, ``0xbf``) is written. As it's rather improbable
1042 that any charmap encoded file starts with these byte values (which would e.g.
1043 map to
1044
1045 | LATIN SMALL LETTER I WITH DIAERESIS
1046 | RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK
1047 | INVERTED QUESTION MARK
1048
1049 in iso-8859-1), this increases the probability that a ``utf-8-sig`` encoding can be
1050 correctly guessed from the byte sequence. So here the BOM is not used to be able
1051 to determine the byte order used for generating the byte sequence, but as a
1052 signature that helps in guessing the encoding. On encoding the utf-8-sig codec
1053 will write ``0xef``, ``0xbb``, ``0xbf`` as the first three bytes to the file. On
1054 decoding ``utf-8-sig`` will skip those three bytes if they appear as the first
1055 three bytes in the file. In UTF-8, the use of the BOM is discouraged and
1056 should generally be avoided.
1057
1058
1059 .. _standard-encodings:
1060
1061 Standard Encodings
1062 ------------------
1063
1064 Python comes with a number of codecs built-in, either implemented as C functions
1065 or with dictionaries as mapping tables. The following table lists the codecs by
1066 name, together with a few common aliases, and the languages for which the
1067 encoding is likely used. Neither the list of aliases nor the list of languages
1068 is meant to be exhaustive. Notice that spelling alternatives that only differ in
1069 case or use a hyphen instead of an underscore are also valid aliases
1070 because they are equivalent when normalized by
1071 :func:`~encodings.normalize_encoding`. For example, ``'utf-8'`` is a valid
1072 alias for the ``'utf_8'`` codec.
1073
1074 .. note::
1075
1076 The below table lists the most common aliases, for a complete list
1077 refer to the source :source:`aliases.py <Lib/encodings/aliases.py>` file.
1078
1079 .. impl-detail::
1080
1081 Some common encodings can bypass the codecs lookup machinery to
1082 improve performance. These optimization opportunities are only
1083 recognized by CPython for a limited set of (case insensitive)
1084 aliases: utf-8, utf8, latin-1, latin1, iso-8859-1, iso8859-1, mbcs
1085 (Windows only), ascii, us-ascii, utf-16, utf16, utf-32, utf32, and
1086 the same using underscores instead of dashes. Using alternative
1087 aliases for these encodings may result in slower execution.
1088
1089 .. versionchanged:: 3.6
1090 Optimization opportunity recognized for us-ascii.
1091
1092 Many of the character sets support the same languages. They vary in individual
1093 characters (e.g. whether the EURO SIGN is supported or not), and in the
1094 assignment of characters to code positions. For the European languages in
1095 particular, the following variants typically exist:
1096
1097 * an ISO 8859 codeset
1098
1099 * a Microsoft Windows code page, which is typically derived from an 8859 codeset,
1100 but replaces control characters with additional graphic characters
1101
1102 * an IBM EBCDIC code page
1103
1104 * an IBM PC code page, which is ASCII compatible
1105
1106 .. tabularcolumns:: |l|p{0.3\linewidth}|p{0.3\linewidth}|
1107
1108 +-----------------+--------------------------------+--------------------------------+
1109 | Codec | Aliases | Languages |
1110 +=================+================================+================================+
1111 | ascii | 646, us-ascii | English |
1112 +-----------------+--------------------------------+--------------------------------+
1113 | big5 | big5-tw, csbig5 | Traditional Chinese |
1114 +-----------------+--------------------------------+--------------------------------+
1115 | big5hkscs | big5-hkscs, hkscs | Traditional Chinese |
1116 +-----------------+--------------------------------+--------------------------------+
1117 | cp037 | IBM037, IBM039 | English |
1118 +-----------------+--------------------------------+--------------------------------+
1119 | cp273 | 273, IBM273, csIBM273 | German |
1120 | | | |
1121 | | | .. versionadded:: 3.4 |
1122 +-----------------+--------------------------------+--------------------------------+
1123 | cp424 | EBCDIC-CP-HE, IBM424 | Hebrew |
1124 +-----------------+--------------------------------+--------------------------------+
1125 | cp437 | 437, IBM437 | English |
1126 +-----------------+--------------------------------+--------------------------------+
1127 | cp500 | EBCDIC-CP-BE, EBCDIC-CP-CH, | Western Europe |
1128 | | IBM500 | |
1129 +-----------------+--------------------------------+--------------------------------+
1130 | cp720 | | Arabic |
1131 +-----------------+--------------------------------+--------------------------------+
1132 | cp737 | | Greek |
1133 +-----------------+--------------------------------+--------------------------------+
1134 | cp775 | IBM775 | Baltic languages |
1135 +-----------------+--------------------------------+--------------------------------+
1136 | cp850 | 850, IBM850 | Western Europe |
1137 +-----------------+--------------------------------+--------------------------------+
1138 | cp852 | 852, IBM852 | Central and Eastern Europe |
1139 +-----------------+--------------------------------+--------------------------------+
1140 | cp855 | 855, IBM855 | Belarusian, Bulgarian, |
1141 | | | Macedonian, Russian, Serbian |
1142 +-----------------+--------------------------------+--------------------------------+
1143 | cp856 | | Hebrew |
1144 +-----------------+--------------------------------+--------------------------------+
1145 | cp857 | 857, IBM857 | Turkish |
1146 +-----------------+--------------------------------+--------------------------------+
1147 | cp858 | 858, IBM00858 | Western Europe |
1148 +-----------------+--------------------------------+--------------------------------+
1149 | cp860 | 860, IBM860 | Portuguese |
1150 +-----------------+--------------------------------+--------------------------------+
1151 | cp861 | 861, CP-IS, IBM861 | Icelandic |
1152 +-----------------+--------------------------------+--------------------------------+
1153 | cp862 | 862, IBM862 | Hebrew |
1154 +-----------------+--------------------------------+--------------------------------+
1155 | cp863 | 863, IBM863 | Canadian |
1156 +-----------------+--------------------------------+--------------------------------+
1157 | cp864 | IBM864 | Arabic |
1158 +-----------------+--------------------------------+--------------------------------+
1159 | cp865 | 865, IBM865 | Danish, Norwegian |
1160 +-----------------+--------------------------------+--------------------------------+
1161 | cp866 | 866, IBM866 | Russian |
1162 +-----------------+--------------------------------+--------------------------------+
1163 | cp869 | 869, CP-GR, IBM869 | Greek |
1164 +-----------------+--------------------------------+--------------------------------+
1165 | cp874 | | Thai |
1166 +-----------------+--------------------------------+--------------------------------+
1167 | cp875 | | Greek |
1168 +-----------------+--------------------------------+--------------------------------+
1169 | cp932 | 932, ms932, mskanji, ms-kanji, | Japanese |
1170 | | windows-31j | |
1171 +-----------------+--------------------------------+--------------------------------+
1172 | cp949 | 949, ms949, uhc | Korean |
1173 +-----------------+--------------------------------+--------------------------------+
1174 | cp950 | 950, ms950 | Traditional Chinese |
1175 +-----------------+--------------------------------+--------------------------------+
1176 | cp1006 | | Urdu |
1177 +-----------------+--------------------------------+--------------------------------+
1178 | cp1026 | ibm1026 | Turkish |
1179 +-----------------+--------------------------------+--------------------------------+
1180 | cp1125 | 1125, ibm1125, cp866u, ruscii | Ukrainian |
1181 | | | |
1182 | | | .. versionadded:: 3.4 |
1183 +-----------------+--------------------------------+--------------------------------+
1184 | cp1140 | IBM01140 | Western Europe |
1185 +-----------------+--------------------------------+--------------------------------+
1186 | cp1250 | windows-1250 | Central and Eastern Europe |
1187 +-----------------+--------------------------------+--------------------------------+
1188 | cp1251 | windows-1251 | Belarusian, Bulgarian, |
1189 | | | Macedonian, Russian, Serbian |
1190 +-----------------+--------------------------------+--------------------------------+
1191 | cp1252 | windows-1252 | Western Europe |
1192 +-----------------+--------------------------------+--------------------------------+
1193 | cp1253 | windows-1253 | Greek |
1194 +-----------------+--------------------------------+--------------------------------+
1195 | cp1254 | windows-1254 | Turkish |
1196 +-----------------+--------------------------------+--------------------------------+
1197 | cp1255 | windows-1255 | Hebrew |
1198 +-----------------+--------------------------------+--------------------------------+
1199 | cp1256 | windows-1256 | Arabic |
1200 +-----------------+--------------------------------+--------------------------------+
1201 | cp1257 | windows-1257 | Baltic languages |
1202 +-----------------+--------------------------------+--------------------------------+
1203 | cp1258 | windows-1258 | Vietnamese |
1204 +-----------------+--------------------------------+--------------------------------+
1205 | euc_jp | eucjp, ujis, u-jis | Japanese |
1206 +-----------------+--------------------------------+--------------------------------+
1207 | euc_jis_2004 | jisx0213, eucjis2004 | Japanese |
1208 +-----------------+--------------------------------+--------------------------------+
1209 | euc_jisx0213 | eucjisx0213 | Japanese |
1210 +-----------------+--------------------------------+--------------------------------+
1211 | euc_kr | euckr, korean, ksc5601, | Korean |
1212 | | ks_c-5601, ks_c-5601-1987, | |
1213 | | ksx1001, ks_x-1001 | |
1214 +-----------------+--------------------------------+--------------------------------+
1215 | gb2312 | chinese, csiso58gb231280, | Simplified Chinese |
1216 | | euc-cn, euccn, eucgb2312-cn, | |
1217 | | gb2312-1980, gb2312-80, | |
1218 | | iso-ir-58 | |
1219 +-----------------+--------------------------------+--------------------------------+
1220 | gbk | 936, cp936, ms936 | Unified Chinese |
1221 +-----------------+--------------------------------+--------------------------------+
1222 | gb18030 | gb18030-2000 | Unified Chinese |
1223 +-----------------+--------------------------------+--------------------------------+
1224 | hz | hzgb, hz-gb, hz-gb-2312 | Simplified Chinese |
1225 +-----------------+--------------------------------+--------------------------------+
1226 | iso2022_jp | csiso2022jp, iso2022jp, | Japanese |
1227 | | iso-2022-jp | |
1228 +-----------------+--------------------------------+--------------------------------+
1229 | iso2022_jp_1 | iso2022jp-1, iso-2022-jp-1 | Japanese |
1230 +-----------------+--------------------------------+--------------------------------+
1231 | iso2022_jp_2 | iso2022jp-2, iso-2022-jp-2 | Japanese, Korean, Simplified |
1232 | | | Chinese, Western Europe, Greek |
1233 +-----------------+--------------------------------+--------------------------------+
1234 | iso2022_jp_2004 | iso2022jp-2004, | Japanese |
1235 | | iso-2022-jp-2004 | |
1236 +-----------------+--------------------------------+--------------------------------+
1237 | iso2022_jp_3 | iso2022jp-3, iso-2022-jp-3 | Japanese |
1238 +-----------------+--------------------------------+--------------------------------+
1239 | iso2022_jp_ext | iso2022jp-ext, iso-2022-jp-ext | Japanese |
1240 +-----------------+--------------------------------+--------------------------------+
1241 | iso2022_kr | csiso2022kr, iso2022kr, | Korean |
1242 | | iso-2022-kr | |
1243 +-----------------+--------------------------------+--------------------------------+
1244 | latin_1 | iso-8859-1, iso8859-1, 8859, | Western Europe |
1245 | | cp819, latin, latin1, L1 | |
1246 +-----------------+--------------------------------+--------------------------------+
1247 | iso8859_2 | iso-8859-2, latin2, L2 | Central and Eastern Europe |
1248 +-----------------+--------------------------------+--------------------------------+
1249 | iso8859_3 | iso-8859-3, latin3, L3 | Esperanto, Maltese |
1250 +-----------------+--------------------------------+--------------------------------+
1251 | iso8859_4 | iso-8859-4, latin4, L4 | Northern Europe |
1252 +-----------------+--------------------------------+--------------------------------+
1253 | iso8859_5 | iso-8859-5, cyrillic | Belarusian, Bulgarian, |
1254 | | | Macedonian, Russian, Serbian |
1255 +-----------------+--------------------------------+--------------------------------+
1256 | iso8859_6 | iso-8859-6, arabic | Arabic |
1257 +-----------------+--------------------------------+--------------------------------+
1258 | iso8859_7 | iso-8859-7, greek, greek8 | Greek |
1259 +-----------------+--------------------------------+--------------------------------+
1260 | iso8859_8 | iso-8859-8, hebrew | Hebrew |
1261 +-----------------+--------------------------------+--------------------------------+
1262 | iso8859_9 | iso-8859-9, latin5, L5 | Turkish |
1263 +-----------------+--------------------------------+--------------------------------+
1264 | iso8859_10 | iso-8859-10, latin6, L6 | Nordic languages |
1265 +-----------------+--------------------------------+--------------------------------+
1266 | iso8859_11 | iso-8859-11, thai | Thai languages |
1267 +-----------------+--------------------------------+--------------------------------+
1268 | iso8859_13 | iso-8859-13, latin7, L7 | Baltic languages |
1269 +-----------------+--------------------------------+--------------------------------+
1270 | iso8859_14 | iso-8859-14, latin8, L8 | Celtic languages |
1271 +-----------------+--------------------------------+--------------------------------+
1272 | iso8859_15 | iso-8859-15, latin9, L9 | Western Europe |
1273 +-----------------+--------------------------------+--------------------------------+
1274 | iso8859_16 | iso-8859-16, latin10, L10 | South-Eastern Europe |
1275 +-----------------+--------------------------------+--------------------------------+
1276 | johab | cp1361, ms1361 | Korean |
1277 +-----------------+--------------------------------+--------------------------------+
1278 | koi8_r | | Russian |
1279 +-----------------+--------------------------------+--------------------------------+
1280 | koi8_t | | Tajik |
1281 | | | |
1282 | | | .. versionadded:: 3.5 |
1283 +-----------------+--------------------------------+--------------------------------+
1284 | koi8_u | | Ukrainian |
1285 +-----------------+--------------------------------+--------------------------------+
1286 | kz1048 | kz_1048, strk1048_2002, rk1048 | Kazakh |
1287 | | | |
1288 | | | .. versionadded:: 3.5 |
1289 +-----------------+--------------------------------+--------------------------------+
1290 | mac_cyrillic | maccyrillic | Belarusian, Bulgarian, |
1291 | | | Macedonian, Russian, Serbian |
1292 +-----------------+--------------------------------+--------------------------------+
1293 | mac_greek | macgreek | Greek |
1294 +-----------------+--------------------------------+--------------------------------+
1295 | mac_iceland | maciceland | Icelandic |
1296 +-----------------+--------------------------------+--------------------------------+
1297 | mac_latin2 | maclatin2, maccentraleurope, | Central and Eastern Europe |
1298 | | mac_centeuro | |
1299 +-----------------+--------------------------------+--------------------------------+
1300 | mac_roman | macroman, macintosh | Western Europe |
1301 +-----------------+--------------------------------+--------------------------------+
1302 | mac_turkish | macturkish | Turkish |
1303 +-----------------+--------------------------------+--------------------------------+
1304 | ptcp154 | csptcp154, pt154, cp154, | Kazakh |
1305 | | cyrillic-asian | |
1306 +-----------------+--------------------------------+--------------------------------+
1307 | shift_jis | csshiftjis, shiftjis, sjis, | Japanese |
1308 | | s_jis | |
1309 +-----------------+--------------------------------+--------------------------------+
1310 | shift_jis_2004 | shiftjis2004, sjis_2004, | Japanese |
1311 | | sjis2004 | |
1312 +-----------------+--------------------------------+--------------------------------+
1313 | shift_jisx0213 | shiftjisx0213, sjisx0213, | Japanese |
1314 | | s_jisx0213 | |
1315 +-----------------+--------------------------------+--------------------------------+
1316 | utf_32 | U32, utf32 | all languages |
1317 +-----------------+--------------------------------+--------------------------------+
1318 | utf_32_be | UTF-32BE | all languages |
1319 +-----------------+--------------------------------+--------------------------------+
1320 | utf_32_le | UTF-32LE | all languages |
1321 +-----------------+--------------------------------+--------------------------------+
1322 | utf_16 | U16, utf16 | all languages |
1323 +-----------------+--------------------------------+--------------------------------+
1324 | utf_16_be | UTF-16BE | all languages |
1325 +-----------------+--------------------------------+--------------------------------+
1326 | utf_16_le | UTF-16LE | all languages |
1327 +-----------------+--------------------------------+--------------------------------+
1328 | utf_7 | U7, unicode-1-1-utf-7 | all languages |
1329 +-----------------+--------------------------------+--------------------------------+
1330 | utf_8 | U8, UTF, utf8, cp65001 | all languages |
1331 +-----------------+--------------------------------+--------------------------------+
1332 | utf_8_sig | | all languages |
1333 +-----------------+--------------------------------+--------------------------------+
1334
1335 .. versionchanged:: 3.4
1336 The utf-16\* and utf-32\* encoders no longer allow surrogate code points
1337 (``U+D800``--``U+DFFF``) to be encoded.
1338 The utf-32\* decoders no longer decode
1339 byte sequences that correspond to surrogate code points.
1340
1341 .. versionchanged:: 3.8
1342 ``cp65001`` is now an alias to ``utf_8``.
1343
1344
1345 Python Specific Encodings
1346 -------------------------
1347
1348 A number of predefined codecs are specific to Python, so their codec names have
1349 no meaning outside Python. These are listed in the tables below based on the
1350 expected input and output types (note that while text encodings are the most
1351 common use case for codecs, the underlying codec infrastructure supports
1352 arbitrary data transforms rather than just text encodings). For asymmetric
1353 codecs, the stated meaning describes the encoding direction.
1354
1355 Text Encodings
1356 ^^^^^^^^^^^^^^
1357
1358 The following codecs provide :class:`str` to :class:`bytes` encoding and
1359 :term:`bytes-like object` to :class:`str` decoding, similar to the Unicode text
1360 encodings.
1361
1362 .. tabularcolumns:: |l|p{0.3\linewidth}|p{0.3\linewidth}|
1363
1364 +--------------------+---------+---------------------------+
1365 | Codec | Aliases | Meaning |
1366 +====================+=========+===========================+
1367 | idna | | Implement :rfc:`3490`, |
1368 | | | see also |
1369 | | | :mod:`encodings.idna`. |
1370 | | | Only ``errors='strict'`` |
1371 | | | is supported. |
1372 +--------------------+---------+---------------------------+
1373 | mbcs | ansi, | Windows only: Encode the |
1374 | | dbcs | operand according to the |
1375 | | | ANSI codepage (CP_ACP). |
1376 +--------------------+---------+---------------------------+
1377 | oem | | Windows only: Encode the |
1378 | | | operand according to the |
1379 | | | OEM codepage (CP_OEMCP). |
1380 | | | |
1381 | | | .. versionadded:: 3.6 |
1382 +--------------------+---------+---------------------------+
1383 | palmos | | Encoding of PalmOS 3.5. |
1384 +--------------------+---------+---------------------------+
1385 | punycode | | Implement :rfc:`3492`. |
1386 | | | Stateful codecs are not |
1387 | | | supported. |
1388 | | | |
1389 | | | .. warning:: |
1390 | | | |
1391 | | | The decoding and |
1392 | | | encoding algorithms |
1393 | | | scale poorly, so |
1394 | | | limit the length of |
1395 | | | untrusted input. |
1396 +--------------------+---------+---------------------------+
1397 | raw_unicode_escape | | Latin-1 encoding with |
1398 | | | :samp:`\\u{XXXX}` and |
1399 | | | :samp:`\\U{XXXXXXXX}` |
1400 | | | for other code points. |
1401 | | | Existing |
1402 | | | backslashes are not |
1403 | | | escaped in any way. |
1404 | | | It is used in the Python |
1405 | | | pickle protocol. |
1406 +--------------------+---------+---------------------------+
1407 | undefined | | This Codec should only |
1408 | | | be used for testing |
1409 | | | purposes. |
1410 | | | |
1411 | | | Raise an exception for |
1412 | | | all conversions, even |
1413 | | | empty strings. The error |
1414 | | | handler is ignored. |
1415 +--------------------+---------+---------------------------+
1416 | unicode_escape | | Encoding suitable as the |
1417 | | | contents of a Unicode |
1418 | | | literal in ASCII-encoded |
1419 | | | Python source code, |
1420 | | | except that quotes are |
1421 | | | not escaped. Decode |
1422 | | | from Latin-1 source code. |
1423 | | | Beware that Python source |
1424 | | | code actually uses UTF-8 |
1425 | | | by default. |
1426 +--------------------+---------+---------------------------+
1427
1428 .. versionchanged:: 3.8
1429 "unicode_internal" codec is removed.
1430
1431
1432 .. _binary-transforms:
1433
1434 Binary Transforms
1435 ^^^^^^^^^^^^^^^^^
1436
1437 The following codecs provide binary transforms: :term:`bytes-like object`
1438 to :class:`bytes` mappings. They are not supported by :meth:`bytes.decode`
1439 (which only produces :class:`str` output).
1440
1441
1442 .. tabularcolumns:: |l|L|L|L|
1443
1444 +----------------------+------------------+------------------------------+------------------------------+
1445 | Codec | Aliases | Meaning | Encoder / decoder |
1446 +======================+==================+==============================+==============================+
1447 | base64_codec [#b64]_ | base64, base_64 | Convert the operand to | :meth:`base64.encodebytes` / |
1448 | | | multiline MIME base64 (the | :meth:`base64.decodebytes` |
1449 | | | result always includes a | |
1450 | | | trailing ``'\n'``). | |
1451 | | | | |
1452 | | | .. versionchanged:: 3.4 | |
1453 | | | accepts any | |
1454 | | | :term:`bytes-like object` | |
1455 | | | as input for encoding and | |
1456 | | | decoding | |
1457 +----------------------+------------------+------------------------------+------------------------------+
1458 | bz2_codec | bz2 | Compress the operand using | :meth:`bz2.compress` / |
1459 | | | bz2. | :meth:`bz2.decompress` |
1460 +----------------------+------------------+------------------------------+------------------------------+
1461 | hex_codec | hex | Convert the operand to | :meth:`binascii.b2a_hex` / |
1462 | | | hexadecimal | :meth:`binascii.a2b_hex` |
1463 | | | representation, with two | |
1464 | | | digits per byte. | |
1465 +----------------------+------------------+------------------------------+------------------------------+
1466 | quopri_codec | quopri, | Convert the operand to MIME | :meth:`quopri.encode` with |
1467 | | quotedprintable, | quoted printable. | ``quotetabs=True`` / |
1468 | | quoted_printable | | :meth:`quopri.decode` |
1469 +----------------------+------------------+------------------------------+------------------------------+
1470 | uu_codec | uu | Convert the operand using | |
1471 | | | uuencode. | |
1472 +----------------------+------------------+------------------------------+------------------------------+
1473 | zlib_codec | zip, zlib | Compress the operand using | :meth:`zlib.compress` / |
1474 | | | gzip. | :meth:`zlib.decompress` |
1475 +----------------------+------------------+------------------------------+------------------------------+
1476
1477 .. [#b64] In addition to :term:`bytes-like objects <bytes-like object>`,
1478 ``'base64_codec'`` also accepts ASCII-only instances of :class:`str` for
1479 decoding
1480
1481 .. versionadded:: 3.2
1482 Restoration of the binary transforms.
1483
1484 .. versionchanged:: 3.4
1485 Restoration of the aliases for the binary transforms.
1486
1487
1488 .. _standalone-codec-functions:
1489
1490 Standalone Codec Functions
1491 ^^^^^^^^^^^^^^^^^^^^^^^^^^
1492
1493 The following functions provide encoding and decoding functionality similar to codecs,
1494 but are not available as named codecs through :func:`codecs.encode` or :func:`codecs.decode`.
1495 They are used internally (for example, by :mod:`pickle`) and behave similarly to the
1496 ``string_escape`` codec that was removed in Python 3.
1497
1498 .. function:: codecs.escape_encode(input, errors=None)
1499
1500 Encode *input* using escape sequences. Similar to how :func:`repr` on bytes
1501 produces escaped byte values.
1502
1503 *input* must be a :class:`bytes` object.
1504
1505 Returns a tuple ``(output, length)`` where *output* is a :class:`bytes`
1506 object and *length* is the number of bytes consumed.
1507
1508 .. function:: codecs.escape_decode(input, errors=None)
1509
1510 Decode *input* from escape sequences back to the original bytes.
1511
1512 *input* must be a :term:`bytes-like object`.
1513
1514 Returns a tuple ``(output, length)`` where *output* is a :class:`bytes`
1515 object and *length* is the number of bytes consumed.
1516
1517
1518 .. _text-transforms:
1519
1520 Text Transforms
1521 ^^^^^^^^^^^^^^^
1522
1523 The following codec provides a text transform: a :class:`str` to :class:`str`
1524 mapping. It is not supported by :meth:`str.encode` (which only produces
1525 :class:`bytes` output).
1526
1527 .. tabularcolumns:: |l|l|L|
1528
1529 +--------------------+---------+---------------------------+
1530 | Codec | Aliases | Meaning |
1531 +====================+=========+===========================+
1532 | rot_13 | rot13 | Return the Caesar-cypher |
1533 | | | encryption of the |
1534 | | | operand. |
1535 +--------------------+---------+---------------------------+
1536
1537 .. versionadded:: 3.2
1538 Restoration of the ``rot_13`` text transform.
1539
1540 .. versionchanged:: 3.4
1541 Restoration of the ``rot13`` alias.
1542
1543
1544 :mod:`encodings` --- Encodings package
1545 --------------------------------------
1546
1547 .. module:: encodings
1548 :synopsis: Encodings package
1549
1550 This module implements the following functions:
1551
1552 .. function:: normalize_encoding(encoding)
1553
1554 Normalize encoding name *encoding*.
1555
1556 Normalization works as follows: all non-alphanumeric characters except the
1557 dot used for Python package names are collapsed and replaced with a single
1558 underscore, leading and trailing underscores are removed.
1559 For example, ``' -;#'`` becomes ``'_'``.
1560
1561 Note that *encoding* should be ASCII only.
1562
1563
1564 .. note::
1565 The following function should not be used directly, except for testing
1566 purposes; :func:`codecs.lookup` should be used instead.
1567
1568
1569 .. function:: search_function(encoding)
1570
1571 Search for the codec module corresponding to the given encoding name
1572 *encoding*.
1573
1574 This function first normalizes the *encoding* using
1575 :func:`normalize_encoding`, then looks for a corresponding alias.
1576 It attempts to import a codec module from the encodings package using either
1577 the alias or the normalized name. If the module is found and defines a valid
1578 ``getregentry()`` function that returns a :class:`codecs.CodecInfo` object,
1579 the codec is cached and returned.
1580
1581 If the codec module defines a ``getaliases()`` function any returned aliases
1582 are registered for future use.
1583
1584
1585 This module implements the following exception:
1586
1587 .. exception:: CodecRegistryError
1588
1589 Raised when a codec is invalid or incompatible.
1590
1591
1592 :mod:`encodings.idna` --- Internationalized Domain Names in Applications
1593 ------------------------------------------------------------------------
1594
1595 .. module:: encodings.idna
1596 :synopsis: Internationalized Domain Names implementation
1597 .. moduleauthor:: Martin v. Löwis
1598
1599 This module implements :rfc:`3490` (Internationalized Domain Names in
1600 Applications) and :rfc:`3492` (Nameprep: A Stringprep Profile for
1601 Internationalized Domain Names (IDN)). It builds upon the ``punycode`` encoding
1602 and :mod:`stringprep`.
1603
1604 If you need the IDNA 2008 standard from :rfc:`5891` and :rfc:`5895`, use the
1605 third-party :pypi:`idna` module.
1606
1607 These RFCs together define a protocol to support non-ASCII characters in domain
1608 names. A domain name containing non-ASCII characters (such as
1609 ``www.Alliancefrançaise.nu``) is converted into an ASCII-compatible encoding
1610 (ACE, such as ``www.xn--alliancefranaise-npb.nu``). The ACE form of the domain
1611 name is then used in all places where arbitrary characters are not allowed by
1612 the protocol, such as DNS queries, HTTP :mailheader:`Host` fields, and so
1613 on. This conversion is carried out in the application; if possible invisible to
1614 the user: The application should transparently convert Unicode domain labels to
1615 IDNA on the wire, and convert back ACE labels to Unicode before presenting them
1616 to the user.
1617
1618 Python supports this conversion in several ways: the ``idna`` codec performs
1619 conversion between Unicode and ACE, separating an input string into labels
1620 based on the separator characters defined in :rfc:`section 3.1 of RFC 3490 <3490#section-3.1>`
1621 and converting each label to ACE as required, and conversely separating an input
1622 byte string into labels based on the ``.`` separator and converting any ACE
1623 labels found into unicode. Furthermore, the :mod:`socket` module
1624 transparently converts Unicode host names to ACE, so that applications need not
1625 be concerned about converting host names themselves when they pass them to the
1626 socket module. On top of that, modules that have host names as function
1627 parameters, such as :mod:`http.client` and :mod:`ftplib`, accept Unicode host
1628 names (:mod:`http.client` then also transparently sends an IDNA hostname in the
1629 :mailheader:`Host` field if it sends that field at all).
1630
1631 When receiving host names from the wire (such as in reverse name lookup), no
1632 automatic conversion to Unicode is performed: applications wishing to present
1633 such host names to the user should decode them to Unicode.
1634
1635 The module :mod:`encodings.idna` also implements the nameprep procedure, which
1636 performs certain normalizations on host names, to achieve case-insensitivity of
1637 international domain names, and to unify similar characters. The nameprep
1638 functions can be used directly if desired.
1639
1640
1641 .. function:: nameprep(label)
1642
1643 Return the nameprepped version of *label*. The implementation currently assumes
1644 query strings, so ``AllowUnassigned`` is true.
1645
1646
1647 .. function:: ToASCII(label)
1648
1649 Convert a label to ASCII, as specified in :rfc:`3490`. ``UseSTD3ASCIIRules`` is
1650 assumed to be false.
1651
1652
1653 .. function:: ToUnicode(label)
1654
1655 Convert a label to Unicode, as specified in :rfc:`3490`.
1656
1657
1658 :mod:`encodings.mbcs` --- Windows ANSI codepage
1659 -----------------------------------------------
1660
1661 .. module:: encodings.mbcs
1662 :synopsis: Windows ANSI codepage
1663
1664 This module implements the ANSI codepage (CP_ACP).
1665
1666 .. availability:: Windows.
1667
1668 .. versionchanged:: 3.2
1669 Before 3.2, the *errors* argument was ignored; ``'replace'`` was always used
1670 to encode, and ``'ignore'`` to decode.
1671
1672 .. versionchanged:: 3.3
1673 Support any error handler.
1674
1675
1676 :mod:`encodings.utf_8_sig` --- UTF-8 codec with BOM signature
1677 -------------------------------------------------------------
1678
1679 .. module:: encodings.utf_8_sig
1680 :synopsis: UTF-8 codec with BOM signature
1681 .. moduleauthor:: Walter Dörwald
1682
1683 This module implements a variant of the UTF-8 codec. On encoding, a UTF-8 encoded
1684 BOM will be prepended to the UTF-8 encoded bytes. For the stateful encoder this
1685 is only done once (on the first write to the byte stream). On decoding, an
1686 optional UTF-8 encoded BOM at the start of the data will be skipped.