closing StringIO objects

Neil Cerutti horpner at yahoo.com
Wed Aug 15 18:10:10 CEST 2007


On 2007-08-15, Alex Martelli <aleax at mac.com> wrote:
> Neil Cerutti <horpner at yahoo.com> wrote:
>> The documentation says the following about StringIO.close:
>> 
>>   close( ) 
>>   Free the memory buffer. 
>> 
>> Or else... what? 
>
> Or else the memory buffer sticks around, so you can keep
> calling getvalue as needed.  I believe the freeing will happen
> anyway, eventually, if and when the StringIO instance is
> garbage collected (just like, say, a file object's underlying
> fd gets closed when the file object is garbage collected), but
> relying on such behavior is often considered a dubious practice
> nowadays (given the existence of many Python implementations
> whose GC strategies differ).

Thanks. It doesn't seem worth the trouble, given your
explanation.

I was refactoring some pickled StringIO code, and decided to try
out the with statement. I discovered that StringIO isn't a
context manager, so I dipped into contextlib and found 'closing'.
But it's starting to look overengineered, and I realized I had no
idea if it was worth all this fuss just to close a StringIO
object.

from __future__ import with_statement
from contextlib import closing
import pickle
import StringIO

def unserialize(d):
    with closing(StringIO.StringIO(d)) as s:
        obj = pickle.load(s)
        return obj

def serialize(d):
    with closing(StringIO.StringIO()) as s:
        pickle.dump(d, s)
        arg = s.getvalue()
        return arg

-- 
Neil Cerutti
Beethoven wrote fewer symphonies than Haydn and Mozart because he wrote
longer, and besides he went death. --Music Lit Essay



More information about the Python-list mailing list