StringIO proposal: add __iadd__

Alex Martelli aleax at mail.comcast.net
Sun Jan 29 16:55:36 EST 2006


Paul Rubin <http://phr.cx@NOSPAM.invalid> wrote:
   ...
>    temp_buf = StringIO()
>    for x in various_pieces_of_output(): 
>       v = go_figure_out_some_string()
>       temp_buf += v
>    final_string = temp_buf.getvalue()
> 
> here, "temp_buf += v" is supposed to be the same as "temp_buf.write(v)".
> So the suggestion is to add a __iadd__ method to StringIO and cStringIO.

What's the added value of spelling x.write(v) as x += v?  Is it worth
the utter strangeness of having a class which allows += and not + (the
only one in the std library, I think it would be)...?

> Any thoughts?

I think that the piece of code you like and I just quoted is just fine,
simply by changing the += to a write.

> Also, I wonder if it's now ok to eliminate the existing StringIO
> module (make it an alias for cStringIO) now that new-style classes
> permit extending cStringIO.StringIO.

I love having a pure-Python version of any C-coded standard library
module (indeed, I wish I had more!-) for all sorts of reasons, including
easing the burden of porting Python to weird platforms.  In StringIO's
case, it's nice to be able to use the above idiom to concatenate Unicode
strings just as easily as plain ones, for example -- cStringIO (like
file objects) wants plain bytestrings.

It would be nice (in Py3k, when backwards compatibility can be broken)
to make the plain-named, "default" modules those coded in C, since
they're used more often, and find another convention to indicate pure
Python equivalents -- e.g., pickle/pypickle and StringIO/pyStringIO
rather than the current cPickle/pickle and cStringIO/StringIO.  But I
hope the pure-python "reference" modules stay around (and, indeed, I'd
love for them to _proliferate_, maybe by adopting some of the work of
the pypy guys at some point;).


Alex



More information about the Python-list mailing list