Python 3 Binary Data Services

Updated: 11/06/2021 by Computer Hope
python command

This page covers the struct and codecs binary services available in Python 3.

struct — Interpret bytes as packed binary data

The struct module performs conversions between Python values and C structs represented as Python bytes objects. This can be used in handling binary data stored in files or from network connections, among other sources. It uses Format Strings as compact descriptions of the layout of the C structs and the intended conversion to/from Python values.

Note

By default, the result of packing a C struct includes pad bytes to maintain proper alignment for the C types involved; similarly, alignment is taken into account when unpacking. This behavior is chosen so that the bytes of a packed struct correspond exactly to the layout in memory of the corresponding C struct. To handle platform-independent data formats or omit implicit pad bytes, use standard size and alignment instead of native size and alignment: see Byte Order, Size, and Alignment for details.

Struct functions and exceptions

The module defines the following exception and functions:

exception struct.error
Exception raised on various occasions; argument is a string describing what is wrong.
struct.pack(fmt,  v1,  v2, ...)
Return a bytes object containing the values v1, v2, etc., packed according to the format string fmt. The arguments must match the values required by the format exactly.
struct.pack_into(fmt,  buffer,  offset,  v1,  v2, ...)
Pack the values v1, v2, etc., according to the format string fmt and write the packed bytes to the writable buffer starting at position offset. Note that offset is a required argument.
struct.unpack(fmt, buffer)
Unpack from the buffer (presumably packed by pack(fmt, ...)) according to the format string fmt. The result is a tuple even if it contains exactly one item. The buffer must contain exactly the amount of data required by the format (len(bytes) must equal calcsize(fmt)).
struct.unpack_from(fmt,  buffer,  offset=0)
Unpack from buffer starting at position offset, according to the format string fmt. The result is a tuple even if it contains exactly one item. The buffer must contain at least the amount of data required by the format (len(buffer[offset:]) must be at least calcsize(fmt)).
struct.iter_unpack(fmt, buffer)
Iteratively unpack from the buffer according to the format string fmt. This function returns an iterator that reads equally-sized chunks from the buffer until all its contents are consumed. The buffer's size in bytes must be a multiple of the amount of data required by the format, as reflected by calcsize().

Each iteration yields a tuple as specified by the format string.
struct.calcsize(fmt)
Return the size of the struct (and hence of the bytes object produced by pack(fmt, ...)) corresponding to the format string fmt.

Struct format strings

Format strings are the mechanism used to specify the expected layout when packing and unpacking data. They are built up from Format Characters, which specify the type of data being packed/unpacked. Also, there are special characters for controlling the Byte Order, Size, and Alignment.

Struct byte order, size, and alignment

By default, C types are represented in the machine's native format and byte order, and properly aligned by skipping pad bytes if necessary (according to the rules used by the C compiler).

Alternatively, the first character of the format string can indicate the byte order, size, and alignment of the packed data, according to the following table:

Character Byte Order Size Alignment
@ native native native
= little-endian standard none
< little-endian standard none
> big-endian standard none
! network (= big-endian) standard none

If the first character is not one of these, '@' is assumed.

Native byte order is big-endian or little-endian, depending on the host system. For example, Intel x86 and AMD64 (x86-64) are little-endian; Motorola 68000 and PowerPC G5 are big-endian; ARM and Intel Itanium feature switchable endianness (bi-endian). Use sys.byteorder to check the endianness of your system.

Native size and alignment are determined using the C compiler's sizeof expression. This is always combined with native byte order.

Standard size depends only on the format character; see the table in the Format Characters section.

Note the difference between '@' and '=': both use native byte order, but the size and alignment of the latter is standardized.

The form '!' is available for those poor souls who claim they can’t remember whether network byte order is big-endian or little-endian.

There is no way to indicate non-native byte order (force byte-swapping); use the appropriate choice of '<' or '>'. Notes:

  • Padding is only automatically added between successive structure members. No padding is added at the beginning or the end of the encoded struct.
  • No padding is added when using non-native size and alignment, e.g., with ‘<’, ‘>’, ‘=’, and ‘!’.
  • To align the end of a structure to the alignment requirement of a particular type, end the format with the code for that type with a repeat count of zero. See examples.

Struct format characters

Format characters have the following meaning; the conversion between C and Python values should be obvious given their types. The ‘Standard size’ column refers to the size of the packed value in bytes when using standard size; that is, when the format string starts with one of '<', '>', '!' or '='. When using native size, the size of the packed value is platform-dependent.

