PageRenderTime 263ms CodeModel.GetById 17ms RepoModel.GetById 1ms app.codeStats 1ms

/Doc/library/codecs.rst

http://unladen-swallow.googlecode.com/
ReStructuredText | 1236 lines | 907 code | 329 blank | 0 comment | 0 complexity | 9d43bcdc6335b5fe3331167d630ca395 MD5 | raw file
Possible License(s): 0BSD, BSD-3-Clause
  1. :mod:`codecs` --- Codec registry and base classes
  2. =================================================
  3. .. module:: codecs
  4. :synopsis: Encode and decode data and streams.
  5. .. moduleauthor:: Marc-Andre Lemburg <mal@lemburg.com>
  6. .. sectionauthor:: Marc-Andre Lemburg <mal@lemburg.com>
  7. .. sectionauthor:: Martin v. Lรถwis <martin@v.loewis.de>
  8. .. index::
  9. single: Unicode
  10. single: Codecs
  11. pair: Codecs; encode
  12. pair: Codecs; decode
  13. single: streams
  14. pair: stackable; streams
  15. This module defines base classes for standard Python codecs (encoders and
  16. decoders) and provides access to the internal Python codec registry which
  17. manages the codec and error handling lookup process.
  18. It defines the following functions:
  19. .. function:: register(search_function)
  20. Register a codec search function. Search functions are expected to take one
  21. argument, the encoding name in all lower case letters, and return a
  22. :class:`CodecInfo` object having the following attributes:
  23. * ``name`` The name of the encoding;
  24. * ``encode`` The stateless encoding function;
  25. * ``decode`` The stateless decoding function;
  26. * ``incrementalencoder`` An incremental encoder class or factory function;
  27. * ``incrementaldecoder`` An incremental decoder class or factory function;
  28. * ``streamwriter`` A stream writer class or factory function;
  29. * ``streamreader`` A stream reader class or factory function.
  30. The various functions or classes take the following arguments:
  31. *encode* and *decode*: These must be functions or methods which have the same
  32. interface as the :meth:`encode`/:meth:`decode` methods of Codec instances (see
  33. Codec Interface). The functions/methods are expected to work in a stateless
  34. mode.
  35. *incrementalencoder* and *incrementaldecoder*: These have to be factory
  36. functions providing the following interface:
  37. ``factory(errors='strict')``
  38. The factory functions must return objects providing the interfaces defined by
  39. the base classes :class:`IncrementalEncoder` and :class:`IncrementalDecoder`,
  40. respectively. Incremental codecs can maintain state.
  41. *streamreader* and *streamwriter*: These have to be factory functions providing
  42. the following interface:
  43. ``factory(stream, errors='strict')``
  44. The factory functions must return objects providing the interfaces defined by
  45. the base classes :class:`StreamWriter` and :class:`StreamReader`, respectively.
  46. Stream codecs can maintain state.
  47. Possible values for errors are ``'strict'`` (raise an exception in case of an
  48. encoding error), ``'replace'`` (replace malformed data with a suitable
  49. replacement marker, such as ``'?'``), ``'ignore'`` (ignore malformed data and
  50. continue without further notice), ``'xmlcharrefreplace'`` (replace with the
  51. appropriate XML character reference (for encoding only)) and
  52. ``'backslashreplace'`` (replace with backslashed escape sequences (for encoding
  53. only)) as well as any other error handling name defined via
  54. :func:`register_error`.
  55. In case a search function cannot find a given encoding, it should return
  56. ``None``.
  57. .. function:: lookup(encoding)
  58. Looks up the codec info in the Python codec registry and returns a
  59. :class:`CodecInfo` object as defined above.
  60. Encodings are first looked up in the registry's cache. If not found, the list of
  61. registered search functions is scanned. If no :class:`CodecInfo` object is
  62. found, a :exc:`LookupError` is raised. Otherwise, the :class:`CodecInfo` object
  63. is stored in the cache and returned to the caller.
  64. To simplify access to the various codecs, the module provides these additional
  65. functions which use :func:`lookup` for the codec lookup:
  66. .. function:: getencoder(encoding)
  67. Look up the codec for the given encoding and return its encoder function.
  68. Raises a :exc:`LookupError` in case the encoding cannot be found.
  69. .. function:: getdecoder(encoding)
  70. Look up the codec for the given encoding and return its decoder function.
  71. Raises a :exc:`LookupError` in case the encoding cannot be found.
  72. .. function:: getincrementalencoder(encoding)
  73. Look up the codec for the given encoding and return its incremental encoder
  74. class or factory function.
  75. Raises a :exc:`LookupError` in case the encoding cannot be found or the codec
  76. doesn't support an incremental encoder.
  77. .. versionadded:: 2.5
  78. .. function:: getincrementaldecoder(encoding)
  79. Look up the codec for the given encoding and return its incremental decoder
  80. class or factory function.
  81. Raises a :exc:`LookupError` in case the encoding cannot be found or the codec
  82. doesn't support an incremental decoder.
  83. .. versionadded:: 2.5
  84. .. function:: getreader(encoding)
  85. Look up the codec for the given encoding and return its StreamReader class or
  86. factory function.
  87. Raises a :exc:`LookupError` in case the encoding cannot be found.
  88. .. function:: getwriter(encoding)
  89. Look up the codec for the given encoding and return its StreamWriter class or
  90. factory function.
  91. Raises a :exc:`LookupError` in case the encoding cannot be found.
  92. .. function:: register_error(name, error_handler)
  93. Register the error handling function *error_handler* under the name *name*.
  94. *error_handler* will be called during encoding and decoding in case of an error,
  95. when *name* is specified as the errors parameter.
  96. For encoding *error_handler* will be called with a :exc:`UnicodeEncodeError`
  97. instance, which contains information about the location of the error. The error
  98. handler must either raise this or a different exception or return a tuple with a
  99. replacement for the unencodable part of the input and a position where encoding
  100. should continue. The encoder will encode the replacement and continue encoding
  101. the original input at the specified position. Negative position values will be
  102. treated as being relative to the end of the input string. If the resulting
  103. position is out of bound an :exc:`IndexError` will be raised.
  104. Decoding and translating works similar, except :exc:`UnicodeDecodeError` or
  105. :exc:`UnicodeTranslateError` will be passed to the handler and that the
  106. replacement from the error handler will be put into the output directly.
  107. .. function:: lookup_error(name)
  108. Return the error handler previously registered under the name *name*.
  109. Raises a :exc:`LookupError` in case the handler cannot be found.
  110. .. function:: strict_errors(exception)
  111. Implements the ``strict`` error handling.
  112. .. function:: replace_errors(exception)
  113. Implements the ``replace`` error handling.
  114. .. function:: ignore_errors(exception)
  115. Implements the ``ignore`` error handling.
  116. .. function:: xmlcharrefreplace_errors(exception)
  117. Implements the ``xmlcharrefreplace`` error handling.
  118. .. function:: backslashreplace_errors(exception)
  119. Implements the ``backslashreplace`` error handling.
  120. To simplify working with encoded files or stream, the module also defines these
  121. utility functions:
  122. .. function:: open(filename, mode[, encoding[, errors[, buffering]]])
  123. Open an encoded file using the given *mode* and return a wrapped version
  124. providing transparent encoding/decoding. The default file mode is ``'r'``
  125. meaning to open the file in read mode.
  126. .. note::
  127. The wrapped version will only accept the object format defined by the codecs,
  128. i.e. Unicode objects for most built-in codecs. Output is also codec-dependent
  129. and will usually be Unicode as well.
  130. .. note::
  131. Files are always opened in binary mode, even if no binary mode was
  132. specified. This is done to avoid data loss due to encodings using 8-bit
  133. values. This means that no automatic conversion of ``'\n'`` is done
  134. on reading and writing.
  135. *encoding* specifies the encoding which is to be used for the file.
  136. *errors* may be given to define the error handling. It defaults to ``'strict'``
  137. which causes a :exc:`ValueError` to be raised in case an encoding error occurs.
  138. *buffering* has the same meaning as for the built-in :func:`open` function. It
  139. defaults to line buffered.
  140. .. function:: EncodedFile(file, input[, output[, errors]])
  141. Return a wrapped version of file which provides transparent encoding
  142. translation.
  143. Strings written to the wrapped file are interpreted according to the given
  144. *input* encoding and then written to the original file as strings using the
  145. *output* encoding. The intermediate encoding will usually be Unicode but depends
  146. on the specified codecs.
  147. If *output* is not given, it defaults to *input*.
  148. *errors* may be given to define the error handling. It defaults to ``'strict'``,
  149. which causes :exc:`ValueError` to be raised in case an encoding error occurs.
  150. .. function:: iterencode(iterable, encoding[, errors])
  151. Uses an incremental encoder to iteratively encode the input provided by
  152. *iterable*. This function is a :term:`generator`. *errors* (as well as any
  153. other keyword argument) is passed through to the incremental encoder.
  154. .. versionadded:: 2.5
  155. .. function:: iterdecode(iterable, encoding[, errors])
  156. Uses an incremental decoder to iteratively decode the input provided by
  157. *iterable*. This function is a :term:`generator`. *errors* (as well as any
  158. other keyword argument) is passed through to the incremental decoder.
  159. .. versionadded:: 2.5
  160. The module also provides the following constants which are useful for reading
  161. and writing to platform dependent files:
  162. .. data:: BOM
  163. BOM_BE
  164. BOM_LE
  165. BOM_UTF8
  166. BOM_UTF16
  167. BOM_UTF16_BE
  168. BOM_UTF16_LE
  169. BOM_UTF32
  170. BOM_UTF32_BE
  171. BOM_UTF32_LE
  172. These constants define various encodings of the Unicode byte order mark (BOM)
  173. used in UTF-16 and UTF-32 data streams to indicate the byte order used in the
  174. stream or file and in UTF-8 as a Unicode signature. :const:`BOM_UTF16` is either
  175. :const:`BOM_UTF16_BE` or :const:`BOM_UTF16_LE` depending on the platform's
  176. native byte order, :const:`BOM` is an alias for :const:`BOM_UTF16`,
  177. :const:`BOM_LE` for :const:`BOM_UTF16_LE` and :const:`BOM_BE` for
  178. :const:`BOM_UTF16_BE`. The others represent the BOM in UTF-8 and UTF-32
  179. encodings.
  180. .. _codec-base-classes:
  181. Codec Base Classes
  182. ------------------
  183. The :mod:`codecs` module defines a set of base classes which define the
  184. interface and can also be used to easily write your own codecs for use in
  185. Python.
  186. Each codec has to define four interfaces to make it usable as codec in Python:
  187. stateless encoder, stateless decoder, stream reader and stream writer. The
  188. stream reader and writers typically reuse the stateless encoder/decoder to
  189. implement the file protocols.
  190. The :class:`Codec` class defines the interface for stateless encoders/decoders.
  191. To simplify and standardize error handling, the :meth:`encode` and
  192. :meth:`decode` methods may implement different error handling schemes by
  193. providing the *errors* string argument. The following string values are defined
  194. and implemented by all standard Python codecs:
  195. +-------------------------+-----------------------------------------------+
  196. | Value | Meaning |
  197. +=========================+===============================================+
  198. | ``'strict'`` | Raise :exc:`UnicodeError` (or a subclass); |
  199. | | this is the default. |
  200. +-------------------------+-----------------------------------------------+
  201. | ``'ignore'`` | Ignore the character and continue with the |
  202. | | next. |
  203. +-------------------------+-----------------------------------------------+
  204. | ``'replace'`` | Replace with a suitable replacement |
  205. | | character; Python will use the official |
  206. | | U+FFFD REPLACEMENT CHARACTER for the built-in |
  207. | | Unicode codecs on decoding and '?' on |
  208. | | encoding. |
  209. +-------------------------+-----------------------------------------------+
  210. | ``'xmlcharrefreplace'`` | Replace with the appropriate XML character |
  211. | | reference (only for encoding). |
  212. +-------------------------+-----------------------------------------------+
  213. | ``'backslashreplace'`` | Replace with backslashed escape sequences |
  214. | | (only for encoding). |
  215. +-------------------------+-----------------------------------------------+
  216. The set of allowed values can be extended via :meth:`register_error`.
  217. .. _codec-objects:
  218. Codec Objects
  219. ^^^^^^^^^^^^^
  220. The :class:`Codec` class defines these methods which also define the function
  221. interfaces of the stateless encoder and decoder:
  222. .. method:: Codec.encode(input[, errors])
  223. Encodes the object *input* and returns a tuple (output object, length consumed).
  224. While codecs are not restricted to use with Unicode, in a Unicode context,
  225. encoding converts a Unicode object to a plain string using a particular
  226. character set encoding (e.g., ``cp1252`` or ``iso-8859-1``).
  227. *errors* defines the error handling to apply. It defaults to ``'strict'``
  228. handling.
  229. The method may not store state in the :class:`Codec` instance. Use
  230. :class:`StreamCodec` for codecs which have to keep state in order to make
  231. encoding/decoding efficient.
  232. The encoder must be able to handle zero length input and return an empty object
  233. of the output object type in this situation.
  234. .. method:: Codec.decode(input[, errors])
  235. Decodes the object *input* and returns a tuple (output object, length consumed).
  236. In a Unicode context, decoding converts a plain string encoded using a
  237. particular character set encoding to a Unicode object.
  238. *input* must be an object which provides the ``bf_getreadbuf`` buffer slot.
  239. Python strings, buffer objects and memory mapped files are examples of objects
  240. providing this slot.
  241. *errors* defines the error handling to apply. It defaults to ``'strict'``
  242. handling.
  243. The method may not store state in the :class:`Codec` instance. Use
  244. :class:`StreamCodec` for codecs which have to keep state in order to make
  245. encoding/decoding efficient.
  246. The decoder must be able to handle zero length input and return an empty object
  247. of the output object type in this situation.
  248. The :class:`IncrementalEncoder` and :class:`IncrementalDecoder` classes provide
  249. the basic interface for incremental encoding and decoding. Encoding/decoding the
  250. input isn't done with one call to the stateless encoder/decoder function, but
  251. with multiple calls to the :meth:`encode`/:meth:`decode` method of the
  252. incremental encoder/decoder. The incremental encoder/decoder keeps track of the
  253. encoding/decoding process during method calls.
  254. The joined output of calls to the :meth:`encode`/:meth:`decode` method is the
  255. same as if all the single inputs were joined into one, and this input was
  256. encoded/decoded with the stateless encoder/decoder.
  257. .. _incremental-encoder-objects:
  258. IncrementalEncoder Objects
  259. ^^^^^^^^^^^^^^^^^^^^^^^^^^
  260. .. versionadded:: 2.5
  261. The :class:`IncrementalEncoder` class is used for encoding an input in multiple
  262. steps. It defines the following methods which every incremental encoder must
  263. define in order to be compatible with the Python codec registry.
  264. .. class:: IncrementalEncoder([errors])
  265. Constructor for an :class:`IncrementalEncoder` instance.
  266. All incremental encoders must provide this constructor interface. They are free
  267. to add additional keyword arguments, but only the ones defined here are used by
  268. the Python codec registry.
  269. The :class:`IncrementalEncoder` may implement different error handling schemes
  270. by providing the *errors* keyword argument. These parameters are predefined:
  271. * ``'strict'`` Raise :exc:`ValueError` (or a subclass); this is the default.
  272. * ``'ignore'`` Ignore the character and continue with the next.
  273. * ``'replace'`` Replace with a suitable replacement character
  274. * ``'xmlcharrefreplace'`` Replace with the appropriate XML character reference
  275. * ``'backslashreplace'`` Replace with backslashed escape sequences.
  276. The *errors* argument will be assigned to an attribute of the same name.
  277. Assigning to this attribute makes it possible to switch between different error
  278. handling strategies during the lifetime of the :class:`IncrementalEncoder`
  279. object.
  280. The set of allowed values for the *errors* argument can be extended with
  281. :func:`register_error`.
  282. .. method:: encode(object[, final])
  283. Encodes *object* (taking the current state of the encoder into account)
  284. and returns the resulting encoded object. If this is the last call to
  285. :meth:`encode` *final* must be true (the default is false).
  286. .. method:: reset()
  287. Reset the encoder to the initial state.
  288. .. _incremental-decoder-objects:
  289. IncrementalDecoder Objects
  290. ^^^^^^^^^^^^^^^^^^^^^^^^^^
  291. The :class:`IncrementalDecoder` class is used for decoding an input in multiple
  292. steps. It defines the following methods which every incremental decoder must
  293. define in order to be compatible with the Python codec registry.
  294. .. class:: IncrementalDecoder([errors])
  295. Constructor for an :class:`IncrementalDecoder` instance.
  296. All incremental decoders must provide this constructor interface. They are free
  297. to add additional keyword arguments, but only the ones defined here are used by
  298. the Python codec registry.
  299. The :class:`IncrementalDecoder` may implement different error handling schemes
  300. by providing the *errors* keyword argument. These parameters are predefined:
  301. * ``'strict'`` Raise :exc:`ValueError` (or a subclass); this is the default.
  302. * ``'ignore'`` Ignore the character and continue with the next.
  303. * ``'replace'`` Replace with a suitable replacement character.
  304. The *errors* argument will be assigned to an attribute of the same name.
  305. Assigning to this attribute makes it possible to switch between different error
  306. handling strategies during the lifetime of the :class:`IncrementalDecoder`
  307. object.
  308. The set of allowed values for the *errors* argument can be extended with
  309. :func:`register_error`.
  310. .. method:: decode(object[, final])
  311. Decodes *object* (taking the current state of the decoder into account)
  312. and returns the resulting decoded object. If this is the last call to
  313. :meth:`decode` *final* must be true (the default is false). If *final* is
  314. true the decoder must decode the input completely and must flush all
  315. buffers. If this isn't possible (e.g. because of incomplete byte sequences
  316. at the end of the input) it must initiate error handling just like in the
  317. stateless case (which might raise an exception).
  318. .. method:: reset()
  319. Reset the decoder to the initial state.
  320. The :class:`StreamWriter` and :class:`StreamReader` classes provide generic
  321. working interfaces which can be used to implement new encoding submodules very
  322. easily. See :mod:`encodings.utf_8` for an example of how this is done.
  323. .. _stream-writer-objects:
  324. StreamWriter Objects
  325. ^^^^^^^^^^^^^^^^^^^^
  326. The :class:`StreamWriter` class is a subclass of :class:`Codec` and defines the
  327. following methods which every stream writer must define in order to be
  328. compatible with the Python codec registry.
  329. .. class:: StreamWriter(stream[, errors])
  330. Constructor for a :class:`StreamWriter` instance.
  331. All stream writers must provide this constructor interface. They are free to add
  332. additional keyword arguments, but only the ones defined here are used by the
  333. Python codec registry.
  334. *stream* must be a file-like object open for writing binary data.
  335. The :class:`StreamWriter` may implement different error handling schemes by
  336. providing the *errors* keyword argument. These parameters are predefined:
  337. * ``'strict'`` Raise :exc:`ValueError` (or a subclass); this is the default.
  338. * ``'ignore'`` Ignore the character and continue with the next.
  339. * ``'replace'`` Replace with a suitable replacement character
  340. * ``'xmlcharrefreplace'`` Replace with the appropriate XML character reference
  341. * ``'backslashreplace'`` Replace with backslashed escape sequences.
  342. The *errors* argument will be assigned to an attribute of the same name.
  343. Assigning to this attribute makes it possible to switch between different error
  344. handling strategies during the lifetime of the :class:`StreamWriter` object.
  345. The set of allowed values for the *errors* argument can be extended with
  346. :func:`register_error`.
  347. .. method:: write(object)
  348. Writes the object's contents encoded to the stream.
  349. .. method:: writelines(list)
  350. Writes the concatenated list of strings to the stream (possibly by reusing
  351. the :meth:`write` method).
  352. .. method:: reset()
  353. Flushes and resets the codec buffers used for keeping state.
  354. Calling this method should ensure that the data on the output is put into
  355. a clean state that allows appending of new fresh data without having to
  356. rescan the whole stream to recover state.
  357. In addition to the above methods, the :class:`StreamWriter` must also inherit
  358. all other methods and attributes from the underlying stream.
  359. .. _stream-reader-objects:
  360. StreamReader Objects
  361. ^^^^^^^^^^^^^^^^^^^^
  362. The :class:`StreamReader` class is a subclass of :class:`Codec` and defines the
  363. following methods which every stream reader must define in order to be
  364. compatible with the Python codec registry.
  365. .. class:: StreamReader(stream[, errors])
  366. Constructor for a :class:`StreamReader` instance.
  367. All stream readers must provide this constructor interface. They are free to add
  368. additional keyword arguments, but only the ones defined here are used by the
  369. Python codec registry.
  370. *stream* must be a file-like object open for reading (binary) data.
  371. The :class:`StreamReader` may implement different error handling schemes by
  372. providing the *errors* keyword argument. These parameters are defined:
  373. * ``'strict'`` Raise :exc:`ValueError` (or a subclass); this is the default.
  374. * ``'ignore'`` Ignore the character and continue with the next.
  375. * ``'replace'`` Replace with a suitable replacement character.
  376. The *errors* argument will be assigned to an attribute of the same name.
  377. Assigning to this attribute makes it possible to switch between different error
  378. handling strategies during the lifetime of the :class:`StreamReader` object.
  379. The set of allowed values for the *errors* argument can be extended with
  380. :func:`register_error`.
  381. .. method:: read([size[, chars, [firstline]]])
  382. Decodes data from the stream and returns the resulting object.
  383. *chars* indicates the number of characters to read from the
  384. stream. :func:`read` will never return more than *chars* characters, but
  385. it might return less, if there are not enough characters available.
  386. *size* indicates the approximate maximum number of bytes to read from the
  387. stream for decoding purposes. The decoder can modify this setting as
  388. appropriate. The default value -1 indicates to read and decode as much as
  389. possible. *size* is intended to prevent having to decode huge files in
  390. one step.
  391. *firstline* indicates that it would be sufficient to only return the first
  392. line, if there are decoding errors on later lines.
  393. The method should use a greedy read strategy meaning that it should read
  394. as much data as is allowed within the definition of the encoding and the
  395. given size, e.g. if optional encoding endings or state markers are
  396. available on the stream, these should be read too.
  397. .. versionchanged:: 2.4
  398. *chars* argument added.
  399. .. versionchanged:: 2.4.2
  400. *firstline* argument added.
  401. .. method:: readline([size[, keepends]])
  402. Read one line from the input stream and return the decoded data.
  403. *size*, if given, is passed as size argument to the stream's
  404. :meth:`readline` method.
  405. If *keepends* is false line-endings will be stripped from the lines
  406. returned.
  407. .. versionchanged:: 2.4
  408. *keepends* argument added.
  409. .. method:: readlines([sizehint[, keepends]])
  410. Read all lines available on the input stream and return them as a list of
  411. lines.
  412. Line-endings are implemented using the codec's decoder method and are
  413. included in the list entries if *keepends* is true.
  414. *sizehint*, if given, is passed as the *size* argument to the stream's
  415. :meth:`read` method.
  416. .. method:: reset()
  417. Resets the codec buffers used for keeping state.
  418. Note that no stream repositioning should take place. This method is
  419. primarily intended to be able to recover from decoding errors.
  420. In addition to the above methods, the :class:`StreamReader` must also inherit
  421. all other methods and attributes from the underlying stream.
  422. The next two base classes are included for convenience. They are not needed by
  423. the codec registry, but may provide useful in practice.
  424. .. _stream-reader-writer:
  425. StreamReaderWriter Objects
  426. ^^^^^^^^^^^^^^^^^^^^^^^^^^
  427. The :class:`StreamReaderWriter` allows wrapping streams which work in both read
  428. and write modes.
  429. The design is such that one can use the factory functions returned by the
  430. :func:`lookup` function to construct the instance.
  431. .. class:: StreamReaderWriter(stream, Reader, Writer, errors)
  432. Creates a :class:`StreamReaderWriter` instance. *stream* must be a file-like
  433. object. *Reader* and *Writer* must be factory functions or classes providing the
  434. :class:`StreamReader` and :class:`StreamWriter` interface resp. Error handling
  435. is done in the same way as defined for the stream readers and writers.
  436. :class:`StreamReaderWriter` instances define the combined interfaces of
  437. :class:`StreamReader` and :class:`StreamWriter` classes. They inherit all other
  438. methods and attributes from the underlying stream.
  439. .. _stream-recoder-objects:
  440. StreamRecoder Objects
  441. ^^^^^^^^^^^^^^^^^^^^^
  442. The :class:`StreamRecoder` provide a frontend - backend view of encoding data
  443. which is sometimes useful when dealing with different encoding environments.
  444. The design is such that one can use the factory functions returned by the
  445. :func:`lookup` function to construct the instance.
  446. .. class:: StreamRecoder(stream, encode, decode, Reader, Writer, errors)
  447. Creates a :class:`StreamRecoder` instance which implements a two-way conversion:
  448. *encode* and *decode* work on the frontend (the input to :meth:`read` and output
  449. of :meth:`write`) while *Reader* and *Writer* work on the backend (reading and
  450. writing to the stream).
  451. You can use these objects to do transparent direct recodings from e.g. Latin-1
  452. to UTF-8 and back.
  453. *stream* must be a file-like object.
  454. *encode*, *decode* must adhere to the :class:`Codec` interface. *Reader*,
  455. *Writer* must be factory functions or classes providing objects of the
  456. :class:`StreamReader` and :class:`StreamWriter` interface respectively.
  457. *encode* and *decode* are needed for the frontend translation, *Reader* and
  458. *Writer* for the backend translation. The intermediate format used is
  459. determined by the two sets of codecs, e.g. the Unicode codecs will use Unicode
  460. as the intermediate encoding.
  461. Error handling is done in the same way as defined for the stream readers and
  462. writers.
  463. :class:`StreamRecoder` instances define the combined interfaces of
  464. :class:`StreamReader` and :class:`StreamWriter` classes. They inherit all other
  465. methods and attributes from the underlying stream.
  466. .. _encodings-overview:
  467. Encodings and Unicode
  468. ---------------------
  469. Unicode strings are stored internally as sequences of codepoints (to be precise
  470. as :ctype:`Py_UNICODE` arrays). Depending on the way Python is compiled (either
  471. via :option:`--enable-unicode=ucs2` or :option:`--enable-unicode=ucs4`, with the
  472. former being the default) :ctype:`Py_UNICODE` is either a 16-bit or 32-bit data
  473. type. Once a Unicode object is used outside of CPU and memory, CPU endianness
  474. and how these arrays are stored as bytes become an issue. Transforming a
  475. unicode object into a sequence of bytes is called encoding and recreating the
  476. unicode object from the sequence of bytes is known as decoding. There are many
  477. different methods for how this transformation can be done (these methods are
  478. also called encodings). The simplest method is to map the codepoints 0-255 to
  479. the bytes ``0x0``-``0xff``. This means that a unicode object that contains
  480. codepoints above ``U+00FF`` can't be encoded with this method (which is called
  481. ``'latin-1'`` or ``'iso-8859-1'``). :func:`unicode.encode` will raise a
  482. :exc:`UnicodeEncodeError` that looks like this: ``UnicodeEncodeError: 'latin-1'
  483. codec can't encode character u'\u1234' in position 3: ordinal not in
  484. range(256)``.
  485. There's another group of encodings (the so called charmap encodings) that choose
  486. a different subset of all unicode code points and how these codepoints are
  487. mapped to the bytes ``0x0``-``0xff``. To see how this is done simply open
  488. e.g. :file:`encodings/cp1252.py` (which is an encoding that is used primarily on
  489. Windows). There's a string constant with 256 characters that shows you which
  490. character is mapped to which byte value.
  491. All of these encodings can only encode 256 of the 65536 (or 1114111) codepoints
  492. defined in unicode. A simple and straightforward way that can store each Unicode
  493. code point, is to store each codepoint as two consecutive bytes. There are two
  494. possibilities: Store the bytes in big endian or in little endian order. These
  495. two encodings are called UTF-16-BE and UTF-16-LE respectively. Their
  496. disadvantage is that if e.g. you use UTF-16-BE on a little endian machine you
  497. will always have to swap bytes on encoding and decoding. UTF-16 avoids this
  498. problem: Bytes will always be in natural endianness. When these bytes are read
  499. by a CPU with a different endianness, then bytes have to be swapped though. To
  500. be able to detect the endianness of a UTF-16 byte sequence, there's the so
  501. called BOM (the "Byte Order Mark"). This is the Unicode character ``U+FEFF``.
  502. This character will be prepended to every UTF-16 byte sequence. The byte swapped
  503. version of this character (``0xFFFE``) is an illegal character that may not
  504. appear in a Unicode text. So when the first character in an UTF-16 byte sequence
  505. appears to be a ``U+FFFE`` the bytes have to be swapped on decoding.
  506. Unfortunately upto Unicode 4.0 the character ``U+FEFF`` had a second purpose as
  507. a ``ZERO WIDTH NO-BREAK SPACE``: A character that has no width and doesn't allow
  508. a word to be split. It can e.g. be used to give hints to a ligature algorithm.
  509. With Unicode 4.0 using ``U+FEFF`` as a ``ZERO WIDTH NO-BREAK SPACE`` has been
  510. deprecated (with ``U+2060`` (``WORD JOINER``) assuming this role). Nevertheless
  511. Unicode software still must be able to handle ``U+FEFF`` in both roles: As a BOM
  512. it's a device to determine the storage layout of the encoded bytes, and vanishes
  513. once the byte sequence has been decoded into a Unicode string; as a ``ZERO WIDTH
  514. NO-BREAK SPACE`` it's a normal character that will be decoded like any other.
  515. There's another encoding that is able to encoding the full range of Unicode
  516. characters: UTF-8. UTF-8 is an 8-bit encoding, which means there are no issues
  517. with byte order in UTF-8. Each byte in a UTF-8 byte sequence consists of two
  518. parts: Marker bits (the most significant bits) and payload bits. The marker bits
  519. are a sequence of zero to six 1 bits followed by a 0 bit. Unicode characters are
  520. encoded like this (with x being payload bits, which when concatenated give the
  521. Unicode character):
  522. +-----------------------------------+----------------------------------------------+
  523. | Range | Encoding |
  524. +===================================+==============================================+
  525. | ``U-00000000`` ... ``U-0000007F`` | 0xxxxxxx |
  526. +-----------------------------------+----------------------------------------------+
  527. | ``U-00000080`` ... ``U-000007FF`` | 110xxxxx 10xxxxxx |
  528. +-----------------------------------+----------------------------------------------+
  529. | ``U-00000800`` ... ``U-0000FFFF`` | 1110xxxx 10xxxxxx 10xxxxxx |
  530. +-----------------------------------+----------------------------------------------+
  531. | ``U-00010000`` ... ``U-001FFFFF`` | 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx |
  532. +-----------------------------------+----------------------------------------------+
  533. | ``U-00200000`` ... ``U-03FFFFFF`` | 111110xx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx |
  534. +-----------------------------------+----------------------------------------------+
  535. | ``U-04000000`` ... ``U-7FFFFFFF`` | 1111110x 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx |
  536. | | 10xxxxxx |
  537. +-----------------------------------+----------------------------------------------+
  538. The least significant bit of the Unicode character is the rightmost x bit.
  539. As UTF-8 is an 8-bit encoding no BOM is required and any ``U+FEFF`` character in
  540. the decoded Unicode string (even if it's the first character) is treated as a
  541. ``ZERO WIDTH NO-BREAK SPACE``.
  542. Without external information it's impossible to reliably determine which
  543. encoding was used for encoding a Unicode string. Each charmap encoding can
  544. decode any random byte sequence. However that's not possible with UTF-8, as
  545. UTF-8 byte sequences have a structure that doesn't allow arbitrary byte
  546. sequences. To increase the reliability with which a UTF-8 encoding can be
  547. detected, Microsoft invented a variant of UTF-8 (that Python 2.5 calls
  548. ``"utf-8-sig"``) for its Notepad program: Before any of the Unicode characters
  549. is written to the file, a UTF-8 encoded BOM (which looks like this as a byte
  550. sequence: ``0xef``, ``0xbb``, ``0xbf``) is written. As it's rather improbable
  551. that any charmap encoded file starts with these byte values (which would e.g.
  552. map to
  553. | LATIN SMALL LETTER I WITH DIAERESIS
  554. | RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK
  555. | INVERTED QUESTION MARK
  556. in iso-8859-1), this increases the probability that a utf-8-sig encoding can be
  557. correctly guessed from the byte sequence. So here the BOM is not used to be able
  558. to determine the byte order used for generating the byte sequence, but as a
  559. signature that helps in guessing the encoding. On encoding the utf-8-sig codec
  560. will write ``0xef``, ``0xbb``, ``0xbf`` as the first three bytes to the file. On
  561. decoding utf-8-sig will skip those three bytes if they appear as the first three
  562. bytes in the file.
  563. .. _standard-encodings:
  564. Standard Encodings
  565. ------------------
  566. Python comes with a number of codecs built-in, either implemented as C functions
  567. or with dictionaries as mapping tables. The following table lists the codecs by
  568. name, together with a few common aliases, and the languages for which the
  569. encoding is likely used. Neither the list of aliases nor the list of languages
  570. is meant to be exhaustive. Notice that spelling alternatives that only differ in
  571. case or use a hyphen instead of an underscore are also valid aliases.
  572. Many of the character sets support the same languages. They vary in individual
  573. characters (e.g. whether the EURO SIGN is supported or not), and in the
  574. assignment of characters to code positions. For the European languages in
  575. particular, the following variants typically exist:
  576. * an ISO 8859 codeset
  577. * a Microsoft Windows code page, which is typically derived from a 8859 codeset,
  578. but replaces control characters with additional graphic characters
  579. * an IBM EBCDIC code page
  580. * an IBM PC code page, which is ASCII compatible
  581. +-----------------+--------------------------------+--------------------------------+
  582. | Codec | Aliases | Languages |
  583. +=================+================================+================================+
  584. | ascii | 646, us-ascii | English |
  585. +-----------------+--------------------------------+--------------------------------+
  586. | big5 | big5-tw, csbig5 | Traditional Chinese |
  587. +-----------------+--------------------------------+--------------------------------+
  588. | big5hkscs | big5-hkscs, hkscs | Traditional Chinese |
  589. +-----------------+--------------------------------+--------------------------------+
  590. | cp037 | IBM037, IBM039 | English |
  591. +-----------------+--------------------------------+--------------------------------+
  592. | cp424 | EBCDIC-CP-HE, IBM424 | Hebrew |
  593. +-----------------+--------------------------------+--------------------------------+
  594. | cp437 | 437, IBM437 | English |
  595. +-----------------+--------------------------------+--------------------------------+
  596. | cp500 | EBCDIC-CP-BE, EBCDIC-CP-CH, | Western Europe |
  597. | | IBM500 | |
  598. +-----------------+--------------------------------+--------------------------------+
  599. | cp737 | | Greek |
  600. +-----------------+--------------------------------+--------------------------------+
  601. | cp775 | IBM775 | Baltic languages |
  602. +-----------------+--------------------------------+--------------------------------+
  603. | cp850 | 850, IBM850 | Western Europe |
  604. +-----------------+--------------------------------+--------------------------------+
  605. | cp852 | 852, IBM852 | Central and Eastern Europe |
  606. +-----------------+--------------------------------+--------------------------------+
  607. | cp855 | 855, IBM855 | Bulgarian, Byelorussian, |
  608. | | | Macedonian, Russian, Serbian |
  609. +-----------------+--------------------------------+--------------------------------+
  610. | cp856 | | Hebrew |
  611. +-----------------+--------------------------------+--------------------------------+
  612. | cp857 | 857, IBM857 | Turkish |
  613. +-----------------+--------------------------------+--------------------------------+
  614. | cp860 | 860, IBM860 | Portuguese |
  615. +-----------------+--------------------------------+--------------------------------+
  616. | cp861 | 861, CP-IS, IBM861 | Icelandic |
  617. +-----------------+--------------------------------+--------------------------------+
  618. | cp862 | 862, IBM862 | Hebrew |
  619. +-----------------+--------------------------------+--------------------------------+
  620. | cp863 | 863, IBM863 | Canadian |
  621. +-----------------+--------------------------------+--------------------------------+
  622. | cp864 | IBM864 | Arabic |
  623. +-----------------+--------------------------------+--------------------------------+
  624. | cp865 | 865, IBM865 | Danish, Norwegian |
  625. +-----------------+--------------------------------+--------------------------------+
  626. | cp866 | 866, IBM866 | Russian |
  627. +-----------------+--------------------------------+--------------------------------+
  628. | cp869 | 869, CP-GR, IBM869 | Greek |
  629. +-----------------+--------------------------------+--------------------------------+
  630. | cp874 | | Thai |
  631. +-----------------+--------------------------------+--------------------------------+
  632. | cp875 | | Greek |
  633. +-----------------+--------------------------------+--------------------------------+
  634. | cp932 | 932, ms932, mskanji, ms-kanji | Japanese |
  635. +-----------------+--------------------------------+--------------------------------+
  636. | cp949 | 949, ms949, uhc | Korean |
  637. +-----------------+--------------------------------+--------------------------------+
  638. | cp950 | 950, ms950 | Traditional Chinese |
  639. +-----------------+--------------------------------+--------------------------------+
  640. | cp1006 | | Urdu |
  641. +-----------------+--------------------------------+--------------------------------+
  642. | cp1026 | ibm1026 | Turkish |
  643. +-----------------+--------------------------------+--------------------------------+
  644. | cp1140 | ibm1140 | Western Europe |
  645. +-----------------+--------------------------------+--------------------------------+
  646. | cp1250 | windows-1250 | Central and Eastern Europe |
  647. +-----------------+--------------------------------+--------------------------------+
  648. | cp1251 | windows-1251 | Bulgarian, Byelorussian, |
  649. | | | Macedonian, Russian, Serbian |
  650. +-----------------+--------------------------------+--------------------------------+
  651. | cp1252 | windows-1252 | Western Europe |
  652. +-----------------+--------------------------------+--------------------------------+
  653. | cp1253 | windows-1253 | Greek |
  654. +-----------------+--------------------------------+--------------------------------+
  655. | cp1254 | windows-1254 | Turkish |
  656. +-----------------+--------------------------------+--------------------------------+
  657. | cp1255 | windows-1255 | Hebrew |
  658. +-----------------+--------------------------------+--------------------------------+
  659. | cp1256 | windows1256 | Arabic |
  660. +-----------------+--------------------------------+--------------------------------+
  661. | cp1257 | windows-1257 | Baltic languages |
  662. +-----------------+--------------------------------+--------------------------------+
  663. | cp1258 | windows-1258 | Vietnamese |
  664. +-----------------+--------------------------------+--------------------------------+
  665. | euc_jp | eucjp, ujis, u-jis | Japanese |
  666. +-----------------+--------------------------------+--------------------------------+
  667. | euc_jis_2004 | jisx0213, eucjis2004 | Japanese |
  668. +-----------------+--------------------------------+--------------------------------+
  669. | euc_jisx0213 | eucjisx0213 | Japanese |
  670. +-----------------+--------------------------------+--------------------------------+
  671. | euc_kr | euckr, korean, ksc5601, | Korean |
  672. | | ks_c-5601, ks_c-5601-1987, | |
  673. | | ksx1001, ks_x-1001 | |
  674. +-----------------+--------------------------------+--------------------------------+
  675. | gb2312 | chinese, csiso58gb231280, euc- | Simplified Chinese |
  676. | | cn, euccn, eucgb2312-cn, | |
  677. | | gb2312-1980, gb2312-80, iso- | |
  678. | | ir-58 | |
  679. +-----------------+--------------------------------+--------------------------------+
  680. | gbk | 936, cp936, ms936 | Unified Chinese |
  681. +-----------------+--------------------------------+--------------------------------+
  682. | gb18030 | gb18030-2000 | Unified Chinese |
  683. +-----------------+--------------------------------+--------------------------------+
  684. | hz | hzgb, hz-gb, hz-gb-2312 | Simplified Chinese |
  685. +-----------------+--------------------------------+--------------------------------+
  686. | iso2022_jp | csiso2022jp, iso2022jp, | Japanese |
  687. | | iso-2022-jp | |
  688. +-----------------+--------------------------------+--------------------------------+
  689. | iso2022_jp_1 | iso2022jp-1, iso-2022-jp-1 | Japanese |
  690. +-----------------+--------------------------------+--------------------------------+
  691. | iso2022_jp_2 | iso2022jp-2, iso-2022-jp-2 | Japanese, Korean, Simplified |
  692. | | | Chinese, Western Europe, Greek |
  693. +-----------------+--------------------------------+--------------------------------+
  694. | iso2022_jp_2004 | iso2022jp-2004, | Japanese |
  695. | | iso-2022-jp-2004 | |
  696. +-----------------+--------------------------------+--------------------------------+
  697. | iso2022_jp_3 | iso2022jp-3, iso-2022-jp-3 | Japanese |
  698. +-----------------+--------------------------------+--------------------------------+
  699. | iso2022_jp_ext | iso2022jp-ext, iso-2022-jp-ext | Japanese |
  700. +-----------------+--------------------------------+--------------------------------+
  701. | iso2022_kr | csiso2022kr, iso2022kr, | Korean |
  702. | | iso-2022-kr | |
  703. +-----------------+--------------------------------+--------------------------------+
  704. | latin_1 | iso-8859-1, iso8859-1, 8859, | West Europe |
  705. | | cp819, latin, latin1, L1 | |
  706. +-----------------+--------------------------------+--------------------------------+
  707. | iso8859_2 | iso-8859-2, latin2, L2 | Central and Eastern Europe |
  708. +-----------------+--------------------------------+--------------------------------+
  709. | iso8859_3 | iso-8859-3, latin3, L3 | Esperanto, Maltese |
  710. +-----------------+--------------------------------+--------------------------------+
  711. | iso8859_4 | iso-8859-4, latin4, L4 | Baltic languages |
  712. +-----------------+--------------------------------+--------------------------------+
  713. | iso8859_5 | iso-8859-5, cyrillic | Bulgarian, Byelorussian, |
  714. | | | Macedonian, Russian, Serbian |
  715. +-----------------+--------------------------------+--------------------------------+
  716. | iso8859_6 | iso-8859-6, arabic | Arabic |
  717. +-----------------+--------------------------------+--------------------------------+
  718. | iso8859_7 | iso-8859-7, greek, greek8 | Greek |
  719. +-----------------+--------------------------------+--------------------------------+
  720. | iso8859_8 | iso-8859-8, hebrew | Hebrew |
  721. +-----------------+--------------------------------+--------------------------------+
  722. | iso8859_9 | iso-8859-9, latin5, L5 | Turkish |
  723. +-----------------+--------------------------------+--------------------------------+
  724. | iso8859_10 | iso-8859-10, latin6, L6 | Nordic languages |
  725. +-----------------+--------------------------------+--------------------------------+
  726. | iso8859_13 | iso-8859-13 | Baltic languages |
  727. +-----------------+--------------------------------+--------------------------------+
  728. | iso8859_14 | iso-8859-14, latin8, L8 | Celtic languages |
  729. +-----------------+--------------------------------+--------------------------------+
  730. | iso8859_15 | iso-8859-15 | Western Europe |
  731. +-----------------+--------------------------------+--------------------------------+
  732. | johab | cp1361, ms1361 | Korean |
  733. +-----------------+--------------------------------+--------------------------------+
  734. | koi8_r | | Russian |
  735. +-----------------+--------------------------------+--------------------------------+
  736. | koi8_u | | Ukrainian |
  737. +-----------------+--------------------------------+--------------------------------+
  738. | mac_cyrillic | maccyrillic | Bulgarian, Byelorussian, |
  739. | | | Macedonian, Russian, Serbian |
  740. +-----------------+--------------------------------+--------------------------------+
  741. | mac_greek | macgreek | Greek |
  742. +-----------------+--------------------------------+--------------------------------+
  743. | mac_iceland | maciceland | Icelandic |
  744. +-----------------+--------------------------------+--------------------------------+
  745. | mac_latin2 | maclatin2, maccentraleurope | Central and Eastern Europe |
  746. +-----------------+--------------------------------+--------------------------------+
  747. | mac_roman | macroman | Western Europe |
  748. +-----------------+--------------------------------+--------------------------------+
  749. | mac_turkish | macturkish | Turkish |
  750. +-----------------+--------------------------------+--------------------------------+
  751. | ptcp154 | csptcp154, pt154, cp154, | Kazakh |
  752. | | cyrillic-asian | |
  753. +-----------------+--------------------------------+--------------------------------+
  754. | shift_jis | csshiftjis, shiftjis, sjis, | Japanese |
  755. | | s_jis | |
  756. +-----------------+--------------------------------+--------------------------------+
  757. | shift_jis_2004 | shiftjis2004, sjis_2004, | Japanese |
  758. | | sjis2004 | |
  759. +-----------------+--------------------------------+--------------------------------+
  760. | shift_jisx0213 | shiftjisx0213, sjisx0213, | Japanese |
  761. | | s_jisx0213 | |
  762. +-----------------+--------------------------------+--------------------------------+
  763. | utf_32 | U32, utf32 | all languages |
  764. +-----------------+--------------------------------+--------------------------------+
  765. | utf_32_be | UTF-32BE | all languages |
  766. +-----------------+--------------------------------+--------------------------------+
  767. | utf_32_le | UTF-32LE | all languages |
  768. +-----------------+--------------------------------+--------------------------------+
  769. | utf_16 | U16, utf16 | all languages |
  770. +-----------------+--------------------------------+--------------------------------+
  771. | utf_16_be | UTF-16BE | all languages (BMP only) |
  772. +-----------------+--------------------------------+--------------------------------+
  773. | utf_16_le | UTF-16LE | all languages (BMP only) |
  774. +-----------------+--------------------------------+--------------------------------+
  775. | utf_7 | U7, unicode-1-1-utf-7 | all languages |
  776. +-----------------+--------------------------------+--------------------------------+
  777. | utf_8 | U8, UTF, utf8 | all languages |
  778. +-----------------+--------------------------------+--------------------------------+
  779. | utf_8_sig | | all languages |
  780. +-----------------+--------------------------------+--------------------------------+
  781. A number of codecs are specific to Python, so their codec names have no meaning
  782. outside Python. Some of them don't convert from Unicode strings to byte strings,
  783. but instead use the property of the Python codecs machinery that any bijective
  784. function with one argument can be considered as an encoding.
  785. For the codecs listed below, the result in the "encoding" direction is always a
  786. byte string. The result of the "decoding" direction is listed as operand type in
  787. the table.
  788. +--------------------+---------------------------+----------------+---------------------------+
  789. | Codec | Aliases | Operand type | Purpose |
  790. +====================+===========================+================+===========================+
  791. | base64_codec | base64, base-64 | byte string | Convert operand to MIME |
  792. | | | | base64 |
  793. +--------------------+---------------------------+----------------+---------------------------+
  794. | bz2_codec | bz2 | byte string | Compress the operand |
  795. | | | | using bz2 |
  796. +--------------------+---------------------------+----------------+---------------------------+
  797. | hex_codec | hex | byte string | Convert operand to |
  798. | | | | hexadecimal |
  799. | | | | representation, with two |
  800. | | | | digits per byte |
  801. +--------------------+---------------------------+----------------+---------------------------+
  802. | idna | | Unicode string | Implements :rfc:`3490`, |
  803. | | | | see also |
  804. | | | | :mod:`encodings.idna` |
  805. +--------------------+---------------------------+----------------+---------------------------+
  806. | mbcs | dbcs | Unicode string | Windows only: Encode |
  807. | | | | operand according to the |
  808. | | | | ANSI codepage (CP_ACP) |
  809. +--------------------+---------------------------+----------------+---------------------------+
  810. | palmos | | Unicode string | Encoding of PalmOS 3.5 |
  811. +--------------------+---------------------------+----------------+---------------------------+
  812. | punycode | | Unicode string | Implements :rfc:`3492` |
  813. +--------------------+---------------------------+----------------+---------------------------+
  814. | quopri_codec | quopri, quoted-printable, | byte string | Convert operand to MIME |
  815. | | quotedprintable | | quoted printable |
  816. +--------------------+---------------------------+----------------+---------------------------+
  817. | raw_unicode_escape | | Unicode string | Produce a string that is |
  818. | | | | suitable as raw Unicode |
  819. | | | | literal in Python source |
  820. | | | | code |
  821. +--------------------+---------------------------+----------------+---------------------------+
  822. | rot_13 | rot13 | Unicode string | Returns the Caesar-cypher |
  823. | | | | encryption of the operand |
  824. +--------------------+---------------------------+----------------+---------------------------+
  825. | string_escape | | byte string | Produce a string that is |
  826. | | | | suitable as string |
  827. | | | | literal in Python source |
  828. | | | | code |
  829. +--------------------+---------------------------+----------------+---------------------------+
  830. | undefined | | any | Raise an exception for |
  831. | | | | all conversions. Can be |
  832. | | | | used as the system |
  833. | | | | encoding if no automatic |
  834. | | | | :term:`coercion` between |
  835. | | | | byte and Unicode strings |
  836. | | | | is desired. |
  837. +--------------------+---------------------------+----------------+---------------------------+
  838. | unicode_escape | | Unicode string | Produce a string that is |
  839. | | | | suitable as Unicode |
  840. | | | | literal in Python source |
  841. | | | | code |
  842. +--------------------+---------------------------+----------------+---------------------------+
  843. | unicode_internal | | Unicode string | Return the internal |
  844. | | | | representation of the |
  845. | | | | operand |
  846. +--------------------+---------------------------+----------------+---------------------------+
  847. | uu_codec | uu | byte string | Convert the operand using |
  848. | | | | uuencode |
  849. +--------------------+---------------------------+----------------+---------------------------+
  850. | zlib_codec | zip, zlib | byte string | Compress the operand |
  851. | | | | using gzip |
  852. +--------------------+---------------------------+----------------+---------------------------+
  853. .. versionadded:: 2.3
  854. The ``idna`` and ``punycode`` encodings.
  855. :mod:`encodings.idna` --- Internationalized Domain Names in Applications
  856. ------------------------------------------------------------------------
  857. .. module:: encodings.idna
  858. :synopsis: Internationalized Domain Names implementation
  859. .. moduleauthor:: Martin v. Lรถwis
  860. .. versionadded:: 2.3
  861. This module implements :rfc:`3490` (Internationalized Domain Names in
  862. Applications) and :rfc:`3492` (Nameprep: A Stringprep Profile for
  863. Internationalized Domain Names (IDN)). It builds upon the ``punycode`` encoding
  864. and :mod:`stringprep`.
  865. These RFCs together define a protocol to support non-ASCII characters in domain
  866. names. A domain name containing non-ASCII characters (such as
  867. ``www.Alliancefranรงaise.nu``) is converted into an ASCII-compatible encoding
  868. (ACE, such as ``www.xn--alliancefranaise-npb.nu``). The ACE form of the domain
  869. name is then used in all places where arbitrary characters are not allowed by
  870. the protocol, such as DNS queries, HTTP :mailheader:`Host` fields, and so
  871. on. This conversion is carried out in the application; if possible invisible to
  872. the user: The application should transparently convert Unicode domain labels to
  873. IDNA on the wire, and convert back ACE labels to Unicode before presenting them
  874. to the user.
  875. Python supports this conversion in several ways: The ``idna`` codec allows to
  876. convert between Unicode and the ACE. Furthermore, the :mod:`socket` module
  877. transparently converts Unicode host names to ACE, so that applications need not
  878. be concerned about converting host names themselves when they pass them to the
  879. socket module. On top of that, modules that have host names as function
  880. parameters, such as :mod:`httplib` and :mod:`ftplib`, accept Unicode host names
  881. (:mod:`httplib` then also transparently sends an IDNA hostname in the
  882. :mailheader:`Host` field if it sends that field at all).
  883. When receiving host names from the wire (such as in reverse name lookup), no
  884. automatic conversion to Unicode is performed: Applications wishing to present
  885. such host names to the user should decode them to Unicode.
  886. The module :mod:`encodings.idna` also implements the nameprep procedure, which
  887. performs certain normalizations on host names, to achieve case-insensitivity of
  888. international domain names, and to unify similar characters. The nameprep
  889. functions can be used directly if desired.
  890. .. function:: nameprep(label)
  891. Return the nameprepped version of *label*. The implementation currently assumes
  892. query strings, so ``AllowUnassigned`` is true.
  893. .. function:: ToASCII(label)
  894. Convert a label to ASCII, as specified in :rfc:`3490`. ``UseSTD3ASCIIRules`` is
  895. assumed to be false.
  896. .. function:: ToUnicode(label)
  897. Convert a label to Unicode, as specified in :rfc:`3490`.
  898. :mod:`encodings.utf_8_sig` --- UTF-8 codec with BOM signature
  899. -------------------------------------------------------------
  900. .. module:: encodings.utf_8_sig
  901. :synopsis: UTF-8 codec with BOM signature
  902. .. moduleauthor:: Walter Dรถrwald
  903. .. versionadded:: 2.5
  904. This module implements a variant of the UTF-8 codec: On encoding a UTF-8 encoded
  905. BOM will be prepended to the UTF-8 encoded bytes. For the stateful encoder this
  906. is only done once (on the first write to the byte stream). For decoding an
  907. optional UTF-8 encoded BOM at the start of the data will be skipped.