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