[Python-ideas] Add a .pop() method to ZipFile

Terry Jan Reedy tjreedy at udel.edu
Fri May 10 19:55:13 CEST 2013


On 5/10/2013 8:32 AM, Daniel Holth wrote:
> Check out this efficient way to remove the last file from any ordinary zip file.
>
> class TruncatingZipFile(zipfile.ZipFile):
>      """ZipFile that can pop files off the end. This works for ordinary zip
>      files that do not contain non-ZIP data interleaved between the compressed
>      files."""
>
>      def pop(self):
>          """Truncate the last file off this zipfile."""
>          if not self.fp:
>              raise RuntimeError(
>                    "Attempt to pop from ZIP archive that was already closed")
>          last = self.infolist().pop()
>          del self.NameToInfo[last.filename]
>          self.fp.seek(last.header_offset, os.SEEK_SET)
>          self.fp.truncate()
>          self._didModify = True

I object to the name. Pop methods -- list.pop, set.pop, dict.pop, and 
dict.popitem -- remove *and return* an item from a collection. They 
raise exceptions when attempting to pop from an empty collection. 
(Dict.pop is a semi-exception). This usage of 'pop' in Python derives 
from the pop functions/methods of classical stacks.

This method merely removes. If self.infolist is a list, I guess it would 
also raise IndexError when empty.

tjr







More information about the Python-ideas mailing list