blob: b306606e9e916997f9b8ab0ae418c48b050d3dd6 [file] [log] [blame]
Fred Drakeb7979c72000-04-06 14:21:58 +00001\section{\module{codecs} ---
Fred Drake69ca9502000-04-06 16:09:59 +00002 Codec registry and base classes}
Fred Drakeb7979c72000-04-06 14:21:58 +00003
Fred Drake69ca9502000-04-06 16:09:59 +00004\declaremodule{standard}{codecs}
Fred Drakeb7979c72000-04-06 14:21:58 +00005\modulesynopsis{Encode and decode data and streams.}
6\moduleauthor{Marc-Andre Lemburg}{mal@lemburg.com}
7\sectionauthor{Marc-Andre Lemburg}{mal@lemburg.com}
Martin v. Löwis2548c732003-04-18 10:39:54 +00008\sectionauthor{Martin v. L\"owis}{martin@v.loewis.de}
Fred Drakeb7979c72000-04-06 14:21:58 +00009
10\index{Unicode}
11\index{Codecs}
12\indexii{Codecs}{encode}
13\indexii{Codecs}{decode}
14\index{streams}
15\indexii{stackable}{streams}
16
17
18This module defines base classes for standard Python codecs (encoders
19and decoders) and provides access to the internal Python codec
Walter Dörwald3aeb6322002-09-02 13:14:32 +000020registry which manages the codec and error handling lookup process.
Fred Drakeb7979c72000-04-06 14:21:58 +000021
22It defines the following functions:
23
24\begin{funcdesc}{register}{search_function}
25Register a codec search function. Search functions are expected to
26take one argument, the encoding name in all lower case letters, and
27return a tuple of functions \code{(\var{encoder}, \var{decoder}, \var{stream_reader},
28\var{stream_writer})} taking the following arguments:
29
30 \var{encoder} and \var{decoder}: These must be functions or methods
Fred Drake602aa772000-10-12 20:50:55 +000031 which have the same interface as the
32 \method{encode()}/\method{decode()} methods of Codec instances (see
33 Codec Interface). The functions/methods are expected to work in a
34 stateless mode.
Fred Drakeb7979c72000-04-06 14:21:58 +000035
36 \var{stream_reader} and \var{stream_writer}: These have to be
37 factory functions providing the following interface:
38
Fred Drake602aa772000-10-12 20:50:55 +000039 \code{factory(\var{stream}, \var{errors}='strict')}
Fred Drakeb7979c72000-04-06 14:21:58 +000040
41 The factory functions must return objects providing the interfaces
Fred Drake69ca9502000-04-06 16:09:59 +000042 defined by the base classes \class{StreamWriter} and
43 \class{StreamReader}, respectively. Stream codecs can maintain
44 state.
Fred Drakeb7979c72000-04-06 14:21:58 +000045
Fred Drake69ca9502000-04-06 16:09:59 +000046 Possible values for errors are \code{'strict'} (raise an exception
47 in case of an encoding error), \code{'replace'} (replace malformed
Walter Dörwald72f86162002-11-19 21:51:35 +000048 data with a suitable replacement marker, such as \character{?}),
Fred Drake69ca9502000-04-06 16:09:59 +000049 \code{'ignore'} (ignore malformed data and continue without further
Walter Dörwald72f86162002-11-19 21:51:35 +000050 notice), \code{'xmlcharrefreplace'} (replace with the appropriate XML
51 character reference (for encoding only)) and \code{'backslashreplace'}
52 (replace with backslashed escape sequences (for encoding only)) as
53 well as any other error handling name defined via
54 \function{register_error()}.
Fred Drakeb7979c72000-04-06 14:21:58 +000055
56In case a search function cannot find a given encoding, it should
Fred Drake69ca9502000-04-06 16:09:59 +000057return \code{None}.
Fred Drakeb7979c72000-04-06 14:21:58 +000058\end{funcdesc}
59
60\begin{funcdesc}{lookup}{encoding}
61Looks up a codec tuple in the Python codec registry and returns the
62function tuple as defined above.
63
64Encodings are first looked up in the registry's cache. If not found,
65the list of registered search functions is scanned. If no codecs tuple
Fred Drake69ca9502000-04-06 16:09:59 +000066is found, a \exception{LookupError} is raised. Otherwise, the codecs
67tuple is stored in the cache and returned to the caller.
Fred Drakeb7979c72000-04-06 14:21:58 +000068\end{funcdesc}
69
Skip Montanarob02ea652002-04-17 19:33:06 +000070To simplify access to the various codecs, the module provides these
Marc-André Lemburg494f2ae2001-09-19 11:33:31 +000071additional functions which use \function{lookup()} for the codec
72lookup:
73
74\begin{funcdesc}{getencoder}{encoding}
75Lookup up the codec for the given encoding and return its encoder
76function.
77
78Raises a \exception{LookupError} in case the encoding cannot be found.
79\end{funcdesc}
80
81\begin{funcdesc}{getdecoder}{encoding}
82Lookup up the codec for the given encoding and return its decoder
83function.
84
85Raises a \exception{LookupError} in case the encoding cannot be found.
86\end{funcdesc}
87
88\begin{funcdesc}{getreader}{encoding}
89Lookup up the codec for the given encoding and return its StreamReader
90class or factory function.
91
92Raises a \exception{LookupError} in case the encoding cannot be found.
93\end{funcdesc}
94
95\begin{funcdesc}{getwriter}{encoding}
96Lookup up the codec for the given encoding and return its StreamWriter
97class or factory function.
98
99Raises a \exception{LookupError} in case the encoding cannot be found.
100\end{funcdesc}
101
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000102\begin{funcdesc}{register_error}{name, error_handler}
103Register the error handling function \var{error_handler} under the
Raymond Hettinger8a64d402002-09-08 22:26:13 +0000104name \var{name}. \var{error_handler} will be called during encoding
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000105and decoding in case of an error, when \var{name} is specified as the
Walter Dörwald2e0b18a2003-01-31 17:19:08 +0000106errors parameter.
107
108For encoding \var{error_handler} will be called with a
109\exception{UnicodeEncodeError} instance, which contains information about
110the location of the error. The error handler must either raise this or
111a different exception or return a tuple with a replacement for the
112unencodable part of the input and a position where encoding should
113continue. The encoder will encode the replacement and continue encoding
114the original input at the specified position. Negative position values
115will be treated as being relative to the end of the input string. If the
116resulting position is out of bound an IndexError will be raised.
117
118Decoding and translating works similar, except \exception{UnicodeDecodeError}
119or \exception{UnicodeTranslateError} will be passed to the handler and
120that the replacement from the error handler will be put into the output
121directly.
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000122\end{funcdesc}
123
124\begin{funcdesc}{lookup_error}{name}
125Return the error handler previously register under the name \var{name}.
126
127Raises a \exception{LookupError} in case the handler cannot be found.
128\end{funcdesc}
129
130\begin{funcdesc}{strict_errors}{exception}
131Implements the \code{strict} error handling.
132\end{funcdesc}
133
134\begin{funcdesc}{replace_errors}{exception}
135Implements the \code{replace} error handling.
136\end{funcdesc}
137
138\begin{funcdesc}{ignore_errors}{exception}
139Implements the \code{ignore} error handling.
140\end{funcdesc}
141
142\begin{funcdesc}{xmlcharrefreplace_errors_errors}{exception}
143Implements the \code{xmlcharrefreplace} error handling.
144\end{funcdesc}
145
146\begin{funcdesc}{backslashreplace_errors_errors}{exception}
147Implements the \code{backslashreplace} error handling.
148\end{funcdesc}
149
Walter Dörwald1a7a8942002-11-02 13:32:07 +0000150To simplify working with encoded files or stream, the module
151also defines these utility functions:
152
Fred Drakee1b304d2000-07-24 19:35:52 +0000153\begin{funcdesc}{open}{filename, mode\optional{, encoding\optional{,
154 errors\optional{, buffering}}}}
Fred Drakeb7979c72000-04-06 14:21:58 +0000155Open an encoded file using the given \var{mode} and return
156a wrapped version providing transparent encoding/decoding.
157
Fred Drake0aa811c2001-10-20 04:24:09 +0000158\note{The wrapped version will only accept the object format
Fred Drakee1b304d2000-07-24 19:35:52 +0000159defined by the codecs, i.e.\ Unicode objects for most built-in
160codecs. Output is also codec-dependent and will usually be Unicode as
Fred Drake0aa811c2001-10-20 04:24:09 +0000161well.}
Fred Drakeb7979c72000-04-06 14:21:58 +0000162
163\var{encoding} specifies the encoding which is to be used for the
Raymond Hettinger7e431102003-09-22 15:00:55 +0000164file.
Fred Drakeb7979c72000-04-06 14:21:58 +0000165
166\var{errors} may be given to define the error handling. It defaults
Fred Drakee1b304d2000-07-24 19:35:52 +0000167to \code{'strict'} which causes a \exception{ValueError} to be raised
168in case an encoding error occurs.
Fred Drakeb7979c72000-04-06 14:21:58 +0000169
Fred Drake69ca9502000-04-06 16:09:59 +0000170\var{buffering} has the same meaning as for the built-in
171\function{open()} function. It defaults to line buffered.
Fred Drakeb7979c72000-04-06 14:21:58 +0000172\end{funcdesc}
173
Fred Drakee1b304d2000-07-24 19:35:52 +0000174\begin{funcdesc}{EncodedFile}{file, input\optional{,
175 output\optional{, errors}}}
Fred Drakeb7979c72000-04-06 14:21:58 +0000176Return a wrapped version of file which provides transparent
177encoding translation.
178
179Strings written to the wrapped file are interpreted according to the
180given \var{input} encoding and then written to the original file as
Fred Drakee1b304d2000-07-24 19:35:52 +0000181strings using the \var{output} encoding. The intermediate encoding will
Fred Drakeb7979c72000-04-06 14:21:58 +0000182usually be Unicode but depends on the specified codecs.
183
Fred Drakee1b304d2000-07-24 19:35:52 +0000184If \var{output} is not given, it defaults to \var{input}.
Fred Drakeb7979c72000-04-06 14:21:58 +0000185
186\var{errors} may be given to define the error handling. It defaults to
Fred Drakee1b304d2000-07-24 19:35:52 +0000187\code{'strict'}, which causes \exception{ValueError} to be raised in case
Fred Drakeb7979c72000-04-06 14:21:58 +0000188an encoding error occurs.
189\end{funcdesc}
190
Fred Drakeb7979c72000-04-06 14:21:58 +0000191The module also provides the following constants which are useful
192for reading and writing to platform dependent files:
193
194\begin{datadesc}{BOM}
195\dataline{BOM_BE}
196\dataline{BOM_LE}
Walter Dörwald474458d2002-06-04 15:16:29 +0000197\dataline{BOM_UTF8}
198\dataline{BOM_UTF16}
199\dataline{BOM_UTF16_BE}
200\dataline{BOM_UTF16_LE}
201\dataline{BOM_UTF32}
202\dataline{BOM_UTF32_BE}
203\dataline{BOM_UTF32_LE}
204These constants define various encodings of the Unicode byte order mark
205(BOM) used in UTF-16 and UTF-32 data streams to indicate the byte order
206used in the stream or file and in UTF-8 as a Unicode signature.
207\constant{BOM_UTF16} is either \constant{BOM_UTF16_BE} or
208\constant{BOM_UTF16_LE} depending on the platform's native byte order,
209\constant{BOM} is an alias for \constant{BOM_UTF16}, \constant{BOM_LE}
210for \constant{BOM_UTF16_LE} and \constant{BOM_BE} for \constant{BOM_UTF16_BE}.
211The others represent the BOM in UTF-8 and UTF-32 encodings.
Fred Drakeb7979c72000-04-06 14:21:58 +0000212\end{datadesc}
213
Fred Drakedc40ac02001-01-22 20:17:54 +0000214
Walter Dörwaldd4bfe2c2005-11-25 17:17:12 +0000215\subsection{Codec Base Classes \label{codec-base-classes}}
Fred Drake602aa772000-10-12 20:50:55 +0000216
Fred Drake9984e702005-10-20 17:52:05 +0000217The \module{codecs} module defines a set of base classes which define the
Fred Drake602aa772000-10-12 20:50:55 +0000218interface and can also be used to easily write you own codecs for use
219in Python.
220
221Each codec has to define four interfaces to make it usable as codec in
222Python: stateless encoder, stateless decoder, stream reader and stream
223writer. The stream reader and writers typically reuse the stateless
224encoder/decoder to implement the file protocols.
225
226The \class{Codec} class defines the interface for stateless
227encoders/decoders.
228
229To simplify and standardize error handling, the \method{encode()} and
230\method{decode()} methods may implement different error handling
231schemes by providing the \var{errors} string argument. The following
232string values are defined and implemented by all standard Python
233codecs:
234
Fred Drakedc40ac02001-01-22 20:17:54 +0000235\begin{tableii}{l|l}{code}{Value}{Meaning}
Walter Dörwald430b1562002-11-07 22:33:17 +0000236 \lineii{'strict'}{Raise \exception{UnicodeError} (or a subclass);
Fred Drakedc40ac02001-01-22 20:17:54 +0000237 this is the default.}
238 \lineii{'ignore'}{Ignore the character and continue with the next.}
239 \lineii{'replace'}{Replace with a suitable replacement character;
240 Python will use the official U+FFFD REPLACEMENT
Walter Dörwald430b1562002-11-07 22:33:17 +0000241 CHARACTER for the built-in Unicode codecs on
242 decoding and '?' on encoding.}
243 \lineii{'xmlcharrefreplace'}{Replace with the appropriate XML
244 character reference (only for encoding).}
245 \lineii{'backslashreplace'}{Replace with backslashed escape sequences
246 (only for encoding).}
Fred Drakedc40ac02001-01-22 20:17:54 +0000247\end{tableii}
Fred Drake602aa772000-10-12 20:50:55 +0000248
Walter Dörwald430b1562002-11-07 22:33:17 +0000249The set of allowed values can be extended via \method{register_error}.
250
Fred Drake602aa772000-10-12 20:50:55 +0000251
252\subsubsection{Codec Objects \label{codec-objects}}
253
254The \class{Codec} class defines these methods which also define the
255function interfaces of the stateless encoder and decoder:
256
257\begin{methoddesc}{encode}{input\optional{, errors}}
258 Encodes the object \var{input} and returns a tuple (output object,
Skip Montanaro6c7bc312002-04-16 15:12:10 +0000259 length consumed). While codecs are not restricted to use with Unicode, in
260 a Unicode context, encoding converts a Unicode object to a plain string
261 using a particular character set encoding (e.g., \code{cp1252} or
262 \code{iso-8859-1}).
Fred Drake602aa772000-10-12 20:50:55 +0000263
264 \var{errors} defines the error handling to apply. It defaults to
265 \code{'strict'} handling.
266
267 The method may not store state in the \class{Codec} instance. Use
268 \class{StreamCodec} for codecs which have to keep state in order to
269 make encoding/decoding efficient.
270
271 The encoder must be able to handle zero length input and return an
272 empty object of the output object type in this situation.
273\end{methoddesc}
274
275\begin{methoddesc}{decode}{input\optional{, errors}}
276 Decodes the object \var{input} and returns a tuple (output object,
Skip Montanaro6c7bc312002-04-16 15:12:10 +0000277 length consumed). In a Unicode context, decoding converts a plain string
278 encoded using a particular character set encoding to a Unicode object.
Fred Drake602aa772000-10-12 20:50:55 +0000279
280 \var{input} must be an object which provides the \code{bf_getreadbuf}
281 buffer slot. Python strings, buffer objects and memory mapped files
282 are examples of objects providing this slot.
283
284 \var{errors} defines the error handling to apply. It defaults to
285 \code{'strict'} handling.
286
287 The method may not store state in the \class{Codec} instance. Use
288 \class{StreamCodec} for codecs which have to keep state in order to
289 make encoding/decoding efficient.
290
291 The decoder must be able to handle zero length input and return an
292 empty object of the output object type in this situation.
293\end{methoddesc}
294
295The \class{StreamWriter} and \class{StreamReader} classes provide
296generic working interfaces which can be used to implement new
297encodings submodules very easily. See \module{encodings.utf_8} for an
298example on how this is done.
299
300
301\subsubsection{StreamWriter Objects \label{stream-writer-objects}}
302
303The \class{StreamWriter} class is a subclass of \class{Codec} and
304defines the following methods which every stream writer must define in
305order to be compatible to the Python codec registry.
306
307\begin{classdesc}{StreamWriter}{stream\optional{, errors}}
308 Constructor for a \class{StreamWriter} instance.
309
310 All stream writers must provide this constructor interface. They are
311 free to add additional keyword arguments, but only the ones defined
312 here are used by the Python codec registry.
313
314 \var{stream} must be a file-like object open for writing (binary)
315 data.
316
317 The \class{StreamWriter} may implement different error handling
318 schemes by providing the \var{errors} keyword argument. These
Walter Dörwald430b1562002-11-07 22:33:17 +0000319 parameters are predefined:
Fred Drake602aa772000-10-12 20:50:55 +0000320
321 \begin{itemize}
322 \item \code{'strict'} Raise \exception{ValueError} (or a subclass);
323 this is the default.
324 \item \code{'ignore'} Ignore the character and continue with the next.
325 \item \code{'replace'} Replace with a suitable replacement character
Walter Dörwald430b1562002-11-07 22:33:17 +0000326 \item \code{'xmlcharrefreplace'} Replace with the appropriate XML
327 character reference
328 \item \code{'backslashreplace'} Replace with backslashed escape sequences.
Fred Drake602aa772000-10-12 20:50:55 +0000329 \end{itemize}
Walter Dörwald430b1562002-11-07 22:33:17 +0000330
331 The \var{errors} argument will be assigned to an attribute of the
332 same name. Assigning to this attribute makes it possible to switch
333 between different error handling strategies during the lifetime
334 of the \class{StreamWriter} object.
335
336 The set of allowed values for the \var{errors} argument can
337 be extended with \function{register_error()}.
Fred Drake602aa772000-10-12 20:50:55 +0000338\end{classdesc}
339
340\begin{methoddesc}{write}{object}
341 Writes the object's contents encoded to the stream.
342\end{methoddesc}
343
344\begin{methoddesc}{writelines}{list}
345 Writes the concatenated list of strings to the stream (possibly by
346 reusing the \method{write()} method).
347\end{methoddesc}
348
349\begin{methoddesc}{reset}{}
350 Flushes and resets the codec buffers used for keeping state.
351
352 Calling this method should ensure that the data on the output is put
353 into a clean state, that allows appending of new fresh data without
354 having to rescan the whole stream to recover state.
355\end{methoddesc}
356
357In addition to the above methods, the \class{StreamWriter} must also
358inherit all other methods and attribute from the underlying stream.
359
360
361\subsubsection{StreamReader Objects \label{stream-reader-objects}}
362
363The \class{StreamReader} class is a subclass of \class{Codec} and
364defines the following methods which every stream reader must define in
365order to be compatible to the Python codec registry.
366
367\begin{classdesc}{StreamReader}{stream\optional{, errors}}
368 Constructor for a \class{StreamReader} instance.
369
370 All stream readers must provide this constructor interface. They are
371 free to add additional keyword arguments, but only the ones defined
372 here are used by the Python codec registry.
373
374 \var{stream} must be a file-like object open for reading (binary)
375 data.
376
377 The \class{StreamReader} may implement different error handling
378 schemes by providing the \var{errors} keyword argument. These
379 parameters are defined:
380
381 \begin{itemize}
382 \item \code{'strict'} Raise \exception{ValueError} (or a subclass);
383 this is the default.
384 \item \code{'ignore'} Ignore the character and continue with the next.
385 \item \code{'replace'} Replace with a suitable replacement character.
386 \end{itemize}
Walter Dörwald430b1562002-11-07 22:33:17 +0000387
388 The \var{errors} argument will be assigned to an attribute of the
389 same name. Assigning to this attribute makes it possible to switch
390 between different error handling strategies during the lifetime
391 of the \class{StreamReader} object.
392
393 The set of allowed values for the \var{errors} argument can
394 be extended with \function{register_error()}.
Fred Drake602aa772000-10-12 20:50:55 +0000395\end{classdesc}
396
Martin v. Löwis56066d22005-08-24 07:38:12 +0000397\begin{methoddesc}{read}{\optional{size\optional{, chars, \optional{firstline}}}}
Fred Drake602aa772000-10-12 20:50:55 +0000398 Decodes data from the stream and returns the resulting object.
399
Walter Dörwald69652032004-09-07 20:24:22 +0000400 \var{chars} indicates the number of characters to read from the
Fred Drakea2544ee2004-09-10 01:16:49 +0000401 stream. \function{read()} will never return more than \var{chars}
Walter Dörwald69652032004-09-07 20:24:22 +0000402 characters, but it might return less, if there are not enough
403 characters available.
404
Fred Drake602aa772000-10-12 20:50:55 +0000405 \var{size} indicates the approximate maximum number of bytes to read
406 from the stream for decoding purposes. The decoder can modify this
407 setting as appropriate. The default value -1 indicates to read and
408 decode as much as possible. \var{size} is intended to prevent having
409 to decode huge files in one step.
410
Martin v. Löwis56066d22005-08-24 07:38:12 +0000411 \var{firstline} indicates that it would be sufficient to only return
412 the first line, if there are decoding errors on later lines.
413
Fred Drake602aa772000-10-12 20:50:55 +0000414 The method should use a greedy read strategy meaning that it should
415 read as much data as is allowed within the definition of the encoding
416 and the given size, e.g. if optional encoding endings or state
417 markers are available on the stream, these should be read too.
Walter Dörwald69652032004-09-07 20:24:22 +0000418
419 \versionchanged[\var{chars} argument added]{2.4}
Martin v. Löwis56066d22005-08-24 07:38:12 +0000420 \versionchanged[\var{firstline} argument added]{2.4.2}
Fred Drake602aa772000-10-12 20:50:55 +0000421\end{methoddesc}
422
Walter Dörwald69652032004-09-07 20:24:22 +0000423\begin{methoddesc}{readline}{\optional{size\optional{, keepends}}}
Fred Drake602aa772000-10-12 20:50:55 +0000424 Read one line from the input stream and return the
425 decoded data.
426
Fred Drake602aa772000-10-12 20:50:55 +0000427 \var{size}, if given, is passed as size argument to the stream's
428 \method{readline()} method.
Walter Dörwald69652032004-09-07 20:24:22 +0000429
430 If \var{keepends} is false lineends will be stripped from the
431 lines returned.
432
433 \versionchanged[\var{keepends} argument added]{2.4}
Fred Drake602aa772000-10-12 20:50:55 +0000434\end{methoddesc}
435
Walter Dörwald69652032004-09-07 20:24:22 +0000436\begin{methoddesc}{readlines}{\optional{sizehint\optional{, keepends}}}
Fred Drake602aa772000-10-12 20:50:55 +0000437 Read all lines available on the input stream and return them as list
438 of lines.
439
440 Line breaks are implemented using the codec's decoder method and are
Walter Dörwald69652032004-09-07 20:24:22 +0000441 included in the list entries if \var{keepends} is true.
Fred Drake602aa772000-10-12 20:50:55 +0000442
443 \var{sizehint}, if given, is passed as \var{size} argument to the
444 stream's \method{read()} method.
445\end{methoddesc}
446
447\begin{methoddesc}{reset}{}
448 Resets the codec buffers used for keeping state.
449
450 Note that no stream repositioning should take place. This method is
451 primarily intended to be able to recover from decoding errors.
452\end{methoddesc}
453
454In addition to the above methods, the \class{StreamReader} must also
455inherit all other methods and attribute from the underlying stream.
456
457The next two base classes are included for convenience. They are not
458needed by the codec registry, but may provide useful in practice.
459
460
461\subsubsection{StreamReaderWriter Objects \label{stream-reader-writer}}
462
463The \class{StreamReaderWriter} allows wrapping streams which work in
464both read and write modes.
465
466The design is such that one can use the factory functions returned by
467the \function{lookup()} function to construct the instance.
468
469\begin{classdesc}{StreamReaderWriter}{stream, Reader, Writer, errors}
470 Creates a \class{StreamReaderWriter} instance.
471 \var{stream} must be a file-like object.
472 \var{Reader} and \var{Writer} must be factory functions or classes
473 providing the \class{StreamReader} and \class{StreamWriter} interface
474 resp.
475 Error handling is done in the same way as defined for the
476 stream readers and writers.
477\end{classdesc}
478
479\class{StreamReaderWriter} instances define the combined interfaces of
480\class{StreamReader} and \class{StreamWriter} classes. They inherit
481all other methods and attribute from the underlying stream.
482
483
484\subsubsection{StreamRecoder Objects \label{stream-recoder-objects}}
485
486The \class{StreamRecoder} provide a frontend - backend view of
487encoding data which is sometimes useful when dealing with different
488encoding environments.
489
490The design is such that one can use the factory functions returned by
491the \function{lookup()} function to construct the instance.
492
493\begin{classdesc}{StreamRecoder}{stream, encode, decode,
494 Reader, Writer, errors}
495 Creates a \class{StreamRecoder} instance which implements a two-way
496 conversion: \var{encode} and \var{decode} work on the frontend (the
497 input to \method{read()} and output of \method{write()}) while
498 \var{Reader} and \var{Writer} work on the backend (reading and
499 writing to the stream).
500
501 You can use these objects to do transparent direct recodings from
502 e.g.\ Latin-1 to UTF-8 and back.
503
504 \var{stream} must be a file-like object.
505
506 \var{encode}, \var{decode} must adhere to the \class{Codec}
507 interface, \var{Reader}, \var{Writer} must be factory functions or
Raymond Hettingerf17d65d2003-08-12 00:01:16 +0000508 classes providing objects of the \class{StreamReader} and
Fred Drake602aa772000-10-12 20:50:55 +0000509 \class{StreamWriter} interface respectively.
510
511 \var{encode} and \var{decode} are needed for the frontend
512 translation, \var{Reader} and \var{Writer} for the backend
513 translation. The intermediate format used is determined by the two
514 sets of codecs, e.g. the Unicode codecs will use Unicode as
515 intermediate encoding.
516
517 Error handling is done in the same way as defined for the
518 stream readers and writers.
519\end{classdesc}
520
521\class{StreamRecoder} instances define the combined interfaces of
522\class{StreamReader} and \class{StreamWriter} classes. They inherit
523all other methods and attribute from the underlying stream.
524
Martin v. Löwis412ed3b2006-01-08 10:45:39 +0000525\subsection{Encodings and Unicode\label{encodings-overview}}
526
527Unicode strings are stored internally as sequences of codepoints (to
528be precise as Py_UNICODE arrays). Depending on the way Python is
529compiled (either via --enable-unicode=ucs2 or --enable-unicode=ucs4,
530with the former being the default) Py_UNICODE is either a 16-bit or
53132-bit data type. Once a Unicode object is used outside of CPU and
532memory, CPU endianness and how these arrays are stored as bytes become
533an issue. Transforming a unicode object into a sequence of bytes is
534called encoding and recreating the unicode object from the sequence of
535bytes is known as decoding. There are many different methods how this
536transformation can be done (these methods are also called encodings).
537The simplest method is to map the codepoints 0-255 to the bytes
5380x0-0xff. This means that a unicode object that contains codepoints
539above U+00FF can't be encoded with this method (which is called
540'latin-1' or 'iso-8859-1'). unicode.encode() will raise a
541UnicodeEncodeError that looks like this: UnicodeEncodeError: 'latin-1'
542codec can't encode character u'\u1234' in position 3: ordinal not in
543range(256)
544
545There's another group of encodings (the so called charmap encodings)
546that choose a different subset of all unicode code points and how
547these codepoints are mapped to the bytes 0x0-0xff. To see how this is
548done simply open e.g. encodings/cp1252.py (which is an encoding that
Walter Dörwaldb754fe42006-01-09 12:45:01 +0000549is used primarily on Windows). There's a string constant with 256
Martin v. Löwis412ed3b2006-01-08 10:45:39 +0000550characters that shows you which character is mapped to which byte
551value.
552
553All of these encodings can only encode 256 of the 65536 (or 1114111)
554codepoints defined in unicode. A simple and straightforward way that
555can store each Unicode code point, is to store each codepoint as two
556consecutive bytes. There are two possibilities: Store the bytes in big
557endian or in little endian order. These two encodings are called
558UTF-16-BE and UTF-16-LE respectively. Their disadvantage is that if
559e.g. you use UTF-16-BE on a little endian machine you will always have
560to swap bytes on encoding and decoding. UTF-16 avoids this problem:
561Bytes will always be in natural endianness. When these bytes are read
562by a CPU with a different endianness, then bytes have to be swapped
563though. To be able to detect the endianness of a UTF-16 byte sequence,
564there's the so called BOM (the "Byte Order Mark"). This is the Unicode
565character U+FEFF. This character will be prepended to every UTF-16
566byte sequence. The byte swapped version of this character (0xFFFE) is
567an illegal character that may not appear in a Unicode text. So when
568the first character in an UTF-16 byte sequence appears to be a U+FFFE
569the bytes have to be swapped on decoding. Unfortunately upto Unicode
5704.0 the character U+FEFF had a second purpose as a "ZERO WIDTH
571NO-BREAK SPACE": A character that has no width and doesn't allow a
572word to be split. It can e.g. be used to give hints to a ligature
573algorithm. With Unicode 4.0 using U+FEFF as a ZERO WIDTH NO-BREAK
574SPACE has been deprecated (with U+2060 (WORD JOINER) assuming this
575role). Nevertheless Unicode software still must be able to handle
576U+FEFF in both roles: As a BOM it's a device to determine the storage
577layout of the encoded bytes, and vanishes once the byte sequence has
578been decoded into a Unicode string; as a ZERO WIDTH NO-BREAK SPACE
579it's a normal character that will be decoded like any other.
580
581There's another encoding that is able to encoding the full range of
582Unicode characters: UTF-8. UTF-8 is an 8bit encoding, which means
583there are no issues with byte order in UTF-8. Each byte in a UTF-8
584byte sequence consists of two parts: Marker bits (the most significant
585bits) and payload bits. The marker bits are a sequence of zero to six
5861 bits followed by a 0 bit. Unicode characters are encoded like this
Walter Dörwaldb754fe42006-01-09 12:45:01 +0000587(with x being payload bits, which when concatenated give the Unicode
Martin v. Löwis412ed3b2006-01-08 10:45:39 +0000588character):
589
590\begin{tableii}{l|l}{textrm}{}{Range}{Encoding}
591\lineii{U-00000000 ... U-0000007F}{0xxxxxxx}
592\lineii{U-00000080 ... U-000007FF}{110xxxxx 10xxxxxx}
593\lineii{U-00000800 ... U-0000FFFF}{1110xxxx 10xxxxxx 10xxxxxx}
594\lineii{U-00010000 ... U-001FFFFF}{11110xxx 10xxxxxx 10xxxxxx 10xxxxxx}
595\lineii{U-00200000 ... U-03FFFFFF}{111110xx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx}
596\lineii{U-04000000 ... U-7FFFFFFF}{1111110x 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx}
597\end{tableii}
598
599The least significant bit of the Unicode character is the rightmost x
600bit.
601
602As UTF-8 is an 8bit encoding no BOM is required and any U+FEFF
603character in the decoded Unicode string (even if it's the first
604character) is treated as a ZERO WIDTH NO-BREAK SPACE.
605
606Without external information it's impossible to reliably determine
607which encoding was used for encoding a Unicode string. Each charmap
608encoding can decode any random byte sequence. However that's not
609possible with UTF-8, as UTF-8 byte sequences have a structure that
610doesn't allow arbitrary byte sequence. To increase the reliability
Walter Dörwaldb754fe42006-01-09 12:45:01 +0000611with which a UTF-8 encoding can be detected, Microsoft invented a
Martin v. Löwis412ed3b2006-01-08 10:45:39 +0000612variant of UTF-8 (that Python 2.5 calls "utf-8-sig") for its Notepad
613program: Before any of the Unicode characters is written to the file,
614a UTF-8 encoded BOM (which looks like this as a byte sequence: 0xef,
6150xbb, 0xbf) is written. As it's rather improbably that any charmap
616encoded file starts with these byte values (which would e.g. map to
617
618 LATIN SMALL LETTER I WITH DIAERESIS
619 RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK
620 INVERTED QUESTION MARK
621
622in iso-8859-1), this increases the probability that a utf-8-sig
623encoding can be correctly guessed from the byte sequence. So here the
624BOM is not used to be able to determine the byte order used for
625generating the byte sequence, but as a signature that helps in
626guessing the encoding. On encoding the utf-8-sig codec will write
6270xef, 0xbb, 0xbf as the first three bytes to the file. On decoding
628utf-8-sig will skip those three bytes if they appear as the first
629three bytes in the file.
630
631
Skip Montanaroecf7a522004-07-01 19:26:04 +0000632\subsection{Standard Encodings\label{standard-encodings}}
Martin v. Löwis5c37a772002-12-31 12:39:07 +0000633
634Python comes with a number of codecs builtin, either implemented as C
635functions, or with dictionaries as mapping tables. The following table
636lists the codecs by name, together with a few common aliases, and the
637languages for which the encoding is likely used. Neither the list of
638aliases nor the list of languages is meant to be exhaustive. Notice
639that spelling alternatives that only differ in case or use a hyphen
640instead of an underscore are also valid aliases.
641
642Many of the character sets support the same languages. They vary in
643individual characters (e.g. whether the EURO SIGN is supported or
644not), and in the assignment of characters to code positions. For the
645European languages in particular, the following variants typically
646exist:
647
648\begin{itemize}
649\item an ISO 8859 codeset
650\item a Microsoft Windows code page, which is typically derived from
651 a 8859 codeset, but replaces control characters with additional
652 graphic characters
653\item an IBM EBCDIC code page
Fred Draked4be7472003-04-30 15:02:07 +0000654\item an IBM PC code page, which is \ASCII{} compatible
Martin v. Löwis5c37a772002-12-31 12:39:07 +0000655\end{itemize}
656
657\begin{longtableiii}{l|l|l}{textrm}{Codec}{Aliases}{Languages}
658
659\lineiii{ascii}
660 {646, us-ascii}
661 {English}
662
Hye-Shik Chang3e2a3062004-01-17 14:29:29 +0000663\lineiii{big5}
Hye-Shik Chang910d8f12004-07-17 14:44:43 +0000664 {big5-tw, csbig5}
Hye-Shik Chang3e2a3062004-01-17 14:29:29 +0000665 {Traditional Chinese}
666
Hye-Shik Chang2bb146f2004-07-18 03:06:29 +0000667\lineiii{big5hkscs}
668 {big5-hkscs, hkscs}
669 {Traditional Chinese}
670
Martin v. Löwis5c37a772002-12-31 12:39:07 +0000671\lineiii{cp037}
672 {IBM037, IBM039}
673 {English}
674
675\lineiii{cp424}
676 {EBCDIC-CP-HE, IBM424}
677 {Hebrew}
678
679\lineiii{cp437}
680 {437, IBM437}
681 {English}
682
683\lineiii{cp500}
684 {EBCDIC-CP-BE, EBCDIC-CP-CH, IBM500}
685 {Western Europe}
686
687\lineiii{cp737}
688 {}
689 {Greek}
690
691\lineiii{cp775}
692 {IBM775}
693 {Baltic languages}
694
695\lineiii{cp850}
696 {850, IBM850}
697 {Western Europe}
698
699\lineiii{cp852}
700 {852, IBM852}
701 {Central and Eastern Europe}
702
703\lineiii{cp855}
704 {855, IBM855}
705 {Bulgarian, Byelorussian, Macedonian, Russian, Serbian}
706
707\lineiii{cp856}
708 {}
709 {Hebrew}
710
711\lineiii{cp857}
712 {857, IBM857}
713 {Turkish}
714
715\lineiii{cp860}
716 {860, IBM860}
717 {Portuguese}
718
719\lineiii{cp861}
720 {861, CP-IS, IBM861}
721 {Icelandic}
722
723\lineiii{cp862}
724 {862, IBM862}
725 {Hebrew}
726
727\lineiii{cp863}
728 {863, IBM863}
729 {Canadian}
730
731\lineiii{cp864}
732 {IBM864}
733 {Arabic}
734
735\lineiii{cp865}
736 {865, IBM865}
737 {Danish, Norwegian}
738
Skip Montanaro78bace72004-07-02 02:14:34 +0000739\lineiii{cp866}
740 {866, IBM866}
741 {Russian}
742
Martin v. Löwis5c37a772002-12-31 12:39:07 +0000743\lineiii{cp869}
744 {869, CP-GR, IBM869}
745 {Greek}
746
747\lineiii{cp874}
748 {}
749 {Thai}
750
751\lineiii{cp875}
752 {}
753 {Greek}
754
Hye-Shik Chang3e2a3062004-01-17 14:29:29 +0000755\lineiii{cp932}
Hye-Shik Chang910d8f12004-07-17 14:44:43 +0000756 {932, ms932, mskanji, ms-kanji}
Hye-Shik Chang3e2a3062004-01-17 14:29:29 +0000757 {Japanese}
758
759\lineiii{cp949}
760 {949, ms949, uhc}
761 {Korean}
762
763\lineiii{cp950}
764 {950, ms950}
765 {Traditional Chinese}
766
Martin v. Löwis5c37a772002-12-31 12:39:07 +0000767\lineiii{cp1006}
768 {}
769 {Urdu}
770
771\lineiii{cp1026}
772 {ibm1026}
773 {Turkish}
774
775\lineiii{cp1140}
776 {ibm1140}
777 {Western Europe}
778
779\lineiii{cp1250}
780 {windows-1250}
781 {Central and Eastern Europe}
782
783\lineiii{cp1251}
784 {windows-1251}
785 {Bulgarian, Byelorussian, Macedonian, Russian, Serbian}
786
787\lineiii{cp1252}
788 {windows-1252}
789 {Western Europe}
790
791\lineiii{cp1253}
792 {windows-1253}
793 {Greek}
794
795\lineiii{cp1254}
796 {windows-1254}
797 {Turkish}
798
799\lineiii{cp1255}
800 {windows-1255}
801 {Hebrew}
802
803\lineiii{cp1256}
804 {windows1256}
805 {Arabic}
806
807\lineiii{cp1257}
808 {windows-1257}
809 {Baltic languages}
810
811\lineiii{cp1258}
812 {windows-1258}
813 {Vietnamese}
814
Hye-Shik Chang3e2a3062004-01-17 14:29:29 +0000815\lineiii{euc_jp}
Hye-Shik Chang910d8f12004-07-17 14:44:43 +0000816 {eucjp, ujis, u-jis}
Hye-Shik Chang3e2a3062004-01-17 14:29:29 +0000817 {Japanese}
818
Hye-Shik Chang2bb146f2004-07-18 03:06:29 +0000819\lineiii{euc_jis_2004}
820 {jisx0213, eucjis2004}
821 {Japanese}
822
Hye-Shik Chang3e2a3062004-01-17 14:29:29 +0000823\lineiii{euc_jisx0213}
Hye-Shik Chang2bb146f2004-07-18 03:06:29 +0000824 {eucjisx0213}
Hye-Shik Chang3e2a3062004-01-17 14:29:29 +0000825 {Japanese}
826
827\lineiii{euc_kr}
Hye-Shik Chang910d8f12004-07-17 14:44:43 +0000828 {euckr, korean, ksc5601, ks_c-5601, ks_c-5601-1987, ksx1001, ks_x-1001}
Hye-Shik Chang3e2a3062004-01-17 14:29:29 +0000829 {Korean}
830
831\lineiii{gb2312}
Hye-Shik Chang910d8f12004-07-17 14:44:43 +0000832 {chinese, csiso58gb231280, euc-cn, euccn, eucgb2312-cn, gb2312-1980,
833 gb2312-80, iso-ir-58}
Hye-Shik Chang3e2a3062004-01-17 14:29:29 +0000834 {Simplified Chinese}
835
836\lineiii{gbk}
837 {936, cp936, ms936}
838 {Unified Chinese}
839
840\lineiii{gb18030}
Hye-Shik Chang910d8f12004-07-17 14:44:43 +0000841 {gb18030-2000}
Hye-Shik Chang3e2a3062004-01-17 14:29:29 +0000842 {Unified Chinese}
843
844\lineiii{hz}
Hye-Shik Chang910d8f12004-07-17 14:44:43 +0000845 {hzgb, hz-gb, hz-gb-2312}
Hye-Shik Chang3e2a3062004-01-17 14:29:29 +0000846 {Simplified Chinese}
847
848\lineiii{iso2022_jp}
Hye-Shik Chang910d8f12004-07-17 14:44:43 +0000849 {csiso2022jp, iso2022jp, iso-2022-jp}
Hye-Shik Chang3e2a3062004-01-17 14:29:29 +0000850 {Japanese}
851
852\lineiii{iso2022_jp_1}
Hye-Shik Chang910d8f12004-07-17 14:44:43 +0000853 {iso2022jp-1, iso-2022-jp-1}
Hye-Shik Chang3e2a3062004-01-17 14:29:29 +0000854 {Japanese}
855
856\lineiii{iso2022_jp_2}
Hye-Shik Chang910d8f12004-07-17 14:44:43 +0000857 {iso2022jp-2, iso-2022-jp-2}
Hye-Shik Chang3e2a3062004-01-17 14:29:29 +0000858 {Japanese, Korean, Simplified Chinese, Western Europe, Greek}
859
Hye-Shik Chang2bb146f2004-07-18 03:06:29 +0000860\lineiii{iso2022_jp_2004}
861 {iso2022jp-2004, iso-2022-jp-2004}
862 {Japanese}
863
Hye-Shik Chang3e2a3062004-01-17 14:29:29 +0000864\lineiii{iso2022_jp_3}
Hye-Shik Chang910d8f12004-07-17 14:44:43 +0000865 {iso2022jp-3, iso-2022-jp-3}
Hye-Shik Chang3e2a3062004-01-17 14:29:29 +0000866 {Japanese}
867
868\lineiii{iso2022_jp_ext}
Hye-Shik Chang910d8f12004-07-17 14:44:43 +0000869 {iso2022jp-ext, iso-2022-jp-ext}
Hye-Shik Chang3e2a3062004-01-17 14:29:29 +0000870 {Japanese}
871
872\lineiii{iso2022_kr}
Hye-Shik Chang910d8f12004-07-17 14:44:43 +0000873 {csiso2022kr, iso2022kr, iso-2022-kr}
Hye-Shik Chang3e2a3062004-01-17 14:29:29 +0000874 {Korean}
875
Martin v. Löwis5c37a772002-12-31 12:39:07 +0000876\lineiii{latin_1}
877 {iso-8859-1, iso8859-1, 8859, cp819, latin, latin1, L1}
878 {West Europe}
879
880\lineiii{iso8859_2}
881 {iso-8859-2, latin2, L2}
882 {Central and Eastern Europe}
883
884\lineiii{iso8859_3}
885 {iso-8859-3, latin3, L3}
886 {Esperanto, Maltese}
887
888\lineiii{iso8859_4}
889 {iso-8859-4, latin4, L4}
890 {Baltic languagues}
891
892\lineiii{iso8859_5}
893 {iso-8859-5, cyrillic}
894 {Bulgarian, Byelorussian, Macedonian, Russian, Serbian}
895
896\lineiii{iso8859_6}
897 {iso-8859-6, arabic}
898 {Arabic}
899
900\lineiii{iso8859_7}
901 {iso-8859-7, greek, greek8}
902 {Greek}
903
904\lineiii{iso8859_8}
905 {iso-8859-8, hebrew}
906 {Hebrew}
907
908\lineiii{iso8859_9}
909 {iso-8859-9, latin5, L5}
910 {Turkish}
911
912\lineiii{iso8859_10}
913 {iso-8859-10, latin6, L6}
914 {Nordic languages}
915
916\lineiii{iso8859_13}
917 {iso-8859-13}
918 {Baltic languages}
919
920\lineiii{iso8859_14}
921 {iso-8859-14, latin8, L8}
922 {Celtic languages}
923
924\lineiii{iso8859_15}
925 {iso-8859-15}
926 {Western Europe}
927
Hye-Shik Chang3e2a3062004-01-17 14:29:29 +0000928\lineiii{johab}
929 {cp1361, ms1361}
930 {Korean}
931
Martin v. Löwis5c37a772002-12-31 12:39:07 +0000932\lineiii{koi8_r}
933 {}
934 {Russian}
935
936\lineiii{koi8_u}
937 {}
938 {Ukrainian}
939
940\lineiii{mac_cyrillic}
941 {maccyrillic}
942 {Bulgarian, Byelorussian, Macedonian, Russian, Serbian}
943
944\lineiii{mac_greek}
945 {macgreek}
946 {Greek}
947
948\lineiii{mac_iceland}
949 {maciceland}
950 {Icelandic}
951
952\lineiii{mac_latin2}
953 {maclatin2, maccentraleurope}
954 {Central and Eastern Europe}
955
956\lineiii{mac_roman}
957 {macroman}
958 {Western Europe}
959
960\lineiii{mac_turkish}
961 {macturkish}
962 {Turkish}
963
Hye-Shik Chang5c5316f2004-03-19 08:06:07 +0000964\lineiii{ptcp154}
965 {csptcp154, pt154, cp154, cyrillic-asian}
966 {Kazakh}
967
Hye-Shik Chang3e2a3062004-01-17 14:29:29 +0000968\lineiii{shift_jis}
969 {csshiftjis, shiftjis, sjis, s_jis}
970 {Japanese}
971
Hye-Shik Chang2bb146f2004-07-18 03:06:29 +0000972\lineiii{shift_jis_2004}
973 {shiftjis2004, sjis_2004, sjis2004}
974 {Japanese}
975
Hye-Shik Chang3e2a3062004-01-17 14:29:29 +0000976\lineiii{shift_jisx0213}
977 {shiftjisx0213, sjisx0213, s_jisx0213}
978 {Japanese}
979
Martin v. Löwis5c37a772002-12-31 12:39:07 +0000980\lineiii{utf_16}
981 {U16, utf16}
982 {all languages}
983
984\lineiii{utf_16_be}
985 {UTF-16BE}
986 {all languages (BMP only)}
987
988\lineiii{utf_16_le}
989 {UTF-16LE}
990 {all languages (BMP only)}
991
992\lineiii{utf_7}
Walter Dörwald007f8df2005-10-09 19:42:27 +0000993 {U7, unicode-1-1-utf-7}
Martin v. Löwis5c37a772002-12-31 12:39:07 +0000994 {all languages}
995
996\lineiii{utf_8}
997 {U8, UTF, utf8}
998 {all languages}
999
Martin v. Löwis412ed3b2006-01-08 10:45:39 +00001000\lineiii{utf_8_sig}
1001 {}
1002 {all languages}
1003
Martin v. Löwis5c37a772002-12-31 12:39:07 +00001004\end{longtableiii}
1005
1006A number of codecs are specific to Python, so their codec names have
1007no meaning outside Python. Some of them don't convert from Unicode
1008strings to byte strings, but instead use the property of the Python
1009codecs machinery that any bijective function with one argument can be
1010considered as an encoding.
1011
1012For the codecs listed below, the result in the ``encoding'' direction
1013is always a byte string. The result of the ``decoding'' direction is
1014listed as operand type in the table.
1015
1016\begin{tableiv}{l|l|l|l}{textrm}{Codec}{Aliases}{Operand type}{Purpose}
1017
1018\lineiv{base64_codec}
1019 {base64, base-64}
1020 {byte string}
1021 {Convert operand to MIME base64}
1022
Raymond Hettinger9a80c5d2003-09-23 20:21:01 +00001023\lineiv{bz2_codec}
1024 {bz2}
1025 {byte string}
1026 {Compress the operand using bz2}
1027
Martin v. Löwis5c37a772002-12-31 12:39:07 +00001028\lineiv{hex_codec}
1029 {hex}
1030 {byte string}
Fred Draked4be7472003-04-30 15:02:07 +00001031 {Convert operand to hexadecimal representation, with two
1032 digits per byte}
Martin v. Löwis5c37a772002-12-31 12:39:07 +00001033
Martin v. Löwis2548c732003-04-18 10:39:54 +00001034\lineiv{idna}
1035 {}
1036 {Unicode string}
Fred Draked4be7472003-04-30 15:02:07 +00001037 {Implements \rfc{3490}.
Raymond Hettingeraa1178b2003-09-01 23:13:04 +00001038 \versionadded{2.3}
Fred Draked4be7472003-04-30 15:02:07 +00001039 See also \refmodule{encodings.idna}}
Martin v. Löwis2548c732003-04-18 10:39:54 +00001040
Martin v. Löwis5c37a772002-12-31 12:39:07 +00001041\lineiv{mbcs}
1042 {dbcs}
1043 {Unicode string}
1044 {Windows only: Encode operand according to the ANSI codepage (CP_ACP)}
1045
1046\lineiv{palmos}
1047 {}
1048 {Unicode string}
1049 {Encoding of PalmOS 3.5}
1050
Martin v. Löwis2548c732003-04-18 10:39:54 +00001051\lineiv{punycode}
1052 {}
1053 {Unicode string}
Fred Draked4be7472003-04-30 15:02:07 +00001054 {Implements \rfc{3492}.
1055 \versionadded{2.3}}
Martin v. Löwis2548c732003-04-18 10:39:54 +00001056
Martin v. Löwis5c37a772002-12-31 12:39:07 +00001057\lineiv{quopri_codec}
1058 {quopri, quoted-printable, quotedprintable}
1059 {byte string}
1060 {Convert operand to MIME quoted printable}
1061
1062\lineiv{raw_unicode_escape}
1063 {}
1064 {Unicode string}
Fred Draked4be7472003-04-30 15:02:07 +00001065 {Produce a string that is suitable as raw Unicode literal in
1066 Python source code}
Martin v. Löwis5c37a772002-12-31 12:39:07 +00001067
1068\lineiv{rot_13}
1069 {rot13}
1070 {byte string}
1071 {Returns the Caesar-cypher encryption of the operand}
1072
1073\lineiv{string_escape}
1074 {}
1075 {byte string}
Fred Draked4be7472003-04-30 15:02:07 +00001076 {Produce a string that is suitable as string literal in
1077 Python source code}
Martin v. Löwis5c37a772002-12-31 12:39:07 +00001078
1079\lineiv{undefined}
1080 {}
1081 {any}
Fred Draked4be7472003-04-30 15:02:07 +00001082 {Raise an exception for all conversion. Can be used as the
1083 system encoding if no automatic coercion between byte and
1084 Unicode strings is desired.}
Martin v. Löwis5c37a772002-12-31 12:39:07 +00001085
1086\lineiv{unicode_escape}
1087 {}
1088 {Unicode string}
Fred Draked4be7472003-04-30 15:02:07 +00001089 {Produce a string that is suitable as Unicode literal in
1090 Python source code}
Martin v. Löwis5c37a772002-12-31 12:39:07 +00001091
1092\lineiv{unicode_internal}
1093 {}
1094 {Unicode string}
Raymond Hettinger68804312005-01-01 00:28:46 +00001095 {Return the internal representation of the operand}
Martin v. Löwis5c37a772002-12-31 12:39:07 +00001096
1097\lineiv{uu_codec}
1098 {uu}
1099 {byte string}
1100 {Convert the operand using uuencode}
1101
1102\lineiv{zlib_codec}
1103 {zip, zlib}
1104 {byte string}
1105 {Compress the operand using gzip}
1106
1107\end{tableiv}
Martin v. Löwis2548c732003-04-18 10:39:54 +00001108
1109\subsection{\module{encodings.idna} ---
1110 Internationalized Domain Names in Applications}
1111
1112\declaremodule{standard}{encodings.idna}
1113\modulesynopsis{Internationalized Domain Names implementation}
Fred Draked4be7472003-04-30 15:02:07 +00001114% XXX The next line triggers a formatting bug, so it's commented out
1115% until that can be fixed.
1116%\moduleauthor{Martin v. L\"owis}
1117
1118\versionadded{2.3}
Martin v. Löwis2548c732003-04-18 10:39:54 +00001119
1120This module implements \rfc{3490} (Internationalized Domain Names in
1121Applications) and \rfc{3492} (Nameprep: A Stringprep Profile for
1122Internationalized Domain Names (IDN)). It builds upon the
Fred Draked24c7672003-07-16 05:17:23 +00001123\code{punycode} encoding and \refmodule{stringprep}.
Martin v. Löwis2548c732003-04-18 10:39:54 +00001124
Fred Draked4be7472003-04-30 15:02:07 +00001125These RFCs together define a protocol to support non-\ASCII{} characters
1126in domain names. A domain name containing non-\ASCII{} characters (such
Fred Draked24c7672003-07-16 05:17:23 +00001127as ``www.Alliancefran\c caise.nu'') is converted into an
Fred Draked4be7472003-04-30 15:02:07 +00001128\ASCII-compatible encoding (ACE, such as
Martin v. Löwis2548c732003-04-18 10:39:54 +00001129``www.xn--alliancefranaise-npb.nu''). The ACE form of the domain name
1130is then used in all places where arbitrary characters are not allowed
Fred Draked4be7472003-04-30 15:02:07 +00001131by the protocol, such as DNS queries, HTTP \mailheader{Host} fields, and so
Martin v. Löwis2548c732003-04-18 10:39:54 +00001132on. This conversion is carried out in the application; if possible
1133invisible to the user: The application should transparently convert
1134Unicode domain labels to IDNA on the wire, and convert back ACE labels
1135to Unicode before presenting them to the user.
1136
1137Python supports this conversion in several ways: The \code{idna} codec
1138allows to convert between Unicode and the ACE. Furthermore, the
Fred Draked24c7672003-07-16 05:17:23 +00001139\refmodule{socket} module transparently converts Unicode host names to
Martin v. Löwis2548c732003-04-18 10:39:54 +00001140ACE, so that applications need not be concerned about converting host
1141names themselves when they pass them to the socket module. On top of
1142that, modules that have host names as function parameters, such as
Fred Draked24c7672003-07-16 05:17:23 +00001143\refmodule{httplib} and \refmodule{ftplib}, accept Unicode host names
1144(\refmodule{httplib} then also transparently sends an IDNA hostname in
1145the \mailheader{Host} field if it sends that field at all).
Martin v. Löwis2548c732003-04-18 10:39:54 +00001146
1147When receiving host names from the wire (such as in reverse name
1148lookup), no automatic conversion to Unicode is performed: Applications
1149wishing to present such host names to the user should decode them to
1150Unicode.
1151
1152The module \module{encodings.idna} also implements the nameprep
1153procedure, which performs certain normalizations on host names, to
1154achieve case-insensitivity of international domain names, and to unify
1155similar characters. The nameprep functions can be used directly if
1156desired.
1157
1158\begin{funcdesc}{nameprep}{label}
1159Return the nameprepped version of \var{label}. The implementation
1160currently assumes query strings, so \code{AllowUnassigned} is
1161true.
1162\end{funcdesc}
1163
Raymond Hettingerb5155e32003-06-18 01:58:31 +00001164\begin{funcdesc}{ToASCII}{label}
Fred Draked4be7472003-04-30 15:02:07 +00001165Convert a label to \ASCII, as specified in \rfc{3490}.
Martin v. Löwis2548c732003-04-18 10:39:54 +00001166\code{UseSTD3ASCIIRules} is assumed to be false.
1167\end{funcdesc}
1168
1169\begin{funcdesc}{ToUnicode}{label}
1170Convert a label to Unicode, as specified in \rfc{3490}.
1171\end{funcdesc}
Martin v. Löwis412ed3b2006-01-08 10:45:39 +00001172
1173 \subsection{\module{encodings.utf_8_sig} ---
1174 UTF-8 codec with BOM signature}
1175\declaremodule{standard}{encodings.utf-8-sig} % XXX utf_8_sig gives TeX errors
1176\modulesynopsis{UTF-8 codec with BOM signature}
1177\moduleauthor{Walter D\"orwald}
1178
1179\versionadded{2.5}
1180
1181This module implements a variant of the UTF-8 codec: On encoding a
1182UTF-8 encoded BOM will be prepended to the UTF-8 encoded bytes. For
1183the stateful encoder this is only done once (on the first write to the
1184byte stream). For decoding an optional UTF-8 encoded BOM at the start
1185of the data will be skipped.