Format C Type Python Type Standard Size Notes
x (pad byte) no value
c char bytes of length 1 1
b signed char integer 1 1., 3.
B unsigned char integer 1 3.
? _Bool bool 1 1.
h short integer 2 3.
H unsigned short integer 2 3.
i int integer 4 3.
I unsigned int integer 4 3.
l long integer 4 3.
L unsigned long integer 4 3.
q long long integer 8 2., 3.
Q unsigned long long integer 8 2., 3.
n ssize_t integer 4.
N size_t integer 4.
f float float 4 5.
d double float 8 5.
s char[] bytes
p char[] bytes
P void * integer 6.

Notes:

  • The '?' conversion code corresponds to the _Bool type defined by C99. If this type is not available, it is simulated using a char. In standard mode, it is always represented by one byte.
  • The 'q' and 'Q' conversion codes are available in native mode only if the platform C compiler supports C long long, or, on Windows, __int64. They are always available in standard modes.
  • When attempting to pack a non-integer using any of the integer conversion codes, if the non-integer has a __index__() method then that method is called to convert the argument to an integer before packing.
  • Changed in version 3.2: Use of the __index__() method for non-integers is new in 3.2.
  • The 'n' and 'N' conversion codes are only available for the native size (selected as the default or with the '@' byte order character).
  • For the standard size, you can use whichever of the other integer formats fits your application.
  • For the 'f' and 'd' conversion codes, the packed representation uses the IEEE 754 binary32 (for 'f') or binary64 (for 'd') format, regardless of the floating-point format used by the platform.
  • The 'P' format character is only available for the native byte ordering (selected as the default or with the '@' byte order character). The byte order character '=' chooses to use little-endian or big-endian ordering based on the host system. The struct module does not interpret this as native ordering, so the 'P' format is not available.

A format character may be preceded by an integral repeat count. For example, the format string '4h' means the same as 'hhhh'.

Whitespace characters between formats are ignored; a count and its format must not contain whitespace though.

For the 's' format character, the count is interpreted as the length of the bytes, not a repeat count like for the other format characters; for example, '10s' means a single 10-byte string, while '10c' means 10 characters. If a count is not given, it defaults to 1. For packing, the string is truncated or padded with null bytes as appropriate to make it fit. For unpacking, the resulting bytes object always has exactly the specified number of bytes. As a special case, '0s' means a single, empty string (while '0c' means 0 characters).

When packing a value x using one of the integer formats ('b', 'B', 'h', 'H', 'i', 'I', 'l', 'L', 'q', 'Q'), if x is outside the valid range for that format then struct.error is raised.

Changed in version 3.1: In 3.0, some of the integer formats wrapped out-of-range values and raised DeprecationWarning instead of struct.error.

The 'p' format character encodes a “Pascal string”, meaning a short variable-length string stored in a fixed number of bytes, given by the count. The first byte stored is the length of the string, or 255, whichever is smaller. The bytes of the string follow. If the string passed in to pack() is too long (longer than the count minus 1), only the leading count-1 bytes of the string are stored. If the string is shorter than count-1, it is padded with null bytes so that exactly count bytes in all are used. Note that for unpack(), the 'p' format character consumes count bytes, but that the string returned can never contain more than 255 bytes.

For the '?' format character, the return value is either True or False. When packing, the truth value of the argument object is used. Either 0 or 1 in the native or standard bool representation is packed, and any non-zero value is True when unpacking.

Examples

Note

All examples assume a native byte order, size, and alignment with a big-endian machine.

A basic example of packing/unpacking three integers:

>>> from struct import *
>>> pack('hhl', 1, 2, 3)
b'\x00\x01\x00\x02\x00\x00\x00\x03'
>>> unpack('hhl', b'\x00\x01\x00\x02\x00\x00\x00\x03')
(1, 2, 3)
>>> calcsize('hhl')
8

Unpacked fields can be named by assigning them to variables or by wrapping the result in a named tuple:

>>> record = b'raymond   \x32\x12\x08\x01\x08'
>>> name, serialnum, school, gradelevel = unpack('<10sHHb', record)
>>> from collections import namedtuple
>>> Student = namedtuple('Student', 'name serialnum school gradelevel')
>>> Student._make(unpack('<10sHHb', record))
Student(name=b'raymond   ', serialnum=4658, school=264, gradelevel=8)

The ordering of format characters may have an impact on size since the padding needed to satisfy alignment requirements is different:

>>> pack('ci', b'*', 0x12131415)
b'*\x00\x00\x00\x12\x13\x14\x15'
>>> pack('ic', 0x12131415, b'*')
b'\x12\x13\x14\x15*'
>>> calcsize('ci')
8
>>> calcsize('ic')
5

