2

I'm writing some tests using StringIO class and just wonder: I can close StringIO instance, since it is actually mimicking IO, but should I really bother? Should I close StringIO instances as I actually should close files?

Community
  • 1
  • 1
shabunc
  • 23,119
  • 19
  • 77
  • 102

1 Answers1

3

Well, reads and writes go straight to the underlying string; there's no extra buffers to flush, and no OS-level resources to return.

The only reason you might want to close the StringIO is to make subsequent IOs fail or if you needed to make closed? return true, which could be useful if you gave that StringIO to some other component. On the other hand, if you're just going to discard the StringIO a moment later, it doesn't matter in the slightest; the garbage collector doesn't care if it's marked as open or closed.

willglynn
  • 11,210
  • 48
  • 40