blob: bb444a272e1efa38d4c9f2701a3e4e1d405d1b52 [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
20registry which manages the codec lookup process.
21
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
66To simplify working with encoded files or stream, the module
67also defines these utility functions:
68
Fred Drakee1b304d2000-07-24 19:35:52 +000069\begin{funcdesc}{open}{filename, mode\optional{, encoding\optional{,
70 errors\optional{, buffering}}}}
Fred Drakeb7979c72000-04-06 14:21:58 +000071Open an encoded file using the given \var{mode} and return
72a wrapped version providing transparent encoding/decoding.
73
Fred Drake69ca9502000-04-06 16:09:59 +000074\strong{Note:} The wrapped version will only accept the object format
Fred Drakee1b304d2000-07-24 19:35:52 +000075defined by the codecs, i.e.\ Unicode objects for most built-in
76codecs. Output is also codec-dependent and will usually be Unicode as
Fred Drake69ca9502000-04-06 16:09:59 +000077well.
Fred Drakeb7979c72000-04-06 14:21:58 +000078
79\var{encoding} specifies the encoding which is to be used for the
80the file.
81
82\var{errors} may be given to define the error handling. It defaults
Fred Drakee1b304d2000-07-24 19:35:52 +000083to \code{'strict'} which causes a \exception{ValueError} to be raised
84in case an encoding error occurs.
Fred Drakeb7979c72000-04-06 14:21:58 +000085
Fred Drake69ca9502000-04-06 16:09:59 +000086\var{buffering} has the same meaning as for the built-in
87\function{open()} function. It defaults to line buffered.
Fred Drakeb7979c72000-04-06 14:21:58 +000088\end{funcdesc}
89
Fred Drakee1b304d2000-07-24 19:35:52 +000090\begin{funcdesc}{EncodedFile}{file, input\optional{,
91 output\optional{, errors}}}
Fred Drakeb7979c72000-04-06 14:21:58 +000092Return a wrapped version of file which provides transparent
93encoding translation.
94
95Strings written to the wrapped file are interpreted according to the
96given \var{input} encoding and then written to the original file as
Fred Drakee1b304d2000-07-24 19:35:52 +000097strings using the \var{output} encoding. The intermediate encoding will
Fred Drakeb7979c72000-04-06 14:21:58 +000098usually be Unicode but depends on the specified codecs.
99
Fred Drakee1b304d2000-07-24 19:35:52 +0000100If \var{output} is not given, it defaults to \var{input}.
Fred Drakeb7979c72000-04-06 14:21:58 +0000101
102\var{errors} may be given to define the error handling. It defaults to
Fred Drakee1b304d2000-07-24 19:35:52 +0000103\code{'strict'}, which causes \exception{ValueError} to be raised in case
Fred Drakeb7979c72000-04-06 14:21:58 +0000104an encoding error occurs.
105\end{funcdesc}
106
Fred Drakeb7979c72000-04-06 14:21:58 +0000107The module also provides the following constants which are useful
108for reading and writing to platform dependent files:
109
110\begin{datadesc}{BOM}
111\dataline{BOM_BE}
112\dataline{BOM_LE}
113\dataline{BOM32_BE}
114\dataline{BOM32_LE}
115\dataline{BOM64_BE}
116\dataline{BOM64_LE}
117These constants define the byte order marks (BOM) used in data
118streams to indicate the byte order used in the stream or file.
119\constant{BOM} is either \constant{BOM_BE} or \constant{BOM_LE}
120depending on the platform's native byte order, while the others
121represent big endian (\samp{_BE} suffix) and little endian
122(\samp{_LE} suffix) byte order using 32-bit and 64-bit encodings.
123\end{datadesc}
124
Fred Drake602aa772000-10-12 20:50:55 +0000125\subsection{Codec Base Classes}
126
127The \module{codecs} defines a set of base classes which define the
128interface and can also be used to easily write you own codecs for use
129in Python.
130
131Each codec has to define four interfaces to make it usable as codec in
132Python: stateless encoder, stateless decoder, stream reader and stream
133writer. The stream reader and writers typically reuse the stateless
134encoder/decoder to implement the file protocols.
135
136The \class{Codec} class defines the interface for stateless
137encoders/decoders.
138
139To simplify and standardize error handling, the \method{encode()} and
140\method{decode()} methods may implement different error handling
141schemes by providing the \var{errors} string argument. The following
142string values are defined and implemented by all standard Python
143codecs:
144
145\begin{itemize}
146 \item \code{'strict'} Raise \exception{ValueError} (or a subclass);
147 this is the default.
148 \item \code{'ignore'} Ignore the character and continue with the next.
149 \item \code{'replace'} Replace with a suitable replacement character;
150 Python will use the official U+FFFD REPLACEMENT
151 CHARACTER for the builtin Unicode codecs.
152\end{itemize}
153
154
155\subsubsection{Codec Objects \label{codec-objects}}
156
157The \class{Codec} class defines these methods which also define the
158function interfaces of the stateless encoder and decoder:
159
160\begin{methoddesc}{encode}{input\optional{, errors}}
161 Encodes the object \var{input} and returns a tuple (output object,
162 length consumed).
163
164 \var{errors} defines the error handling to apply. It defaults to
165 \code{'strict'} handling.
166
167 The method may not store state in the \class{Codec} instance. Use
168 \class{StreamCodec} for codecs which have to keep state in order to
169 make encoding/decoding efficient.
170
171 The encoder must be able to handle zero length input and return an
172 empty object of the output object type in this situation.
173\end{methoddesc}
174
175\begin{methoddesc}{decode}{input\optional{, errors}}
176 Decodes the object \var{input} and returns a tuple (output object,
177 length consumed).
178
179 \var{input} must be an object which provides the \code{bf_getreadbuf}
180 buffer slot. Python strings, buffer objects and memory mapped files
181 are examples of objects providing this slot.
182
183 \var{errors} defines the error handling to apply. It defaults to
184 \code{'strict'} handling.
185
186 The method may not store state in the \class{Codec} instance. Use
187 \class{StreamCodec} for codecs which have to keep state in order to
188 make encoding/decoding efficient.
189
190 The decoder must be able to handle zero length input and return an
191 empty object of the output object type in this situation.
192\end{methoddesc}
193
194The \class{StreamWriter} and \class{StreamReader} classes provide
195generic working interfaces which can be used to implement new
196encodings submodules very easily. See \module{encodings.utf_8} for an
197example on how this is done.
198
199
200\subsubsection{StreamWriter Objects \label{stream-writer-objects}}
201
202The \class{StreamWriter} class is a subclass of \class{Codec} and
203defines the following methods which every stream writer must define in
204order to be compatible to the Python codec registry.
205
206\begin{classdesc}{StreamWriter}{stream\optional{, errors}}
207 Constructor for a \class{StreamWriter} instance.
208
209 All stream writers must provide this constructor interface. They are
210 free to add additional keyword arguments, but only the ones defined
211 here are used by the Python codec registry.
212
213 \var{stream} must be a file-like object open for writing (binary)
214 data.
215
216 The \class{StreamWriter} may implement different error handling
217 schemes by providing the \var{errors} keyword argument. These
218 parameters are defined:
219
220 \begin{itemize}
221 \item \code{'strict'} Raise \exception{ValueError} (or a subclass);
222 this is the default.
223 \item \code{'ignore'} Ignore the character and continue with the next.
224 \item \code{'replace'} Replace with a suitable replacement character
225 \end{itemize}
226\end{classdesc}
227
228\begin{methoddesc}{write}{object}
229 Writes the object's contents encoded to the stream.
230\end{methoddesc}
231
232\begin{methoddesc}{writelines}{list}
233 Writes the concatenated list of strings to the stream (possibly by
234 reusing the \method{write()} method).
235\end{methoddesc}
236
237\begin{methoddesc}{reset}{}
238 Flushes and resets the codec buffers used for keeping state.
239
240 Calling this method should ensure that the data on the output is put
241 into a clean state, that allows appending of new fresh data without
242 having to rescan the whole stream to recover state.
243\end{methoddesc}
244
245In addition to the above methods, the \class{StreamWriter} must also
246inherit all other methods and attribute from the underlying stream.
247
248
249\subsubsection{StreamReader Objects \label{stream-reader-objects}}
250
251The \class{StreamReader} class is a subclass of \class{Codec} and
252defines the following methods which every stream reader must define in
253order to be compatible to the Python codec registry.
254
255\begin{classdesc}{StreamReader}{stream\optional{, errors}}
256 Constructor for a \class{StreamReader} instance.
257
258 All stream readers must provide this constructor interface. They are
259 free to add additional keyword arguments, but only the ones defined
260 here are used by the Python codec registry.
261
262 \var{stream} must be a file-like object open for reading (binary)
263 data.
264
265 The \class{StreamReader} may implement different error handling
266 schemes by providing the \var{errors} keyword argument. These
267 parameters are defined:
268
269 \begin{itemize}
270 \item \code{'strict'} Raise \exception{ValueError} (or a subclass);
271 this is the default.
272 \item \code{'ignore'} Ignore the character and continue with the next.
273 \item \code{'replace'} Replace with a suitable replacement character.
274 \end{itemize}
275\end{classdesc}
276
277\begin{methoddesc}{read}{\optional{size}}
278 Decodes data from the stream and returns the resulting object.
279
280 \var{size} indicates the approximate maximum number of bytes to read
281 from the stream for decoding purposes. The decoder can modify this
282 setting as appropriate. The default value -1 indicates to read and
283 decode as much as possible. \var{size} is intended to prevent having
284 to decode huge files in one step.
285
286 The method should use a greedy read strategy meaning that it should
287 read as much data as is allowed within the definition of the encoding
288 and the given size, e.g. if optional encoding endings or state
289 markers are available on the stream, these should be read too.
290\end{methoddesc}
291
292\begin{methoddesc}{readline}{[size]}
293 Read one line from the input stream and return the
294 decoded data.
295
296 Note: Unlike the \method{readlines()} method, this method inherits
297 the line breaking knowledge from the underlying stream's
298 \method{readline()} method -- there is currently no support for line
299 breaking using the codec decoder due to lack of line buffering.
300 Sublcasses should however, if possible, try to implement this method
301 using their own knowledge of line breaking.
302
303 \var{size}, if given, is passed as size argument to the stream's
304 \method{readline()} method.
305\end{methoddesc}
306
307\begin{methoddesc}{readlines}{[sizehint]}
308 Read all lines available on the input stream and return them as list
309 of lines.
310
311 Line breaks are implemented using the codec's decoder method and are
312 included in the list entries.
313
314 \var{sizehint}, if given, is passed as \var{size} argument to the
315 stream's \method{read()} method.
316\end{methoddesc}
317
318\begin{methoddesc}{reset}{}
319 Resets the codec buffers used for keeping state.
320
321 Note that no stream repositioning should take place. This method is
322 primarily intended to be able to recover from decoding errors.
323\end{methoddesc}
324
325In addition to the above methods, the \class{StreamReader} must also
326inherit all other methods and attribute from the underlying stream.
327
328The next two base classes are included for convenience. They are not
329needed by the codec registry, but may provide useful in practice.
330
331
332\subsubsection{StreamReaderWriter Objects \label{stream-reader-writer}}
333
334The \class{StreamReaderWriter} allows wrapping streams which work in
335both read and write modes.
336
337The design is such that one can use the factory functions returned by
338the \function{lookup()} function to construct the instance.
339
340\begin{classdesc}{StreamReaderWriter}{stream, Reader, Writer, errors}
341 Creates a \class{StreamReaderWriter} instance.
342 \var{stream} must be a file-like object.
343 \var{Reader} and \var{Writer} must be factory functions or classes
344 providing the \class{StreamReader} and \class{StreamWriter} interface
345 resp.
346 Error handling is done in the same way as defined for the
347 stream readers and writers.
348\end{classdesc}
349
350\class{StreamReaderWriter} instances define the combined interfaces of
351\class{StreamReader} and \class{StreamWriter} classes. They inherit
352all other methods and attribute from the underlying stream.
353
354
355\subsubsection{StreamRecoder Objects \label{stream-recoder-objects}}
356
357The \class{StreamRecoder} provide a frontend - backend view of
358encoding data which is sometimes useful when dealing with different
359encoding environments.
360
361The design is such that one can use the factory functions returned by
362the \function{lookup()} function to construct the instance.
363
364\begin{classdesc}{StreamRecoder}{stream, encode, decode,
365 Reader, Writer, errors}
366 Creates a \class{StreamRecoder} instance which implements a two-way
367 conversion: \var{encode} and \var{decode} work on the frontend (the
368 input to \method{read()} and output of \method{write()}) while
369 \var{Reader} and \var{Writer} work on the backend (reading and
370 writing to the stream).
371
372 You can use these objects to do transparent direct recodings from
373 e.g.\ Latin-1 to UTF-8 and back.
374
375 \var{stream} must be a file-like object.
376
377 \var{encode}, \var{decode} must adhere to the \class{Codec}
378 interface, \var{Reader}, \var{Writer} must be factory functions or
379 classes providing objects of the the \class{StreamReader} and
380 \class{StreamWriter} interface respectively.
381
382 \var{encode} and \var{decode} are needed for the frontend
383 translation, \var{Reader} and \var{Writer} for the backend
384 translation. The intermediate format used is determined by the two
385 sets of codecs, e.g. the Unicode codecs will use Unicode as
386 intermediate encoding.
387
388 Error handling is done in the same way as defined for the
389 stream readers and writers.
390\end{classdesc}
391
392\class{StreamRecoder} instances define the combined interfaces of
393\class{StreamReader} and \class{StreamWriter} classes. They inherit
394all other methods and attribute from the underlying stream.
395