blob: 121183b583132c3b7f8db64919bfdef049bbcd49 [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}
Walter Dörwald430b1562002-11-07 22:33:17 +0000230 \lineii{'strict'}{Raise \exception{UnicodeError} (or a subclass);
Fred Drakedc40ac02001-01-22 20:17:54 +0000231 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
Walter Dörwald430b1562002-11-07 22:33:17 +0000235 CHARACTER for the built-in Unicode codecs on
236 decoding and '?' on encoding.}
237 \lineii{'xmlcharrefreplace'}{Replace with the appropriate XML
238 character reference (only for encoding).}
239 \lineii{'backslashreplace'}{Replace with backslashed escape sequences
240 (only for encoding).}
Fred Drakedc40ac02001-01-22 20:17:54 +0000241\end{tableii}
Fred Drake602aa772000-10-12 20:50:55 +0000242
Walter Dörwald430b1562002-11-07 22:33:17 +0000243The set of allowed values can be extended via \method{register_error}.
244
Fred Drake602aa772000-10-12 20:50:55 +0000245
246\subsubsection{Codec Objects \label{codec-objects}}
247
248The \class{Codec} class defines these methods which also define the
249function interfaces of the stateless encoder and decoder:
250
251\begin{methoddesc}{encode}{input\optional{, errors}}
252 Encodes the object \var{input} and returns a tuple (output object,
Skip Montanaro6c7bc312002-04-16 15:12:10 +0000253 length consumed). While codecs are not restricted to use with Unicode, in
254 a Unicode context, encoding converts a Unicode object to a plain string
255 using a particular character set encoding (e.g., \code{cp1252} or
256 \code{iso-8859-1}).
Fred Drake602aa772000-10-12 20:50:55 +0000257
258 \var{errors} defines the error handling to apply. It defaults to
259 \code{'strict'} handling.
260
261 The method may not store state in the \class{Codec} instance. Use
262 \class{StreamCodec} for codecs which have to keep state in order to
263 make encoding/decoding efficient.
264
265 The encoder must be able to handle zero length input and return an
266 empty object of the output object type in this situation.
267\end{methoddesc}
268
269\begin{methoddesc}{decode}{input\optional{, errors}}
270 Decodes the object \var{input} and returns a tuple (output object,
Skip Montanaro6c7bc312002-04-16 15:12:10 +0000271 length consumed). In a Unicode context, decoding converts a plain string
272 encoded using a particular character set encoding to a Unicode object.
Fred Drake602aa772000-10-12 20:50:55 +0000273
274 \var{input} must be an object which provides the \code{bf_getreadbuf}
275 buffer slot. Python strings, buffer objects and memory mapped files
276 are examples of objects providing this slot.
277
278 \var{errors} defines the error handling to apply. It defaults to
279 \code{'strict'} handling.
280
281 The method may not store state in the \class{Codec} instance. Use
282 \class{StreamCodec} for codecs which have to keep state in order to
283 make encoding/decoding efficient.
284
285 The decoder must be able to handle zero length input and return an
286 empty object of the output object type in this situation.
287\end{methoddesc}
288
289The \class{StreamWriter} and \class{StreamReader} classes provide
290generic working interfaces which can be used to implement new
291encodings submodules very easily. See \module{encodings.utf_8} for an
292example on how this is done.
293
294
295\subsubsection{StreamWriter Objects \label{stream-writer-objects}}
296
297The \class{StreamWriter} class is a subclass of \class{Codec} and
298defines the following methods which every stream writer must define in
299order to be compatible to the Python codec registry.
300
301\begin{classdesc}{StreamWriter}{stream\optional{, errors}}
302 Constructor for a \class{StreamWriter} instance.
303
304 All stream writers must provide this constructor interface. They are
305 free to add additional keyword arguments, but only the ones defined
306 here are used by the Python codec registry.
307
308 \var{stream} must be a file-like object open for writing (binary)
309 data.
310
311 The \class{StreamWriter} may implement different error handling
312 schemes by providing the \var{errors} keyword argument. These
Walter Dörwald430b1562002-11-07 22:33:17 +0000313 parameters are predefined:
Fred Drake602aa772000-10-12 20:50:55 +0000314
315 \begin{itemize}
316 \item \code{'strict'} Raise \exception{ValueError} (or a subclass);
317 this is the default.
318 \item \code{'ignore'} Ignore the character and continue with the next.
319 \item \code{'replace'} Replace with a suitable replacement character
Walter Dörwald430b1562002-11-07 22:33:17 +0000320 \item \code{'xmlcharrefreplace'} Replace with the appropriate XML
321 character reference
322 \item \code{'backslashreplace'} Replace with backslashed escape sequences.
Fred Drake602aa772000-10-12 20:50:55 +0000323 \end{itemize}
Walter Dörwald430b1562002-11-07 22:33:17 +0000324
325 The \var{errors} argument will be assigned to an attribute of the
326 same name. Assigning to this attribute makes it possible to switch
327 between different error handling strategies during the lifetime
328 of the \class{StreamWriter} object.
329
330 The set of allowed values for the \var{errors} argument can
331 be extended with \function{register_error()}.
Fred Drake602aa772000-10-12 20:50:55 +0000332\end{classdesc}
333
334\begin{methoddesc}{write}{object}
335 Writes the object's contents encoded to the stream.
336\end{methoddesc}
337
338\begin{methoddesc}{writelines}{list}
339 Writes the concatenated list of strings to the stream (possibly by
340 reusing the \method{write()} method).
341\end{methoddesc}
342
343\begin{methoddesc}{reset}{}
344 Flushes and resets the codec buffers used for keeping state.
345
346 Calling this method should ensure that the data on the output is put
347 into a clean state, that allows appending of new fresh data without
348 having to rescan the whole stream to recover state.
349\end{methoddesc}
350
351In addition to the above methods, the \class{StreamWriter} must also
352inherit all other methods and attribute from the underlying stream.
353
354
355\subsubsection{StreamReader Objects \label{stream-reader-objects}}
356
357The \class{StreamReader} class is a subclass of \class{Codec} and
358defines the following methods which every stream reader must define in
359order to be compatible to the Python codec registry.
360
361\begin{classdesc}{StreamReader}{stream\optional{, errors}}
362 Constructor for a \class{StreamReader} instance.
363
364 All stream readers must provide this constructor interface. They are
365 free to add additional keyword arguments, but only the ones defined
366 here are used by the Python codec registry.
367
368 \var{stream} must be a file-like object open for reading (binary)
369 data.
370
371 The \class{StreamReader} may implement different error handling
372 schemes by providing the \var{errors} keyword argument. These
373 parameters are defined:
374
375 \begin{itemize}
376 \item \code{'strict'} Raise \exception{ValueError} (or a subclass);
377 this is the default.
378 \item \code{'ignore'} Ignore the character and continue with the next.
379 \item \code{'replace'} Replace with a suitable replacement character.
380 \end{itemize}
Walter Dörwald430b1562002-11-07 22:33:17 +0000381
382 The \var{errors} argument will be assigned to an attribute of the
383 same name. Assigning to this attribute makes it possible to switch
384 between different error handling strategies during the lifetime
385 of the \class{StreamReader} object.
386
387 The set of allowed values for the \var{errors} argument can
388 be extended with \function{register_error()}.
Fred Drake602aa772000-10-12 20:50:55 +0000389\end{classdesc}
390
391\begin{methoddesc}{read}{\optional{size}}
392 Decodes data from the stream and returns the resulting object.
393
394 \var{size} indicates the approximate maximum number of bytes to read
395 from the stream for decoding purposes. The decoder can modify this
396 setting as appropriate. The default value -1 indicates to read and
397 decode as much as possible. \var{size} is intended to prevent having
398 to decode huge files in one step.
399
400 The method should use a greedy read strategy meaning that it should
401 read as much data as is allowed within the definition of the encoding
402 and the given size, e.g. if optional encoding endings or state
403 markers are available on the stream, these should be read too.
404\end{methoddesc}
405
406\begin{methoddesc}{readline}{[size]}
407 Read one line from the input stream and return the
408 decoded data.
409
Fred Drake0aa811c2001-10-20 04:24:09 +0000410 Unlike the \method{readlines()} method, this method inherits
Fred Drake602aa772000-10-12 20:50:55 +0000411 the line breaking knowledge from the underlying stream's
412 \method{readline()} method -- there is currently no support for line
413 breaking using the codec decoder due to lack of line buffering.
414 Sublcasses should however, if possible, try to implement this method
415 using their own knowledge of line breaking.
416
417 \var{size}, if given, is passed as size argument to the stream's
418 \method{readline()} method.
419\end{methoddesc}
420
421\begin{methoddesc}{readlines}{[sizehint]}
422 Read all lines available on the input stream and return them as list
423 of lines.
424
425 Line breaks are implemented using the codec's decoder method and are
426 included in the list entries.
427
428 \var{sizehint}, if given, is passed as \var{size} argument to the
429 stream's \method{read()} method.
430\end{methoddesc}
431
432\begin{methoddesc}{reset}{}
433 Resets the codec buffers used for keeping state.
434
435 Note that no stream repositioning should take place. This method is
436 primarily intended to be able to recover from decoding errors.
437\end{methoddesc}
438
439In addition to the above methods, the \class{StreamReader} must also
440inherit all other methods and attribute from the underlying stream.
441
442The next two base classes are included for convenience. They are not
443needed by the codec registry, but may provide useful in practice.
444
445
446\subsubsection{StreamReaderWriter Objects \label{stream-reader-writer}}
447
448The \class{StreamReaderWriter} allows wrapping streams which work in
449both read and write modes.
450
451The design is such that one can use the factory functions returned by
452the \function{lookup()} function to construct the instance.
453
454\begin{classdesc}{StreamReaderWriter}{stream, Reader, Writer, errors}
455 Creates a \class{StreamReaderWriter} instance.
456 \var{stream} must be a file-like object.
457 \var{Reader} and \var{Writer} must be factory functions or classes
458 providing the \class{StreamReader} and \class{StreamWriter} interface
459 resp.
460 Error handling is done in the same way as defined for the
461 stream readers and writers.
462\end{classdesc}
463
464\class{StreamReaderWriter} instances define the combined interfaces of
465\class{StreamReader} and \class{StreamWriter} classes. They inherit
466all other methods and attribute from the underlying stream.
467
468
469\subsubsection{StreamRecoder Objects \label{stream-recoder-objects}}
470
471The \class{StreamRecoder} provide a frontend - backend view of
472encoding data which is sometimes useful when dealing with different
473encoding environments.
474
475The design is such that one can use the factory functions returned by
476the \function{lookup()} function to construct the instance.
477
478\begin{classdesc}{StreamRecoder}{stream, encode, decode,
479 Reader, Writer, errors}
480 Creates a \class{StreamRecoder} instance which implements a two-way
481 conversion: \var{encode} and \var{decode} work on the frontend (the
482 input to \method{read()} and output of \method{write()}) while
483 \var{Reader} and \var{Writer} work on the backend (reading and
484 writing to the stream).
485
486 You can use these objects to do transparent direct recodings from
487 e.g.\ Latin-1 to UTF-8 and back.
488
489 \var{stream} must be a file-like object.
490
491 \var{encode}, \var{decode} must adhere to the \class{Codec}
492 interface, \var{Reader}, \var{Writer} must be factory functions or
493 classes providing objects of the the \class{StreamReader} and
494 \class{StreamWriter} interface respectively.
495
496 \var{encode} and \var{decode} are needed for the frontend
497 translation, \var{Reader} and \var{Writer} for the backend
498 translation. The intermediate format used is determined by the two
499 sets of codecs, e.g. the Unicode codecs will use Unicode as
500 intermediate encoding.
501
502 Error handling is done in the same way as defined for the
503 stream readers and writers.
504\end{classdesc}
505
506\class{StreamRecoder} instances define the combined interfaces of
507\class{StreamReader} and \class{StreamWriter} classes. They inherit
508all other methods and attribute from the underlying stream.
509