blob: 998964bf668a5fd973a551faa23ffd234140c251 [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
Fred Drake602aa772000-10-12 20:50:55 +0000215\subsection{Codec Base Classes}
216
217The \module{codecs} defines a set of base classes which define the
218interface 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
Walter Dörwald69652032004-09-07 20:24:22 +0000397\begin{methoddesc}{read}{\optional{size\optional{, chars}}}
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
411 The method should use a greedy read strategy meaning that it should
412 read as much data as is allowed within the definition of the encoding
413 and the given size, e.g. if optional encoding endings or state
414 markers are available on the stream, these should be read too.
Walter Dörwald69652032004-09-07 20:24:22 +0000415
416 \versionchanged[\var{chars} argument added]{2.4}
Fred Drake602aa772000-10-12 20:50:55 +0000417\end{methoddesc}
418
Walter Dörwald69652032004-09-07 20:24:22 +0000419\begin{methoddesc}{readline}{\optional{size\optional{, keepends}}}
Fred Drake602aa772000-10-12 20:50:55 +0000420 Read one line from the input stream and return the
421 decoded data.
422
Fred Drake602aa772000-10-12 20:50:55 +0000423 \var{size}, if given, is passed as size argument to the stream's
424 \method{readline()} method.
Walter Dörwald69652032004-09-07 20:24:22 +0000425
426 If \var{keepends} is false lineends will be stripped from the
427 lines returned.
428
429 \versionchanged[\var{keepends} argument added]{2.4}
Fred Drake602aa772000-10-12 20:50:55 +0000430\end{methoddesc}
431
Walter Dörwald69652032004-09-07 20:24:22 +0000432\begin{methoddesc}{readlines}{\optional{sizehint\optional{, keepends}}}
Fred Drake602aa772000-10-12 20:50:55 +0000433 Read all lines available on the input stream and return them as list
434 of lines.
435
436 Line breaks are implemented using the codec's decoder method and are
Walter Dörwald69652032004-09-07 20:24:22 +0000437 included in the list entries if \var{keepends} is true.
Fred Drake602aa772000-10-12 20:50:55 +0000438
439 \var{sizehint}, if given, is passed as \var{size} argument to the
440 stream's \method{read()} method.
441\end{methoddesc}
442
443\begin{methoddesc}{reset}{}
444 Resets the codec buffers used for keeping state.
445
446 Note that no stream repositioning should take place. This method is
447 primarily intended to be able to recover from decoding errors.
448\end{methoddesc}
449
450In addition to the above methods, the \class{StreamReader} must also
451inherit all other methods and attribute from the underlying stream.
452
453The next two base classes are included for convenience. They are not
454needed by the codec registry, but may provide useful in practice.
455
456
457\subsubsection{StreamReaderWriter Objects \label{stream-reader-writer}}
458
459The \class{StreamReaderWriter} allows wrapping streams which work in
460both read and write modes.
461
462The design is such that one can use the factory functions returned by
463the \function{lookup()} function to construct the instance.
464
465\begin{classdesc}{StreamReaderWriter}{stream, Reader, Writer, errors}
466 Creates a \class{StreamReaderWriter} instance.
467 \var{stream} must be a file-like object.
468 \var{Reader} and \var{Writer} must be factory functions or classes
469 providing the \class{StreamReader} and \class{StreamWriter} interface
470 resp.
471 Error handling is done in the same way as defined for the
472 stream readers and writers.
473\end{classdesc}
474
475\class{StreamReaderWriter} instances define the combined interfaces of
476\class{StreamReader} and \class{StreamWriter} classes. They inherit
477all other methods and attribute from the underlying stream.
478
479
480\subsubsection{StreamRecoder Objects \label{stream-recoder-objects}}
481
482The \class{StreamRecoder} provide a frontend - backend view of
483encoding data which is sometimes useful when dealing with different
484encoding environments.
485
486The design is such that one can use the factory functions returned by
487the \function{lookup()} function to construct the instance.
488
489\begin{classdesc}{StreamRecoder}{stream, encode, decode,
490 Reader, Writer, errors}
491 Creates a \class{StreamRecoder} instance which implements a two-way
492 conversion: \var{encode} and \var{decode} work on the frontend (the
493 input to \method{read()} and output of \method{write()}) while
494 \var{Reader} and \var{Writer} work on the backend (reading and
495 writing to the stream).
496
497 You can use these objects to do transparent direct recodings from
498 e.g.\ Latin-1 to UTF-8 and back.
499
500 \var{stream} must be a file-like object.
501
502 \var{encode}, \var{decode} must adhere to the \class{Codec}
503 interface, \var{Reader}, \var{Writer} must be factory functions or
Raymond Hettingerf17d65d2003-08-12 00:01:16 +0000504 classes providing objects of the \class{StreamReader} and
Fred Drake602aa772000-10-12 20:50:55 +0000505 \class{StreamWriter} interface respectively.
506
507 \var{encode} and \var{decode} are needed for the frontend
508 translation, \var{Reader} and \var{Writer} for the backend
509 translation. The intermediate format used is determined by the two
510 sets of codecs, e.g. the Unicode codecs will use Unicode as
511 intermediate encoding.
512
513 Error handling is done in the same way as defined for the
514 stream readers and writers.
515\end{classdesc}
516
517\class{StreamRecoder} instances define the combined interfaces of
518\class{StreamReader} and \class{StreamWriter} classes. They inherit
519all other methods and attribute from the underlying stream.
520
Skip Montanaroecf7a522004-07-01 19:26:04 +0000521\subsection{Standard Encodings\label{standard-encodings}}
Martin v. Löwis5c37a772002-12-31 12:39:07 +0000522
523Python comes with a number of codecs builtin, either implemented as C
524functions, or with dictionaries as mapping tables. The following table
525lists the codecs by name, together with a few common aliases, and the
526languages for which the encoding is likely used. Neither the list of
527aliases nor the list of languages is meant to be exhaustive. Notice
528that spelling alternatives that only differ in case or use a hyphen
529instead of an underscore are also valid aliases.
530
531Many of the character sets support the same languages. They vary in
532individual characters (e.g. whether the EURO SIGN is supported or
533not), and in the assignment of characters to code positions. For the
534European languages in particular, the following variants typically
535exist:
536
537\begin{itemize}
538\item an ISO 8859 codeset
539\item a Microsoft Windows code page, which is typically derived from
540 a 8859 codeset, but replaces control characters with additional
541 graphic characters
542\item an IBM EBCDIC code page
Fred Draked4be7472003-04-30 15:02:07 +0000543\item an IBM PC code page, which is \ASCII{} compatible
Martin v. Löwis5c37a772002-12-31 12:39:07 +0000544\end{itemize}
545
546\begin{longtableiii}{l|l|l}{textrm}{Codec}{Aliases}{Languages}
547
548\lineiii{ascii}
549 {646, us-ascii}
550 {English}
551
Hye-Shik Chang3e2a3062004-01-17 14:29:29 +0000552\lineiii{big5}
Hye-Shik Chang910d8f12004-07-17 14:44:43 +0000553 {big5-tw, csbig5}
Hye-Shik Chang3e2a3062004-01-17 14:29:29 +0000554 {Traditional Chinese}
555
Hye-Shik Chang2bb146f2004-07-18 03:06:29 +0000556\lineiii{big5hkscs}
557 {big5-hkscs, hkscs}
558 {Traditional Chinese}
559
Martin v. Löwis5c37a772002-12-31 12:39:07 +0000560\lineiii{cp037}
561 {IBM037, IBM039}
562 {English}
563
564\lineiii{cp424}
565 {EBCDIC-CP-HE, IBM424}
566 {Hebrew}
567
568\lineiii{cp437}
569 {437, IBM437}
570 {English}
571
572\lineiii{cp500}
573 {EBCDIC-CP-BE, EBCDIC-CP-CH, IBM500}
574 {Western Europe}
575
576\lineiii{cp737}
577 {}
578 {Greek}
579
580\lineiii{cp775}
581 {IBM775}
582 {Baltic languages}
583
584\lineiii{cp850}
585 {850, IBM850}
586 {Western Europe}
587
588\lineiii{cp852}
589 {852, IBM852}
590 {Central and Eastern Europe}
591
592\lineiii{cp855}
593 {855, IBM855}
594 {Bulgarian, Byelorussian, Macedonian, Russian, Serbian}
595
596\lineiii{cp856}
597 {}
598 {Hebrew}
599
600\lineiii{cp857}
601 {857, IBM857}
602 {Turkish}
603
604\lineiii{cp860}
605 {860, IBM860}
606 {Portuguese}
607
608\lineiii{cp861}
609 {861, CP-IS, IBM861}
610 {Icelandic}
611
612\lineiii{cp862}
613 {862, IBM862}
614 {Hebrew}
615
616\lineiii{cp863}
617 {863, IBM863}
618 {Canadian}
619
620\lineiii{cp864}
621 {IBM864}
622 {Arabic}
623
624\lineiii{cp865}
625 {865, IBM865}
626 {Danish, Norwegian}
627
Skip Montanaro78bace72004-07-02 02:14:34 +0000628\lineiii{cp866}
629 {866, IBM866}
630 {Russian}
631
Martin v. Löwis5c37a772002-12-31 12:39:07 +0000632\lineiii{cp869}
633 {869, CP-GR, IBM869}
634 {Greek}
635
636\lineiii{cp874}
637 {}
638 {Thai}
639
640\lineiii{cp875}
641 {}
642 {Greek}
643
Hye-Shik Chang3e2a3062004-01-17 14:29:29 +0000644\lineiii{cp932}
Hye-Shik Chang910d8f12004-07-17 14:44:43 +0000645 {932, ms932, mskanji, ms-kanji}
Hye-Shik Chang3e2a3062004-01-17 14:29:29 +0000646 {Japanese}
647
648\lineiii{cp949}
649 {949, ms949, uhc}
650 {Korean}
651
652\lineiii{cp950}
653 {950, ms950}
654 {Traditional Chinese}
655
Martin v. Löwis5c37a772002-12-31 12:39:07 +0000656\lineiii{cp1006}
657 {}
658 {Urdu}
659
660\lineiii{cp1026}
661 {ibm1026}
662 {Turkish}
663
664\lineiii{cp1140}
665 {ibm1140}
666 {Western Europe}
667
668\lineiii{cp1250}
669 {windows-1250}
670 {Central and Eastern Europe}
671
672\lineiii{cp1251}
673 {windows-1251}
674 {Bulgarian, Byelorussian, Macedonian, Russian, Serbian}
675
676\lineiii{cp1252}
677 {windows-1252}
678 {Western Europe}
679
680\lineiii{cp1253}
681 {windows-1253}
682 {Greek}
683
684\lineiii{cp1254}
685 {windows-1254}
686 {Turkish}
687
688\lineiii{cp1255}
689 {windows-1255}
690 {Hebrew}
691
692\lineiii{cp1256}
693 {windows1256}
694 {Arabic}
695
696\lineiii{cp1257}
697 {windows-1257}
698 {Baltic languages}
699
700\lineiii{cp1258}
701 {windows-1258}
702 {Vietnamese}
703
Hye-Shik Chang3e2a3062004-01-17 14:29:29 +0000704\lineiii{euc_jp}
Hye-Shik Chang910d8f12004-07-17 14:44:43 +0000705 {eucjp, ujis, u-jis}
Hye-Shik Chang3e2a3062004-01-17 14:29:29 +0000706 {Japanese}
707
Hye-Shik Chang2bb146f2004-07-18 03:06:29 +0000708\lineiii{euc_jis_2004}
709 {jisx0213, eucjis2004}
710 {Japanese}
711
Hye-Shik Chang3e2a3062004-01-17 14:29:29 +0000712\lineiii{euc_jisx0213}
Hye-Shik Chang2bb146f2004-07-18 03:06:29 +0000713 {eucjisx0213}
Hye-Shik Chang3e2a3062004-01-17 14:29:29 +0000714 {Japanese}
715
716\lineiii{euc_kr}
Hye-Shik Chang910d8f12004-07-17 14:44:43 +0000717 {euckr, korean, ksc5601, ks_c-5601, ks_c-5601-1987, ksx1001, ks_x-1001}
Hye-Shik Chang3e2a3062004-01-17 14:29:29 +0000718 {Korean}
719
720\lineiii{gb2312}
Hye-Shik Chang910d8f12004-07-17 14:44:43 +0000721 {chinese, csiso58gb231280, euc-cn, euccn, eucgb2312-cn, gb2312-1980,
722 gb2312-80, iso-ir-58}
Hye-Shik Chang3e2a3062004-01-17 14:29:29 +0000723 {Simplified Chinese}
724
725\lineiii{gbk}
726 {936, cp936, ms936}
727 {Unified Chinese}
728
729\lineiii{gb18030}
Hye-Shik Chang910d8f12004-07-17 14:44:43 +0000730 {gb18030-2000}
Hye-Shik Chang3e2a3062004-01-17 14:29:29 +0000731 {Unified Chinese}
732
733\lineiii{hz}
Hye-Shik Chang910d8f12004-07-17 14:44:43 +0000734 {hzgb, hz-gb, hz-gb-2312}
Hye-Shik Chang3e2a3062004-01-17 14:29:29 +0000735 {Simplified Chinese}
736
737\lineiii{iso2022_jp}
Hye-Shik Chang910d8f12004-07-17 14:44:43 +0000738 {csiso2022jp, iso2022jp, iso-2022-jp}
Hye-Shik Chang3e2a3062004-01-17 14:29:29 +0000739 {Japanese}
740
741\lineiii{iso2022_jp_1}
Hye-Shik Chang910d8f12004-07-17 14:44:43 +0000742 {iso2022jp-1, iso-2022-jp-1}
Hye-Shik Chang3e2a3062004-01-17 14:29:29 +0000743 {Japanese}
744
745\lineiii{iso2022_jp_2}
Hye-Shik Chang910d8f12004-07-17 14:44:43 +0000746 {iso2022jp-2, iso-2022-jp-2}
Hye-Shik Chang3e2a3062004-01-17 14:29:29 +0000747 {Japanese, Korean, Simplified Chinese, Western Europe, Greek}
748
Hye-Shik Chang2bb146f2004-07-18 03:06:29 +0000749\lineiii{iso2022_jp_2004}
750 {iso2022jp-2004, iso-2022-jp-2004}
751 {Japanese}
752
Hye-Shik Chang3e2a3062004-01-17 14:29:29 +0000753\lineiii{iso2022_jp_3}
Hye-Shik Chang910d8f12004-07-17 14:44:43 +0000754 {iso2022jp-3, iso-2022-jp-3}
Hye-Shik Chang3e2a3062004-01-17 14:29:29 +0000755 {Japanese}
756
757\lineiii{iso2022_jp_ext}
Hye-Shik Chang910d8f12004-07-17 14:44:43 +0000758 {iso2022jp-ext, iso-2022-jp-ext}
Hye-Shik Chang3e2a3062004-01-17 14:29:29 +0000759 {Japanese}
760
761\lineiii{iso2022_kr}
Hye-Shik Chang910d8f12004-07-17 14:44:43 +0000762 {csiso2022kr, iso2022kr, iso-2022-kr}
Hye-Shik Chang3e2a3062004-01-17 14:29:29 +0000763 {Korean}
764
Martin v. Löwis5c37a772002-12-31 12:39:07 +0000765\lineiii{latin_1}
766 {iso-8859-1, iso8859-1, 8859, cp819, latin, latin1, L1}
767 {West Europe}
768
769\lineiii{iso8859_2}
770 {iso-8859-2, latin2, L2}
771 {Central and Eastern Europe}
772
773\lineiii{iso8859_3}
774 {iso-8859-3, latin3, L3}
775 {Esperanto, Maltese}
776
777\lineiii{iso8859_4}
778 {iso-8859-4, latin4, L4}
779 {Baltic languagues}
780
781\lineiii{iso8859_5}
782 {iso-8859-5, cyrillic}
783 {Bulgarian, Byelorussian, Macedonian, Russian, Serbian}
784
785\lineiii{iso8859_6}
786 {iso-8859-6, arabic}
787 {Arabic}
788
789\lineiii{iso8859_7}
790 {iso-8859-7, greek, greek8}
791 {Greek}
792
793\lineiii{iso8859_8}
794 {iso-8859-8, hebrew}
795 {Hebrew}
796
797\lineiii{iso8859_9}
798 {iso-8859-9, latin5, L5}
799 {Turkish}
800
801\lineiii{iso8859_10}
802 {iso-8859-10, latin6, L6}
803 {Nordic languages}
804
805\lineiii{iso8859_13}
806 {iso-8859-13}
807 {Baltic languages}
808
809\lineiii{iso8859_14}
810 {iso-8859-14, latin8, L8}
811 {Celtic languages}
812
813\lineiii{iso8859_15}
814 {iso-8859-15}
815 {Western Europe}
816
Hye-Shik Chang3e2a3062004-01-17 14:29:29 +0000817\lineiii{johab}
818 {cp1361, ms1361}
819 {Korean}
820
Martin v. Löwis5c37a772002-12-31 12:39:07 +0000821\lineiii{koi8_r}
822 {}
823 {Russian}
824
825\lineiii{koi8_u}
826 {}
827 {Ukrainian}
828
829\lineiii{mac_cyrillic}
830 {maccyrillic}
831 {Bulgarian, Byelorussian, Macedonian, Russian, Serbian}
832
833\lineiii{mac_greek}
834 {macgreek}
835 {Greek}
836
837\lineiii{mac_iceland}
838 {maciceland}
839 {Icelandic}
840
841\lineiii{mac_latin2}
842 {maclatin2, maccentraleurope}
843 {Central and Eastern Europe}
844
845\lineiii{mac_roman}
846 {macroman}
847 {Western Europe}
848
849\lineiii{mac_turkish}
850 {macturkish}
851 {Turkish}
852
Hye-Shik Chang5c5316f2004-03-19 08:06:07 +0000853\lineiii{ptcp154}
854 {csptcp154, pt154, cp154, cyrillic-asian}
855 {Kazakh}
856
Hye-Shik Chang3e2a3062004-01-17 14:29:29 +0000857\lineiii{shift_jis}
858 {csshiftjis, shiftjis, sjis, s_jis}
859 {Japanese}
860
Hye-Shik Chang2bb146f2004-07-18 03:06:29 +0000861\lineiii{shift_jis_2004}
862 {shiftjis2004, sjis_2004, sjis2004}
863 {Japanese}
864
Hye-Shik Chang3e2a3062004-01-17 14:29:29 +0000865\lineiii{shift_jisx0213}
866 {shiftjisx0213, sjisx0213, s_jisx0213}
867 {Japanese}
868
Martin v. Löwis5c37a772002-12-31 12:39:07 +0000869\lineiii{utf_16}
870 {U16, utf16}
871 {all languages}
872
873\lineiii{utf_16_be}
874 {UTF-16BE}
875 {all languages (BMP only)}
876
877\lineiii{utf_16_le}
878 {UTF-16LE}
879 {all languages (BMP only)}
880
881\lineiii{utf_7}
882 {U7}
883 {all languages}
884
885\lineiii{utf_8}
886 {U8, UTF, utf8}
887 {all languages}
888
889\end{longtableiii}
890
891A number of codecs are specific to Python, so their codec names have
892no meaning outside Python. Some of them don't convert from Unicode
893strings to byte strings, but instead use the property of the Python
894codecs machinery that any bijective function with one argument can be
895considered as an encoding.
896
897For the codecs listed below, the result in the ``encoding'' direction
898is always a byte string. The result of the ``decoding'' direction is
899listed as operand type in the table.
900
901\begin{tableiv}{l|l|l|l}{textrm}{Codec}{Aliases}{Operand type}{Purpose}
902
903\lineiv{base64_codec}
904 {base64, base-64}
905 {byte string}
906 {Convert operand to MIME base64}
907
Raymond Hettinger9a80c5d2003-09-23 20:21:01 +0000908\lineiv{bz2_codec}
909 {bz2}
910 {byte string}
911 {Compress the operand using bz2}
912
Martin v. Löwis5c37a772002-12-31 12:39:07 +0000913\lineiv{hex_codec}
914 {hex}
915 {byte string}
Fred Draked4be7472003-04-30 15:02:07 +0000916 {Convert operand to hexadecimal representation, with two
917 digits per byte}
Martin v. Löwis5c37a772002-12-31 12:39:07 +0000918
Martin v. Löwis2548c732003-04-18 10:39:54 +0000919\lineiv{idna}
920 {}
921 {Unicode string}
Fred Draked4be7472003-04-30 15:02:07 +0000922 {Implements \rfc{3490}.
Raymond Hettingeraa1178b2003-09-01 23:13:04 +0000923 \versionadded{2.3}
Fred Draked4be7472003-04-30 15:02:07 +0000924 See also \refmodule{encodings.idna}}
Martin v. Löwis2548c732003-04-18 10:39:54 +0000925
Martin v. Löwis5c37a772002-12-31 12:39:07 +0000926\lineiv{mbcs}
927 {dbcs}
928 {Unicode string}
929 {Windows only: Encode operand according to the ANSI codepage (CP_ACP)}
930
931\lineiv{palmos}
932 {}
933 {Unicode string}
934 {Encoding of PalmOS 3.5}
935
Martin v. Löwis2548c732003-04-18 10:39:54 +0000936\lineiv{punycode}
937 {}
938 {Unicode string}
Fred Draked4be7472003-04-30 15:02:07 +0000939 {Implements \rfc{3492}.
940 \versionadded{2.3}}
Martin v. Löwis2548c732003-04-18 10:39:54 +0000941
Martin v. Löwis5c37a772002-12-31 12:39:07 +0000942\lineiv{quopri_codec}
943 {quopri, quoted-printable, quotedprintable}
944 {byte string}
945 {Convert operand to MIME quoted printable}
946
947\lineiv{raw_unicode_escape}
948 {}
949 {Unicode string}
Fred Draked4be7472003-04-30 15:02:07 +0000950 {Produce a string that is suitable as raw Unicode literal in
951 Python source code}
Martin v. Löwis5c37a772002-12-31 12:39:07 +0000952
953\lineiv{rot_13}
954 {rot13}
955 {byte string}
956 {Returns the Caesar-cypher encryption of the operand}
957
958\lineiv{string_escape}
959 {}
960 {byte string}
Fred Draked4be7472003-04-30 15:02:07 +0000961 {Produce a string that is suitable as string literal in
962 Python source code}
Martin v. Löwis5c37a772002-12-31 12:39:07 +0000963
964\lineiv{undefined}
965 {}
966 {any}
Fred Draked4be7472003-04-30 15:02:07 +0000967 {Raise an exception for all conversion. Can be used as the
968 system encoding if no automatic coercion between byte and
969 Unicode strings is desired.}
Martin v. Löwis5c37a772002-12-31 12:39:07 +0000970
971\lineiv{unicode_escape}
972 {}
973 {Unicode string}
Fred Draked4be7472003-04-30 15:02:07 +0000974 {Produce a string that is suitable as Unicode literal in
975 Python source code}
Martin v. Löwis5c37a772002-12-31 12:39:07 +0000976
977\lineiv{unicode_internal}
978 {}
979 {Unicode string}
980 {Return the internal represenation of the operand}
981
982\lineiv{uu_codec}
983 {uu}
984 {byte string}
985 {Convert the operand using uuencode}
986
987\lineiv{zlib_codec}
988 {zip, zlib}
989 {byte string}
990 {Compress the operand using gzip}
991
992\end{tableiv}
Martin v. Löwis2548c732003-04-18 10:39:54 +0000993
994\subsection{\module{encodings.idna} ---
995 Internationalized Domain Names in Applications}
996
997\declaremodule{standard}{encodings.idna}
998\modulesynopsis{Internationalized Domain Names implementation}
Fred Draked4be7472003-04-30 15:02:07 +0000999% XXX The next line triggers a formatting bug, so it's commented out
1000% until that can be fixed.
1001%\moduleauthor{Martin v. L\"owis}
1002
1003\versionadded{2.3}
Martin v. Löwis2548c732003-04-18 10:39:54 +00001004
1005This module implements \rfc{3490} (Internationalized Domain Names in
1006Applications) and \rfc{3492} (Nameprep: A Stringprep Profile for
1007Internationalized Domain Names (IDN)). It builds upon the
Fred Draked24c7672003-07-16 05:17:23 +00001008\code{punycode} encoding and \refmodule{stringprep}.
Martin v. Löwis2548c732003-04-18 10:39:54 +00001009
Fred Draked4be7472003-04-30 15:02:07 +00001010These RFCs together define a protocol to support non-\ASCII{} characters
1011in domain names. A domain name containing non-\ASCII{} characters (such
Fred Draked24c7672003-07-16 05:17:23 +00001012as ``www.Alliancefran\c caise.nu'') is converted into an
Fred Draked4be7472003-04-30 15:02:07 +00001013\ASCII-compatible encoding (ACE, such as
Martin v. Löwis2548c732003-04-18 10:39:54 +00001014``www.xn--alliancefranaise-npb.nu''). The ACE form of the domain name
1015is then used in all places where arbitrary characters are not allowed
Fred Draked4be7472003-04-30 15:02:07 +00001016by the protocol, such as DNS queries, HTTP \mailheader{Host} fields, and so
Martin v. Löwis2548c732003-04-18 10:39:54 +00001017on. This conversion is carried out in the application; if possible
1018invisible to the user: The application should transparently convert
1019Unicode domain labels to IDNA on the wire, and convert back ACE labels
1020to Unicode before presenting them to the user.
1021
1022Python supports this conversion in several ways: The \code{idna} codec
1023allows to convert between Unicode and the ACE. Furthermore, the
Fred Draked24c7672003-07-16 05:17:23 +00001024\refmodule{socket} module transparently converts Unicode host names to
Martin v. Löwis2548c732003-04-18 10:39:54 +00001025ACE, so that applications need not be concerned about converting host
1026names themselves when they pass them to the socket module. On top of
1027that, modules that have host names as function parameters, such as
Fred Draked24c7672003-07-16 05:17:23 +00001028\refmodule{httplib} and \refmodule{ftplib}, accept Unicode host names
1029(\refmodule{httplib} then also transparently sends an IDNA hostname in
1030the \mailheader{Host} field if it sends that field at all).
Martin v. Löwis2548c732003-04-18 10:39:54 +00001031
1032When receiving host names from the wire (such as in reverse name
1033lookup), no automatic conversion to Unicode is performed: Applications
1034wishing to present such host names to the user should decode them to
1035Unicode.
1036
1037The module \module{encodings.idna} also implements the nameprep
1038procedure, which performs certain normalizations on host names, to
1039achieve case-insensitivity of international domain names, and to unify
1040similar characters. The nameprep functions can be used directly if
1041desired.
1042
1043\begin{funcdesc}{nameprep}{label}
1044Return the nameprepped version of \var{label}. The implementation
1045currently assumes query strings, so \code{AllowUnassigned} is
1046true.
1047\end{funcdesc}
1048
Raymond Hettingerb5155e32003-06-18 01:58:31 +00001049\begin{funcdesc}{ToASCII}{label}
Fred Draked4be7472003-04-30 15:02:07 +00001050Convert a label to \ASCII, as specified in \rfc{3490}.
Martin v. Löwis2548c732003-04-18 10:39:54 +00001051\code{UseSTD3ASCIIRules} is assumed to be false.
1052\end{funcdesc}
1053
1054\begin{funcdesc}{ToUnicode}{label}
1055Convert a label to Unicode, as specified in \rfc{3490}.
1056\end{funcdesc}