The following format 'llh0l' specifies two pad bytes at the end, assuming longs are aligned on 4-byte boundaries:

>>> pack('llh0l', 1, 2, 3)
b'\x00\x00\x00\x01\x00\x00\x00\x02\x00\x03\x00\x00'

This only works when native size and alignment are in effect; standard size and alignment does not enforce any alignment.

Struct classes

The struct module also defines the following type:

class struct.Struct(format)
Return a new Struct object which writes and reads binary data according to the format string format. Creating a Struct object once and calling its methods is more efficient than calling the struct functions with the same format since the format string only needs to be compiled once.

Compiled Struct objects support the following methods and attributes:

pack(v1,  v2, ...)
Identical to the pack() function, using the compiled format. (len(result) equals self.size.)
pack_into(buffer,  offset,  v1,  v2, ...)
Identical to the pack_into() function, using the compiled format.
unpack(buffer)
Identical to the unpack() function, using the compiled format. (len(buffer) must equal self.size).
unpack_from(buffer, offset=0)
Identical to the unpack_from() function, using the compiled format. (len(buffer[offset:]) must be at least self.size).
iter_unpack(buffer)
Identical to the iter_unpack() function, using the compiled format. (len(buffer) must be a multiple of self.size).
format
The format string used to construct this Struct object.
size
The calculated size of the struct (and hence of the bytes object produced by the pack() method) corresponding to format.

Codecs module

The codecs module handles the compression and decompression of some standard data formats.

Codecs: registry and base classes

This module defines base classes for standard Python codecs (encoders and decoders) and provides access to the internal Python codec registry which manages the codec and error handling look up process.

It defines the following functions:

codecs.encode(obj [, encoding [, errors]])
Encodes obj using the codec registered for encoding. The default encoding is utf-8.

Errors may be given to set the desired error handling scheme. The default error handler is strict meaning that encoding errors raise ValueError (or a more codec specific subclass, such as UnicodeEncodeError). Refer to Codec Base Classes for more information on codec error handling.
codecs.decode(obj [, encoding [, errors]])
Decodes obj using the codec registered for encoding. The default encoding is utf-8.

Errors may be given to set the desired error handling scheme. The default error handler is strict meaning that decoding errors raise ValueError (or a more codec specific subclass, such as UnicodeDecodeError). Refer to Codec Base Classes for more information on codec error handling.
codecs.register(search_function)
Register a codec search function. Search functions are expected to take one argument, the encoding name in all lower case letters, and return a CodecInfo object having the following attributes:

name The name of the encoding
encode The stateless encoding function
decode The stateless decoding function
incrementalencoder An incremental encoder class or factory function
incrementaldecoder An incremental decoder class or factory function
streamwriter A stream writer class or factory function
streamreader A stream reader class or factory function
The various functions or classes take the following arguments:

encode and decode: These must be functions or methods which have the same interface as the encode()/decode() methods of Codec instances (see Codec Objects). The functions/methods are expected to work in a stateless mode.

incrementalencoder and incrementaldecoder: These have to be factory functions providing the following interface:

factory(errors='strict')
The factory functions must return objects providing the interfaces defined by the base classes IncrementalEncoder and IncrementalDecoder, respectively. Incremental codecs can maintain state.

streamreader and streamwriter: These have to be factory functions providing the following interface:

factory(stream, errors='strict')
The factory functions must return objects providing the interfaces defined by the base classes StreamReader and StreamWriter, respectively. Stream codecs can maintain state.

Possible values for errors are:

  • 'strict': raise an exception in case of an encoding error
  • 'replace': replace malformed data with a suitable replacement marker, such as '?' or '\ufffd'
  • 'ignore': ignore malformed data and continue without further notice
  • 'xmlcharrefreplace': replace with the appropriate XML character reference (for encoding only)
  • 'backslashreplace': replace with backslashed escape sequences (for encoding only)
  • 'surrogateescape': on decoding, replace with code points in the Unicode Private Use Area ranging from U+DC80 to U+DCFF. These private code points are then turned back into the same bytes when the surrogateescape error handler is used when encoding the data. (See PEP 383 for more.)
And any other error handling name defined via register_error().

In case a search function cannot find a specific encoding, it should return None.
codecs.lookup(encoding)
Looks up the codec info in the Python codec registry and returns a CodecInfo object as defined above.

Encodings are first looked up in the registry's cache. If not found, the list of registered search functions is scanned. If no CodecInfo object is found, a LookupError is raised. Otherwise, the CodecInfo object is stored in the cache and returned to the caller.

