snakeoil.stringio module

StringIO functionality

This module provides essentially two types of StringIO’s, and two types of modes of operation; text versus bytes, and readonly versus writable.

The reason for separate classes is that when we’re running on py2k, if all we’re doing is consuming/reading the data it’s heavily preferable to use cStringIO.StringIO if at all possible for performance reasons. Thus we have readonly and writable classes; the separation has clear performance benefits.

Note that while this functionality is based on StringIO and friends, there is some differences in behavior from stdlib- stdlib’s cStringIO.StringIO is pseudo-writable; it has a truncate method (which works). This is suboptimal since the majority of consumers treat it as write only, thus in these classes we specifically raise a TypeError if you try to truncate a readonly instance. Further, instead of just lacking write and writelines methods, we supply those (to maintain file like IO compatibility) but have them raise TypeError if invoked

Exempting the caveats above, usage of these classes is basically no different than interacting with a normal StringIO.

Finally note that the __slots__ layout for py2k cStringIO differs from io.BytesIO (or io.TextIO) in py3k; as such if you’re deriving from a writable instance you’ll need to compensate for this if you want to have source that is usable under both py2k and py3k.

class snakeoil.stringio.bytes_readonly(initial_bytes=b'')[source]

Bases: BytesIO

truncate(*a, **kwds)

Truncate the file to at most size bytes.

Size defaults to the current file position, as returned by tell(). The current file position is unchanged. Returns the new size.

write(*a, **kwds)

Write bytes to file.

Return the number of bytes written.

writelines(*a, **kwds)

Write lines to the file.

Note that newlines are not added. lines can be any iterable object producing bytes-like objects. This is equivalent to calling write() for each element.

class snakeoil.stringio.text_readonly(initial_value='', newline='\n')[source]

Bases: StringIO

truncate(*a, **kwds)

Truncate size to pos.

The pos argument defaults to the current file position, as returned by tell(). The current file position is unchanged. Returns the new absolute position.

write(*a, **kwds)

Write string to file.

Returns the number of characters written, which is always equal to the length of the string.

writelines(*a, **kwds)

Write a list of lines to stream.

Line separators are not added, so it is usual for each of the lines provided to have a line separator at the end.