blob: d4354401cb8330d066f59934d18a37d6dc47e3d7 [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}
8
9
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
48 data with a suitable replacement marker, such as \character{?}) and
49 \code{'ignore'} (ignore malformed data and continue without further
50 notice).
Fred Drakeb7979c72000-04-06 14:21:58 +000051
52In case a search function cannot find a given encoding, it should
Fred Drake69ca9502000-04-06 16:09:59 +000053return \code{None}.
Fred Drakeb7979c72000-04-06 14:21:58 +000054\end{funcdesc}
55
56\begin{funcdesc}{lookup}{encoding}
57Looks up a codec tuple in the Python codec registry and returns the
58function tuple as defined above.
59
60Encodings are first looked up in the registry's cache. If not found,
61the list of registered search functions is scanned. If no codecs tuple
Fred Drake69ca9502000-04-06 16:09:59 +000062is found, a \exception{LookupError} is raised. Otherwise, the codecs
63tuple is stored in the cache and returned to the caller.
Fred Drakeb7979c72000-04-06 14:21:58 +000064\end{funcdesc}
65
Skip Montanarob02ea652002-04-17 19:33:06 +000066To simplify access to the various codecs, the module provides these
Marc-André Lemburg494f2ae2001-09-19 11:33:31 +000067additional functions which use \function{lookup()} for the codec
68lookup:
69
70\begin{funcdesc}{getencoder}{encoding}
71Lookup up the codec for the given encoding and return its encoder
72function.
73
74Raises a \exception{LookupError} in case the encoding cannot be found.
75\end{funcdesc}
76
77\begin{funcdesc}{getdecoder}{encoding}
78Lookup up the codec for the given encoding and return its decoder
79function.
80
81Raises a \exception{LookupError} in case the encoding cannot be found.
82\end{funcdesc}
83
84\begin{funcdesc}{getreader}{encoding}
85Lookup up the codec for the given encoding and return its StreamReader
86class or factory function.
87
88Raises a \exception{LookupError} in case the encoding cannot be found.
89\end{funcdesc}
90
91\begin{funcdesc}{getwriter}{encoding}
92Lookup up the codec for the given encoding and return its StreamWriter
93class or factory function.
94
95Raises a \exception{LookupError} in case the encoding cannot be found.
96\end{funcdesc}
97
Walter Dörwald3aeb6322002-09-02 13:14:32 +000098\begin{funcdesc}{register_error}{name, error_handler}
99Register the error handling function \var{error_handler} under the
Raymond Hettinger8a64d402002-09-08 22:26:13 +0000100name \var{name}. \var{error_handler} will be called during encoding
Walter Dörwald3aeb6322002-09-02 13:14:32 +0000101and decoding in case of an error, when \var{name} is specified as the
102errors parameter. \var{error_handler} will be called with an
103\exception{UnicodeEncodeError}, \exception{UnicodeDecodeError} or
104\exception{UnicodeTranslateError} instance and must return a tuple
105with a replacement for the unencodable/undecodable part of the input
106and a position where encoding/decoding should continue.
107\end{funcdesc}
108
109\begin{funcdesc}{lookup_error}{name}
110Return the error handler previously register under the name \var{name}.
111
112Raises a \exception{LookupError} in case the handler cannot be found.
113\end{funcdesc}
114
115\begin{funcdesc}{strict_errors}{exception}
116Implements the \code{strict} error handling.
117\end{funcdesc}
118
119\begin{funcdesc}{replace_errors}{exception}
120Implements the \code{replace} error handling.
121\end{funcdesc}
122
123\begin{funcdesc}{ignore_errors}{exception}
124Implements the \code{ignore} error handling.
125\end{funcdesc}
126
127\begin{funcdesc}{xmlcharrefreplace_errors_errors}{exception}
128Implements the \code{xmlcharrefreplace} error handling.
129\end{funcdesc}
130
131\begin{funcdesc}{backslashreplace_errors_errors}{exception}
132Implements the \code{backslashreplace} error handling.
133\end{funcdesc}
134
Walter Dörwald1a7a8942002-11-02 13:32:07 +0000135To simplify working with encoded files or stream, the module
136also defines these utility functions:
137
Fred Drakee1b304d2000-07-24 19:35:52 +0000138\begin{funcdesc}{open}{filename, mode\optional{, encoding\optional{,
139 errors\optional{, buffering}}}}
Fred Drakeb7979c72000-04-06 14:21:58 +0000140Open an encoded file using the given \var{mode} and return
141a wrapped version providing transparent encoding/decoding.
142
Fred Drake0aa811c2001-10-20 04:24:09 +0000143\note{The wrapped version will only accept the object format
Fred Drakee1b304d2000-07-24 19:35:52 +0000144defined by the codecs, i.e.\ Unicode objects for most built-in
145codecs. Output is also codec-dependent and will usually be Unicode as
Fred Drake0aa811c2001-10-20 04:24:09 +0000146well.}
Fred Drakeb7979c72000-04-06 14:21:58 +0000147
148\var{encoding} specifies the encoding which is to be used for the
149the file.
150
151\var{errors} may be given to define the error handling. It defaults
Fred Drakee1b304d2000-07-24 19:35:52 +0000152to \code{'strict'} which causes a \exception{ValueError} to be raised
153in case an encoding error occurs.
Fred Drakeb7979c72000-04-06 14:21:58 +0000154
Fred Drake69ca9502000-04-06 16:09:59 +0000155\var{buffering} has the same meaning as for the built-in
156\function{open()} function. It defaults to line buffered.
Fred Drakeb7979c72000-04-06 14:21:58 +0000157\end{funcdesc}
158
Fred Drakee1b304d2000-07-24 19:35:52 +0000159\begin{funcdesc}{EncodedFile}{file, input\optional{,
160 output\optional{, errors}}}
Fred Drakeb7979c72000-04-06 14:21:58 +0000161Return a wrapped version of file which provides transparent
162encoding translation.
163
164Strings written to the wrapped file are interpreted according to the
165given \var{input} encoding and then written to the original file as
Fred Drakee1b304d2000-07-24 19:35:52 +0000166strings using the \var{output} encoding. The intermediate encoding will
Fred Drakeb7979c72000-04-06 14:21:58 +0000167usually be Unicode but depends on the specified codecs.
168
Fred Drakee1b304d2000-07-24 19:35:52 +0000169If \var{output} is not given, it defaults to \var{input}.
Fred Drakeb7979c72000-04-06 14:21:58 +0000170
171\var{errors} may be given to define the error handling. It defaults to
Fred Drakee1b304d2000-07-24 19:35:52 +0000172\code{'strict'}, which causes \exception{ValueError} to be raised in case
Fred Drakeb7979c72000-04-06 14:21:58 +0000173an encoding error occurs.
174\end{funcdesc}
175
Fred Drakeb7979c72000-04-06 14:21:58 +0000176The module also provides the following constants which are useful
177for reading and writing to platform dependent files:
178
179\begin{datadesc}{BOM}
180\dataline{BOM_BE}
181\dataline{BOM_LE}
Walter Dörwald474458d2002-06-04 15:16:29 +0000182\dataline{BOM_UTF8}
183\dataline{BOM_UTF16}
184\dataline{BOM_UTF16_BE}
185\dataline{BOM_UTF16_LE}
186\dataline{BOM_UTF32}
187\dataline{BOM_UTF32_BE}
188\dataline{BOM_UTF32_LE}
189These constants define various encodings of the Unicode byte order mark
190(BOM) used in UTF-16 and UTF-32 data streams to indicate the byte order
191used in the stream or file and in UTF-8 as a Unicode signature.
192\constant{BOM_UTF16} is either \constant{BOM_UTF16_BE} or
193\constant{BOM_UTF16_LE} depending on the platform's native byte order,
194\constant{BOM} is an alias for \constant{BOM_UTF16}, \constant{BOM_LE}
195for \constant{BOM_UTF16_LE} and \constant{BOM_BE} for \constant{BOM_UTF16_BE}.
196The others represent the BOM in UTF-8 and UTF-32 encodings.
Fred Drakeb7979c72000-04-06 14:21:58 +0000197\end{datadesc}
198
Fred Drakedc40ac02001-01-22 20:17:54 +0000199
200\begin{seealso}
201 \seeurl{http://sourceforge.net/projects/python-codecs/}{A
202 SourceForge project working on additional support for Asian
203 codecs for use with Python. They are in the early stages of
204 development at the time of this writing --- look in their
205 FTP area for downloadable files.}
206\end{seealso}
207
208
Fred Drake602aa772000-10-12 20:50:55 +0000209\subsection{Codec Base Classes}
210
211The \module{codecs} defines a set of base classes which define the
212interface and can also be used to easily write you own codecs for use
213in Python.
214
215Each codec has to define four interfaces to make it usable as codec in
216Python: stateless encoder, stateless decoder, stream reader and stream
217writer. The stream reader and writers typically reuse the stateless
218encoder/decoder to implement the file protocols.
219
220The \class{Codec} class defines the interface for stateless
221encoders/decoders.
222
223To simplify and standardize error handling, the \method{encode()} and
224\method{decode()} methods may implement different error handling
225schemes by providing the \var{errors} string argument. The following
226string values are defined and implemented by all standard Python
227codecs:
228
Fred Drakedc40ac02001-01-22 20:17:54 +0000229\begin{tableii}{l|l}{code}{Value}{Meaning}
230 \lineii{'strict'}{Raise \exception{ValueError} (or a subclass);
231 this is the default.}
232 \lineii{'ignore'}{Ignore the character and continue with the next.}
233 \lineii{'replace'}{Replace with a suitable replacement character;
234 Python will use the official U+FFFD REPLACEMENT
235 CHARACTER for the built-in Unicode codecs.}
236\end{tableii}
Fred Drake602aa772000-10-12 20:50:55 +0000237
238
239\subsubsection{Codec Objects \label{codec-objects}}
240
241The \class{Codec} class defines these methods which also define the
242function interfaces of the stateless encoder and decoder:
243
244\begin{methoddesc}{encode}{input\optional{, errors}}
245 Encodes the object \var{input} and returns a tuple (output object,
Skip Montanaro6c7bc312002-04-16 15:12:10 +0000246 length consumed). While codecs are not restricted to use with Unicode, in
247 a Unicode context, encoding converts a Unicode object to a plain string
248 using a particular character set encoding (e.g., \code{cp1252} or
249 \code{iso-8859-1}).
Fred Drake602aa772000-10-12 20:50:55 +0000250
251 \var{errors} defines the error handling to apply. It defaults to
252 \code{'strict'} handling.
253
254 The method may not store state in the \class{Codec} instance. Use
255 \class{StreamCodec} for codecs which have to keep state in order to
256 make encoding/decoding efficient.
257
258 The encoder must be able to handle zero length input and return an
259 empty object of the output object type in this situation.
260\end{methoddesc}
261
262\begin{methoddesc}{decode}{input\optional{, errors}}
263 Decodes the object \var{input} and returns a tuple (output object,
Skip Montanaro6c7bc312002-04-16 15:12:10 +0000264 length consumed). In a Unicode context, decoding converts a plain string
265 encoded using a particular character set encoding to a Unicode object.
Fred Drake602aa772000-10-12 20:50:55 +0000266
267 \var{input} must be an object which provides the \code{bf_getreadbuf}
268 buffer slot. Python strings, buffer objects and memory mapped files
269 are examples of objects providing this slot.
270
271 \var{errors} defines the error handling to apply. It defaults to
272 \code{'strict'} handling.
273
274 The method may not store state in the \class{Codec} instance. Use
275 \class{StreamCodec} for codecs which have to keep state in order to
276 make encoding/decoding efficient.
277
278 The decoder must be able to handle zero length input and return an
279 empty object of the output object type in this situation.
280\end{methoddesc}
281
282The \class{StreamWriter} and \class{StreamReader} classes provide
283generic working interfaces which can be used to implement new
284encodings submodules very easily. See \module{encodings.utf_8} for an
285example on how this is done.
286
287
288\subsubsection{StreamWriter Objects \label{stream-writer-objects}}
289
290The \class{StreamWriter} class is a subclass of \class{Codec} and
291defines the following methods which every stream writer must define in
292order to be compatible to the Python codec registry.
293
294\begin{classdesc}{StreamWriter}{stream\optional{, errors}}
295 Constructor for a \class{StreamWriter} instance.
296
297 All stream writers must provide this constructor interface. They are
298 free to add additional keyword arguments, but only the ones defined
299 here are used by the Python codec registry.
300
301 \var{stream} must be a file-like object open for writing (binary)
302 data.
303
304 The \class{StreamWriter} may implement different error handling
305 schemes by providing the \var{errors} keyword argument. These
306 parameters are defined:
307
308 \begin{itemize}
309 \item \code{'strict'} Raise \exception{ValueError} (or a subclass);
310 this is the default.
311 \item \code{'ignore'} Ignore the character and continue with the next.
312 \item \code{'replace'} Replace with a suitable replacement character
313 \end{itemize}
314\end{classdesc}
315
316\begin{methoddesc}{write}{object}
317 Writes the object's contents encoded to the stream.
318\end{methoddesc}
319
320\begin{methoddesc}{writelines}{list}
321 Writes the concatenated list of strings to the stream (possibly by
322 reusing the \method{write()} method).
323\end{methoddesc}
324
325\begin{methoddesc}{reset}{}
326 Flushes and resets the codec buffers used for keeping state.
327
328 Calling this method should ensure that the data on the output is put
329 into a clean state, that allows appending of new fresh data without
330 having to rescan the whole stream to recover state.
331\end{methoddesc}
332
333In addition to the above methods, the \class{StreamWriter} must also
334inherit all other methods and attribute from the underlying stream.
335
336
337\subsubsection{StreamReader Objects \label{stream-reader-objects}}
338
339The \class{StreamReader} class is a subclass of \class{Codec} and
340defines the following methods which every stream reader must define in
341order to be compatible to the Python codec registry.
342
343\begin{classdesc}{StreamReader}{stream\optional{, errors}}
344 Constructor for a \class{StreamReader} instance.
345
346 All stream readers must provide this constructor interface. They are
347 free to add additional keyword arguments, but only the ones defined
348 here are used by the Python codec registry.
349
350 \var{stream} must be a file-like object open for reading (binary)
351 data.
352
353 The \class{StreamReader} may implement different error handling
354 schemes by providing the \var{errors} keyword argument. These
355 parameters are defined:
356
357 \begin{itemize}
358 \item \code{'strict'} Raise \exception{ValueError} (or a subclass);
359 this is the default.
360 \item \code{'ignore'} Ignore the character and continue with the next.
361 \item \code{'replace'} Replace with a suitable replacement character.
362 \end{itemize}
363\end{classdesc}
364
365\begin{methoddesc}{read}{\optional{size}}
366 Decodes data from the stream and returns the resulting object.
367
368 \var{size} indicates the approximate maximum number of bytes to read
369 from the stream for decoding purposes. The decoder can modify this
370 setting as appropriate. The default value -1 indicates to read and
371 decode as much as possible. \var{size} is intended to prevent having
372 to decode huge files in one step.
373
374 The method should use a greedy read strategy meaning that it should
375 read as much data as is allowed within the definition of the encoding
376 and the given size, e.g. if optional encoding endings or state
377 markers are available on the stream, these should be read too.
378\end{methoddesc}
379
380\begin{methoddesc}{readline}{[size]}
381 Read one line from the input stream and return the
382 decoded data.
383
Fred Drake0aa811c2001-10-20 04:24:09 +0000384 Unlike the \method{readlines()} method, this method inherits
Fred Drake602aa772000-10-12 20:50:55 +0000385 the line breaking knowledge from the underlying stream's
386 \method{readline()} method -- there is currently no support for line
387 breaking using the codec decoder due to lack of line buffering.
388 Sublcasses should however, if possible, try to implement this method
389 using their own knowledge of line breaking.
390
391 \var{size}, if given, is passed as size argument to the stream's
392 \method{readline()} method.
393\end{methoddesc}
394
395\begin{methoddesc}{readlines}{[sizehint]}
396 Read all lines available on the input stream and return them as list
397 of lines.
398
399 Line breaks are implemented using the codec's decoder method and are
400 included in the list entries.
401
402 \var{sizehint}, if given, is passed as \var{size} argument to the
403 stream's \method{read()} method.
404\end{methoddesc}
405
406\begin{methoddesc}{reset}{}
407 Resets the codec buffers used for keeping state.
408
409 Note that no stream repositioning should take place. This method is
410 primarily intended to be able to recover from decoding errors.
411\end{methoddesc}
412
413In addition to the above methods, the \class{StreamReader} must also
414inherit all other methods and attribute from the underlying stream.
415
416The next two base classes are included for convenience. They are not
417needed by the codec registry, but may provide useful in practice.
418
419
420\subsubsection{StreamReaderWriter Objects \label{stream-reader-writer}}
421
422The \class{StreamReaderWriter} allows wrapping streams which work in
423both read and write modes.
424
425The design is such that one can use the factory functions returned by
426the \function{lookup()} function to construct the instance.
427
428\begin{classdesc}{StreamReaderWriter}{stream, Reader, Writer, errors}
429 Creates a \class{StreamReaderWriter} instance.
430 \var{stream} must be a file-like object.
431 \var{Reader} and \var{Writer} must be factory functions or classes
432 providing the \class{StreamReader} and \class{StreamWriter} interface
433 resp.
434 Error handling is done in the same way as defined for the
435 stream readers and writers.
436\end{classdesc}
437
438\class{StreamReaderWriter} instances define the combined interfaces of
439\class{StreamReader} and \class{StreamWriter} classes. They inherit
440all other methods and attribute from the underlying stream.
441
442
443\subsubsection{StreamRecoder Objects \label{stream-recoder-objects}}
444
445The \class{StreamRecoder} provide a frontend - backend view of
446encoding data which is sometimes useful when dealing with different
447encoding environments.
448
449The design is such that one can use the factory functions returned by
450the \function{lookup()} function to construct the instance.
451
452\begin{classdesc}{StreamRecoder}{stream, encode, decode,
453 Reader, Writer, errors}
454 Creates a \class{StreamRecoder} instance which implements a two-way
455 conversion: \var{encode} and \var{decode} work on the frontend (the
456 input to \method{read()} and output of \method{write()}) while
457 \var{Reader} and \var{Writer} work on the backend (reading and
458 writing to the stream).
459
460 You can use these objects to do transparent direct recodings from
461 e.g.\ Latin-1 to UTF-8 and back.
462
463 \var{stream} must be a file-like object.
464
465 \var{encode}, \var{decode} must adhere to the \class{Codec}
466 interface, \var{Reader}, \var{Writer} must be factory functions or
467 classes providing objects of the the \class{StreamReader} and
468 \class{StreamWriter} interface respectively.
469
470 \var{encode} and \var{decode} are needed for the frontend
471 translation, \var{Reader} and \var{Writer} for the backend
472 translation. The intermediate format used is determined by the two
473 sets of codecs, e.g. the Unicode codecs will use Unicode as
474 intermediate encoding.
475
476 Error handling is done in the same way as defined for the
477 stream readers and writers.
478\end{classdesc}
479
480\class{StreamRecoder} instances define the combined interfaces of
481\class{StreamReader} and \class{StreamWriter} classes. They inherit
482all other methods and attribute from the underlying stream.
483