To simplify access to the various codecs, the module provides these additional functions which use lookup() for the codec look up:

codecs.getencoder(encoding)
Look up the codec for the given encoding and return its encoder function.

Raises a LookupError in case the encoding cannot be found.
codecs.getdecoder(encoding)
Look up the codec for the given encoding and return its decoder function.

Raises a LookupError in case the encoding cannot be found.
codecs.getincrementalencoder(encoding)
Look up the codec for the given encoding and return its incremental encoder class or factory function.

Raises a LookupError in case the encoding cannot be found or the codec doesn’t support an incremental encoder.
codecs.getincrementaldecoder(encoding)
Look up the codec for the given encoding and return its incremental decoder class or factory function.

Raises a LookupError in case the encoding cannot be found or the codec doesn’t support an incremental decoder.
codecs.getreader(encoding)
Look up the codec for the given encoding and return its StreamReader class or factory function.

Raises a LookupError in case the encoding cannot be found.
codecs.getwriter(encoding)
Look up the codec for the given encoding and return its StreamWriter class or factory function.

Raises a LookupError in case the encoding cannot be found.
codecs.register_error(name,  error_handler)
Register the error handling function error_handler under the name name. error_handler is called during encoding and decoding in case of an error, when name is specified as the errors parameter.

For encoding error_handler is called with a UnicodeEncodeError instance, which contains information about the location of the error. The error handler must either raise this or a different exception or return a tuple with a replacement for the unencodable part of the input and a position where encoding should continue. The replacement may be either str or bytes. If the replacement is bytes, the encoder copies them to the output buffer. If the replacement is a string, the encoder encodes the replacement. Encoding continues on original input at the specified position. Negative position values are treated as being relative to the end of the input string. If the resulting position is out of bound, an IndexError is raised.

Decoding and translating works similar, except UnicodeDecodeError or UnicodeTranslateError is passed to the handler and that the replacement from the error handler is put in the output directly.
codecs.lookup_error(name)
Return the error handler previously registered under the name name.

Raises a LookupError in case the handler cannot be found.
codecs.strict_errors(exception)
Implements the strict error handling: each encoding or decoding error raises a UnicodeError.
codecs.replace_errors(exception)
Implements the replace error handling: malformed data is replaced with a suitable replacement character such as '?' in bytestrings and '\ufffd' in Unicode strings.
codecs.ignore_errors(exception)
Implements the ignore error handling: malformed data is ignored and encoding or decoding is continued without further notice.
codecs.xmlcharrefreplace_errors(exception)
Implements the xmlcharrefreplace error handling (for encoding only): the unencodable character is replaced by an appropriate XML character reference.
codecs.backslashreplace_errors(exception)
Implements the backslashreplace error handling (for encoding only): the unencodable character is replaced by a backslashed escape sequence.

To simplify working with encoded files or stream, the module also defines these utility functions:

codecs.open(filename,  mode [, encoding [, errors [, buffering]]])
Open an encoded file using the given mode and return a wrapped version providing transparent encoding/decoding. The default file mode is 'r' meaning to open the file in read mode.

Note: The wrapped version's methods accepts and return strings only. Bytes arguments are rejected.

Note: Files are always opened in binary mode, even if no binary mode was specified. This is done to avoid data loss due to encodings using 8-bit values. This means that no automatic conversion of b'\n' is done on reading and writing. The encoding specifies the encoding that is to be used for the file. The errors may be given to define the error handling. It defaults to 'strict' which causes a ValueError to be raised in case an encoding error occurs.

The buffering has the same meaning as for the built-in open() function. It defaults to line buffered.
codecs.EncodedFile(file,  data_encoding,  file_encoding=None,  errors='strict')
Return a wrapped version of file which provides transparent encoding translation.

Bytes written to the wrapped file are interpreted according to the given data_encoding and then written to the original file as bytes using the file_encoding. If file_encoding is not given, it defaults to data_encoding. Errors may be given to define the error handling. It defaults to 'strict', which causes ValueError to be raised in case an encoding error occurs.
codecs.iterencode(iterator,  encoding,  errors='strict',  **kwargs)
Uses an incremental encoder to iteratively encode the input provided by iterator. This function is a generator. errors (and any other keyword argument) is passed through to the incremental encoder.
codecs.iterdecode(iterator,  encoding,  errors='strict',  **kwargs)
Uses an incremental decoder to iteratively decode the input provided by iterator. This function is a generator. errors (and any other keyword argument) is passed through to the incremental decoder.

