cStringIO write

Robin Becker robin at jessikat.fsnet.co.uk
Sat Apr 13 14:05:34 EDT 2002


In article <krYt8.13007$b62.354393 at news1.tin.it>, Alex Martelli
<aleax at aleax.it> writes
>Robin Becker wrote:
>
>> Is it deliberate that 2.2 cStringIO only has a write method when created
>> uninitialised? StringIO doesn't have this 'feature', but no mention is
>> made of this in the docs.
>
>Very deliberate, I'd say -- they're different types:
>
>[alex at lancelot cb]$ python
>Python 2.2 (#1, Dec 23 2001, 20:09:01)
>[GCC 2.96 20000731 (Mandrake Linux 8.1 2.96-0.62mdk)] on linux2
>Type "help", "copyright", "credits" or "license" for more information.
>>>> import cStringIO
>>>> readonly = cStringIO.StringIO('ciao')
>>>> writeonly = cStringIO.StringIO()
>>>> type(readonly)
><type 'cStringIO.StringI'>
>>>> type(writeonly)
><type 'cStringIO.StringO'>
>>>> print type(writeonly).__doc__
>Simple type for output to strings.
>>>> print type(readonly).__doc__
>Simple type for treating strings as input file streams
>>>>
>
>
>And this is indeed covered in the docs:
>"""
>The following data objects are provided as well:
>
>InputType
>The type object of the objects created by calling
>  StringIO with a string parameter.
>OutputType
>The type object of the objects returned by calling
>  StringIO with no parameters.
>"""
>
>Maybe you could post to sf, either a tiny patch to the docs clarifying this 
>(I think a "(read-only)" or something like that in the brief description of 
>InputType might be enough?), or a vastly richer and more complex patch if
>you think this isn't a documentation problem but rather than these types
>should be merged into a single, more complicated one.
>
>
>Alex
>
strange in my docs I see no mention of these special types. I see for
StringIO 

This module implements a file-like class, StringIO, that reads and
writes a string buffer


and indeed StringIO.StringIO('aaa') and StringIO() apear to be the same
type. I see that cStringIO does indeed behave as you say, but the module
docs don't say anything about the differences other than mention non-
subclassibility.

Indeed a writeable cStringIO.StringIO is made readable using seek so the
readonly/writeonly distinction is moot.

I need only instances of either so I think I can get away with

def getStringIO(s=None):
    try:
        from cStringIO import StringIO
    except ImportError:
        from StringIO import StringIO
    f = StringIO()
    if s is not None:
        f.write(s)
        f.seek(0)
    return f

but this makes the assumption that initialised StringIO's are to be read
from and not written again.
-- 
Robin Becker



More information about the Python-list mailing list