closing StringIO objects

N

Neil Cerutti

The documentation says the following about StringIO.close:

close( )
Free the memory buffer.

Or else... what?
 
A

Alex Martelli

Neil Cerutti said:
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).


Alex
 
N

Neil Cerutti

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,431
Messages
2,571,679
Members
48,796
Latest member
Greg L.

Latest Threads

Top