The module also provides the following constants that are useful for reading and writing to platform dependent files:

codecs.BOMcodecs.BOM_BEcodecs.BOM_LEcodecs.BOM_UTF8codecs.BOM_UTF16codecs.BOM_UTF16_BEcodecs.BOM_UTF16_LEcodecs.BOM_UTF32codecs.BOM_UTF32_BEcodecs.BOM_UTF32_LE
These constants define various encodings of the Unicode byte order mark (BOM) used in UTF-16 and UTF-32 data streams to indicate the byte order used in the stream or file and in UTF-8 as a Unicode signature. BOM_UTF16 is either BOM_UTF16_BE or BOM_UTF16_LE depending on the platform's native byte order, BOM is an alias for BOM_UTF16, BOM_LE for BOM_UTF16_LE and BOM_BE for BOM_UTF16_BE. The others represent the BOM in UTF-8 and UTF-32 encodings.

Codecs base classes

The codecs module defines a set of base classes which define the interface and can also be used to easily write codecs for use in Python.

Each codec has to define four interfaces to make it usable as codec in Python: stateless encoder, stateless decoder, stream reader and stream writer. The stream reader and writers often reuse the stateless encoder/decoder to implement the file protocols.

The Codec class defines the interface for stateless encoders/decoders.

To simplify and standardize error handling, the encode() and decode() methods may implement different error handling schemes by providing the errors string argument. The following string values are defined and implemented by all standard Python codecs:

Value Meaning
'strict' Raise UnicodeError (or a subclass); this is the default.
'ignore' Ignore the character and continue with the next.
'replace' Replace with a suitable replacement character; Python uses the official U+FFFD REPLACEMENT CHARACTER for the built-in Unicode codecs on decoding and ‘?’ on encoding.
'xmlcharrefreplace' Replace with the appropriate XML character reference (only for encoding).
'backslashreplace' Replace with backslashed escape sequences (only for encoding).
'surrogateescape' Replace byte with surrogate U+DCxx, as defined in PEP 383.

Also, the following error handlers are specific to Unicode encoding schemes:

Value Codec Meaning
'surrogatepass' utf-8, utf-16, utf-32, utf-16-be, utf-16-le, utf-32-be, utf-32-le Allow encoding and decoding of surrogate codes in all the Unicode encoding schemes.

The set of allowed values can be extended via register_error().

Codec objects

The Codec class defines these methods that also define the function interfaces of the stateless encoder and decoder:

Codec.encode(input [, errors])
Encodes the object input and returns a tuple (output object, length consumed). Encoding converts a string object to a bytes object using a particular character set encoding (e.g., cp1252 or iso-8859-1).

The errors defines the error handling to apply. It defaults to 'strict' handling.

The method may not store state in the Codec instance. Use StreamCodec for codecs which have to keep state to make encoding/decoding efficient.

The encoder must be able to handle zero length input and return an empty object of the output object type in this situation.
Codec.decode(input[,  errors])
Decodes the object input and returns a tuple (output object, length consumed). Decoding converts a bytes object encoded using a particular character set encoding to a string object.

The input must be a bytes object or one which provides the read-only character buffer interface – for example, buffer objects and memory mapped files.

The errors defines the error handling to apply. It defaults to 'strict' handling.

The method may not store state in the Codec instance. Use StreamCodec for codecs which have to keep state to make encoding/decoding efficient.

The decoder must be able to handle zero length input and return an empty object of the output object type in this situation.

The IncrementalEncoder and IncrementalDecoder classes provide the basic interface for incremental encoding and decoding. Encoding/decoding the input isn’t done with one call to the stateless encoder/decoder function, but with multiple calls to the encode()/decode() method of the incremental encoder/decoder. The incremental encoder/decoder keeps track of the encoding/decoding process during method calls.

The joined output of calls to the encode()/decode() method is the same as if all the single inputs were joined into one, and this input was encoded/decoded with the stateless encoder/decoder.

Codecs IncrementalEncoder objects

The IncrementalEncoder class is used for encoding an input in multiple steps. It defines the following methods which every incremental encoder must define to be compatible with the Python codec registry.

class codecs.IncrementalEncoder([errors])
Constructor for an IncrementalEncoder instance.

All incremental encoders must provide this constructor interface. They are free to add additional keyword arguments, but only the ones defined here are used by the Python codec registry.

The IncrementalEncoder may implement different error handling schemes by providing the errors keyword argument. These parameters are predefined:

