0

What is the best way in Python to check if a ZipFile object is not already closed?

For the moment I am doing this in a class:

try:
    self.zf.open(archive_name).close()
except RuntimeError:
    self.zf = zipfile.ZipFile(self.path)

with self.zf.open(archive_name) as f: 
    # do stuff...

Is there a better way?

Dharman
  • 30,962
  • 25
  • 85
  • 135
BioGeek
  • 21,897
  • 23
  • 83
  • 145
  • What do you mean by "already"? When can the file be closed by whom? –  Aug 10 '12 at 08:22

1 Answers1

4

Internally, there is an open file pointer called fp that get's cleared on close; you can test for that yourself too:

if not self.zf.fp:
    self.zf = zipfile.ZipFile(self.path)

See the zipfile module source; the open method raises the RuntimeError exception if not self.fp is True.

Note that relying on such internal, undocumented implementations can be hairy; if future implementations change your code will break, perhaps in subtle ways. Make sure you have good test coverage for your project.

Alternatively, you could create a ZipFile subclass and override the .close method to track the state, which would be less at risk of breaking due to internal changes:

class MyZipFile(zipfile.ZipFile):
    closed = False
    def close(self):
        self.closed = True
        super(MyZipFile, self).close()

and

if self.zf.closed:
    self.zf = MyZipFile(self.path)

with thanks to aknuds1 for the suggestion.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • There doesn't seem to be any other indication whether a ZipFile is closed unfortunately. Maybe it'd be an idea to subclass ZipFile and override close() with a method that indicates that the instance has been closed? – aknuds1 Aug 10 '12 at 08:34
  • @aknuds1: That's not the issue; calling `.close()` multiple times works fine. It's the *open* call that is the problem for the OP. – Martijn Pieters Aug 10 '12 at 08:37
  • My idea was to remedy that there's no public state indicating whether a ZipFile has been closed, by subclassing ZipFile you could implement that state yourself. – aknuds1 Aug 10 '12 at 08:40