Do I have to do StringIO.close()?

前端 未结 4 1229
旧时难觅i
旧时难觅i 2021-02-05 01:45

Some code:

import cStringIO

def f():
    buffer = cStringIO.StringIO()
    buffer.write(\'something\')
    return buffer.getvalue()

The docume

相关标签:
4条回答
  • 2021-02-05 02:14

    From the source:

    class StringIO:
        ...
        def close(self):
            """Free the memory buffer.
            """
            if not self.closed:
                self.closed = True
                del self.buf, self.pos
    

    So StringIO.close just frees the memory buffer deleting references to StringIO.buf and StringIO.pos. But if self is garbage collected, its attributes will also be garbage collected, having the same effect as StringIO.close.

    0 讨论(0)
  • 2021-02-05 02:21

    I wound up using a try block to handle it.

    import cStringIO
    
    def f():
        buffer = cStringIO.StringIO()
        try:
            buffer.write('something')
            return buffer.getvalue()
        finally:
            buffer.close()
    
    0 讨论(0)
  • 2021-02-05 02:27

    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.

    0 讨论(0)
  • 2021-02-05 02:34

    StringIO.close() is merely a convenience for routines that take a file-like and eventually attempt to close them. There is no need to do so yourself.

    0 讨论(0)
提交回复
热议问题