'strict' Raise ValueError (or a subclass); this is the default.
'ignore' Ignore the character and continue with the next.
'replace' Replace with a suitable replacement character
'xmlcharrefreplace' Replace with the appropriate XML character reference
'backslashreplace' Replace with backslashed escape sequences.
The errors argument is assigned to an attribute of the same name. Assigning to this attribute makes it possible to switch between different error handling strategies during the lifetime of the IncrementalEncoder object. The set of allowed values for the errors argument can be extended with register_error().

encode(object [, final])
Encodes object (taking the current state of the encoder into account) and returns the resulting encoded object. If this is the last call to encode(), final must be true (the default is false).
reset()
Reset the encoder to the initial state. The output is discarded: call .encode('', final=True) to reset the encoder and to get the output.
IncrementalEncoder.getstate()
Return the current state of the encoder which must be an integer. The implementation should make sure that 0 is the most common state. (States that are more complicated than integers can be converted into an integer by marshaling/pickling the state and encoding the bytes of the resulting string into an integer).
IncrementalEncoder.setstate(state)
Set the state of the encoder to state. state must be an encoder state returned by getstate().

Codecs IncrementalDecoder objects

The IncrementalDecoder class is used for decoding an input in multiple steps. It defines the following methods which every incremental decoder must define to be compatible with the Python codec registry.

class codecs.IncrementalDecoder([errors])
Constructor for an IncrementalDecoder instance.

All incremental decoders must provide this constructor interface. They are free to add additional keyword arguments, but only the ones defined here are used by the Python codec registry.

The IncrementalDecoder may implement different error handling schemes by providing the errors keyword argument. These parameters are predefined:

  • 'strict' Raise ValueError (or a subclass); this is the default.
  • 'ignore' Ignore the character and continue with the next.
  • 'replace' Replace with a suitable replacement character.
The errors argument is assigned to an attribute of the same name. Assigning to this attribute makes it possible to switch between different error handling strategies during the lifetime of the IncrementalDecoder object.

The set of allowed values for the errors argument can be extended with register_error().

decode(object [, final])
Decodes object (taking the current state of the decoder into account) and returns the resulting decoded object. If this is the last call to decode() final must be true (the default is false). If final is true the decoder must decode the input completely and must flush all buffers. If this isn’t possible (e.g., because of incomplete byte sequences at the end of the input) it must initiate error handling like in the stateless case (which might raise an exception).
reset()
Reset the decoder to the initial state.
getstate()
Return the current state of the decoder. This must be a tuple with two items, the first must be the buffer containing the still undecoded input. The second must be an integer and can be additional state info. (The implementation should make sure that 0 is the most common additional state info.) If this additional state info is 0 it must be possible to set the decoder to the state which has no input buffered and 0 as the additional state info, so that feeding the previously buffered input to the decoder returns it to the previous state without producing any output. (Additional state info that is more complicated than integers can be converted into an integer by marshaling/pickling the info and encoding the bytes of the resulting string into an integer.)
setstate(state)
Set the state of the encoder to state. state must be a decoder state returned by getstate().

The StreamWriter and StreamReader classes provide generic working interfaces which can implement new encoding submodules very easily. See encodings.utf_8 for an example of how this is done.

Codecs StreamWriter objects

The StreamWriter class is a subclass of Codec and defines the following methods which every stream writer must define to be compatible with the Python codec registry.

class codecs.StreamWriter(stream [, errors])
Constructor for a StreamWriter instance.

All stream writers must provide this constructor interface. They are free to add additional keyword arguments, but only the ones defined here are used by the Python codec registry.

stream must be a file-like object open for writing binary data.

The StreamWriter may implement different error handling schemes by providing the errors keyword argument. These parameters are predefined:

  • 'strict' Raise ValueError (or a subclass); this is the default.
  • 'ignore' Ignore the character and continue with the next.
  • 'replace' Replace with a suitable replacement character
  • 'xmlcharrefreplace' Replace with the appropriate XML character reference
  • 'backslashreplace' Replace with backslashed escape sequences.
The errors argument is assigned to an attribute of the same name. Assigning to this attribute makes it possible to switch between different error handling strategies during the lifetime of the StreamWriter object.

The set of allowed values for the errors argument can be extended with register_error().

write(object)
Writes the object's contents encoded to the stream.
writelines(list)
Writes the concatenated list of strings to the stream (possibly by reusing the write() method).
reset()
Flushes and resets the codec buffers used for keeping state.

Calling this method should ensure that the data on the output is put into a clean state that allows appending of new fresh data without having to rescan the whole stream to recover state.
In addition to the above methods, the StreamWriter must also inherit all other methods and attributes from the underlying stream.

