Do I have to do StringIO.close()?

2024/11/19 15:35:35

Some code:

import cStringIOdef f():buffer = cStringIO.StringIO()buffer.write('something')return buffer.getvalue()

The documentation says:

StringIO.close(): Free the memory buffer. Attempting to do furtheroperations with a closed StringIO object will raise a ValueError.

Do I have to do buffer.close(), or it will happen automatically when buffer goes out of scope and is garbage collected?

UPDATE:

I did a test:

import StringIO, weakrefdef handler(ref):print 'Buffer died!'def f():buffer = StringIO.StringIO()ref = weakref.ref(buffer, handler)buffer.write('something')return buffer.getvalue()print 'before f()'
f()
print 'after f()'

Result:

vic@wic:~/projects$ python test.py 
before f()
Buffer died!
after f()
vic@wic:~/projects$
Answer

Generally it's still better to call close() or use the with statement, because there may be some unexpected behaviour in special circumstances. For example, the expat-IncrementalParser seems to expect a file to be closed, or it won't return the last tidbit of parsed xml until a timeout occurs in some rare circumstances.

But for the with-statement, which handles the closing for you, you have to use the StringIO class from the io-Modules, as stated in the comment of Ivc.

This was a major headache in some legacy sax-parser script we solved by closing the StringIO manually.

The "out-of-scope" close didn't work. It just waited for the timeout-limit.

https://en.xdnf.cn/q/26425.html

Related Q&A

Python: ulimit and nice for subprocess.call / subprocess.Popen?

I need to limit the amount of time and cpu taken by external command line apps I spawn from a python process using subprocess.call , mainly because sometimes the spawned process gets stuck and pins the…

array.shape() giving error tuple not callable

I have a 2D numpy array called results, which contains its own array of data, and I want to go into it and use each list: for r in results:print "r:"print ry_pred = np.array(r)print y_pred.sh…

Python unittest - Ran 0 tests in 0.000s

So I want to do this code Kata for practice. I want to implement the kata with tdd in separate files:The algorithm:# stringcalculator.py def Add(string):return 1and the tests:# stringcalculator.spec.…

How and where does py.test find fixtures

Where and how does py.test look for fixtures? I have the same code in 2 files in the same folder. When I delete conftest.py, cmdopt cannot be found running test_conf.py (also in same fo…

Python match a string with regex [duplicate]

This question already has answers here:What exactly do "u" and "r" string prefixes do, and what are raw string literals?(7 answers)What exactly is a "raw string regex" an…

What are the consequences of disabling gossip, mingle and heartbeat for celery workers?

What are the implications of disabling gossip, mingle, and heartbeat on my celery workers?In order to reduce the number of messages sent to CloudAMQP to stay within the free plan, I decided to follow …

How to determine if an exception was raised once youre in the finally block?

Is it possible to tell if there was an exception once youre in the finally clause? Something like:try:funky code finally:if ???:print(the funky code raised)Im looking to make something like this m…

How to use re match objects in a list comprehension

I have a function to pick out lumps from a list of strings and return them as another list:def filterPick(lines,regex):result = []for l in lines:match = re.search(regex,l)if match:result += [match.grou…

How do I run pip on python for windows? [duplicate]

This question already has answers here:Why does "pip install" inside Python raise a SyntaxError?(6 answers)Closed 8 years ago.Ive just installed python 3.5, ran Python 3.5 (32-bit) and typed…

Select certain rows by index of another DataFrame

I have a DataFrame and I would select only rows that contain index value into df1.index. for Example: In [96]: df Out[96]:A B C D 1 1 4 9 1 2 4 5 0 2 3 5 5 1 0 22 1 3 9 6and these ind…