Codecs StreamReader objects

The StreamReader class is a subclass of Codec and defines the following methods which every stream reader must define to be compatible with the Python codec registry.

class codecs.StreamReader(stream [, errors])
Constructor for a StreamReader instance.

All stream readers must provide this constructor interface. They are free to add additional keyword arguments, but only the ones defined here are used by the Python codec registry.

stream must be a file-like object open for reading (binary) data.

The StreamReader may implement different error handling schemes by providing the errors keyword argument. These parameters are defined:

  • 'strict' Raise ValueError (or a subclass); this is the default.
  • 'ignore' Ignore the character and continue with the next.
  • 'replace' Replace with a suitable replacement character.
The errors argument is assigned to an attribute of the same name. Assigning to this attribute makes it possible to switch between different error handling strategies during the lifetime of the StreamReader object.

The set of allowed values for the errors argument can be extended with register_error().

read([size [, chars [, firstline]]])
Decodes data from the stream and returns the resulting object.

chars indicates the number of characters to read from the stream. read() never returns more than chars characters, but it might return less, if there are not enough characters available.

size indicates the approximate maximum number of bytes to read from the stream for decoding purposes. The decoder can modify this setting as appropriate. The default value -1 indicates to read and decode as much as possible. size is intended to prevent having to decode huge files in one step.

firstline indicates that it would be sufficient to only return the first line, if there are decoding errors on later lines.

The method should use a greedy read strategy meaning that it should read as much data as is allowed in the definition of the encoding and the given size, e.g., if optional encoding endings or state markers are available on the stream, these should be read too.
readline([size [, keepends]])
Read one line from the input stream and return the decoded data.

size, if given, is passed as size argument to the stream's read() method.

If keepends is false, line-endings are stripped from the lines returned.
readlines([sizehint [, keepends]])
Read all lines available on the input stream and return them as a list of lines.

Line-endings are implemented using the codec's decoder method and are included in the list entries if keepends is true.

sizehint, if given, is passed as the size argument to the stream's read() method.
reset()
Resets the codec buffers used for keeping state.

Note that no stream repositioning should take place. This method is primarily intended to be able to recover from decoding errors.
In addition to the above methods, the StreamReader must also inherit all other methods and attributes from the underlying stream.

The next two base classes are included for convenience. They are not needed by the codec registry, but may provide useful in practice.

Codecs StreamReaderWriter objects

The StreamReaderWriter allows wrapping streams which work in both read and write modes.

The design is such that one can use the factory functions returned by the lookup() function to construct the instance.

class codecs.StreamReaderWriter(stream,  Reader,  Writer,  errors)
Creates a StreamReaderWriter instance. Stream must be a file-like object. Reader and Writer must be factory functions or classes providing the StreamReader and StreamWriter interface respectively. Error handling is done in the same way as defined for the stream readers and writers.

StreamReaderWriter instances define the combined interfaces of StreamReader and StreamWriter classes. They inherit all other methods and attributes from the underlying stream.

Codecs StreamRecoder objects

The StreamRecoder provide a frontend - backend view of encoding data that is sometimes useful when dealing with different encoding environments.

The design is such that one can use the factory functions returned by the lookup() function to construct the instance.

class codecs.StreamRecoder(stream,  encode,  decode,  Reader,  Writer,  errors)
Creates a StreamRecoder instance which implements a two-way conversion: encode and decode work on the frontend (the input to read() and output of write()) while Reader and Writer work on the backend (reading and writing to the stream).

You can use these objects to do transparent direct recodings from e.g., Latin-1 to UTF-8 and back.

stream must be a file-like object.

encode, decode must adhere to the Codec interface. Reader, Writer must be factory functions or classes providing objects of the StreamReader and StreamWriter interface respectively.

encode and decode are needed for the frontend translation, Reader and Writer for the backend translation.

Error handling is done in the same way as defined for the stream readers and writers.

StreamRecoder instances define the combined interfaces of StreamReader and StreamWriter classes. They inherit all other methods and attributes from the underlying stream.

Codecs encodings and unicode

Strings are stored internally as sequences of codepoints in range 0 - 10FFFF (see PEP 393 for more details about the implementation). Once a string object is used outside of CPU and memory, CPU endianness and how these arrays are stored as bytes become an issue. Transforming a string object into a sequence of bytes is called encoding and recreating the string object from the sequence of bytes is known as decoding. There are many different methods for how this transformation can be done (these methods are also called encodings). The simplest method is to map the codepoints 0-255 to the bytes 0x0-0xff. This means that a string object containing codepoints above U+00FF can’t be encoded with this method (which is called 'latin-1' or 'iso-8859-1'). str.encode() raises a UnicodeEncodeError that looks like this:

UnicodeEncodeError: 'latin-1' codec can't encode character 
'\u1234' in position 3: ordinal not in range(256).

There's another group of encodings (the so called charmap encodings) that choose a different subset of all Unicode code points and how these codepoints are mapped to the bytes 0x0-0xff. To see how this is done open e.g., encodings/cp1252.py (which is an encoding that is used primarily on Windows). There's a string constant with 256 characters that shows you which character is mapped to each byte value.

All of these encodings can only encode 256 of the 1114112 codepoints defined in Unicode. A simple and straightforward way that can store each Unicode code point, is to store each codepoint as four consecutive bytes. There are two possibilities: store the bytes in big endian or in little endian order. These two encodings are called UTF-32-BE and UTF-32-LE respectively. Their disadvantage is that if e.g., you use UTF-32-BE on a little endian machine, you always have to swap bytes on encoding and decoding. UTF-32 avoids this problem: bytes is always in natural endianness. When these bytes are read by a CPU with a different endianness, then bytes have to be swapped though. To be able to detect the endianness of a UTF-16 or UTF-32 byte sequence, there's the so called BOM (“Byte Order Mark”). This is the Unicode character U+FEFF. This character can be prepended to every UTF-16 or UTF-32 byte sequence. The byte swapped version of this character (0xFFFE) is an illegal character that may not appear in a Unicode text. So when the first character in an UTF-16 or UTF-32 byte sequence appears to be a U+FFFE the bytes have to be swapped on decoding. Unfortunately, the character U+FEFF had a second purpose as a ZERO WIDTH NO-BREAK SPACE: a character with no width and doesn't allow a word to be split. It can e.g., be used to give hints to a ligature algorithm. With Unicode 4.0, using U+FEFF as a ZERO WIDTH NO-BREAK SPACE is deprecated (with U+2060 (WORD JOINER) assuming this role). Nevertheless Unicode software still must be able to handle U+FEFF in both roles: as a BOM it's a device to determine the storage layout of the encoded bytes, and vanishes once the byte sequence is decoded into a string; as a ZERO WIDTH NO-BREAK SPACE it's a normal character that is decoded like any other.

There's another encoding that can encode the full range of Unicode characters: UTF-8. UTF-8 is an 8-bit encoding, which means there are no issues with byte order in UTF-8. Each byte in a UTF-8 byte sequence consists of two parts: marker bits (the most significant bits) and payload bits. The marker bits are a sequence of zero to four 1 bits followed by a 0 bit. Unicode characters are encoded like this (with x being payload bits, which when concatenated give the Unicode character):

Range Encoding
U-00000000 ... U-0000007F 0xxxxxxx
U-00000080 ... U-000007FF 110xxxxx 10xxxxxx
U-00000800 ... U-0000FFFF 1110xxxx 10xxxxxx 10xxxxxx

The least significant bit of the Unicode character is the rightmost x bit.

As UTF-8 is an 8-bit encoding no BOM is required and any U+FEFF character in the decoded string (even if it's the first character) is treated as a ZERO WIDTH NO-BREAK SPACE.

Without external information it's impossible to reliably determine which encoding was used for encoding a string. Each charmap encoding can decode any random byte sequence. However, that's not possible with UTF-8, as UTF-8 byte sequences have a structure that doesn’t allow arbitrary byte sequences. To increase the reliability with which a UTF-8 encoding can be detected, Microsoft invented a variant of UTF-8 (that Python 2.5 calls "utf-8-sig") for its Notepad program: Before any of the Unicode characters is written to the file, a UTF-8 encoded BOM (which looks like this as a byte sequence: 0xef, 0xbb, 0xbf) is written. As it's rather improbable that any charmap encoded file starts with these byte values (which would e.g., map to

LATIN SMALL LETTER I WITH DIAERESIS
RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK
INVERTED QUESTION MARK

In iso-8859-1), this increases the probability that a utf-8-sig encoding can be correctly guessed from the byte sequence. So here the BOM is not used to be able to determine the byte order used for generating the byte sequence, but as a signature that helps in guessing the encoding. On encoding the utf-8-sig codec writes 0xef, 0xbb, 0xbf as the first three bytes to the file. On decoding, utf-8-sig skips those three bytes if they appear as the first three bytes in the file. In UTF-8, the use of the BOM is discouraged and should generally be avoided.

Additional Python Reference