Search code examples
pythonwith-statementcontextmanager

where is the __enter__ and __exit__ defined for zipfile?


Based on the with statement

  • The context manager’s __exit__() is loaded for later use.
  • The context manager’s __enter__() method is invoked.

I have seen one of the with usage with zipfile

Question> I have checked the source code of zipfile located here:

/usr/lib/python2.6/zipfile.py

I don't know where the __enter__ and __exit__ functions are defined?

Thank you


Solution

  • I've added this as another answer because it is generally not an answer to initial question. However, it can help to fix your problem.

    class MyZipFile(zipfile.ZipFile): # Create class based on zipfile.ZipFile
      def __init__(file, mode='r'): # Initial part of our module
        zipfile.ZipFile.__init__(file, mode) # Create ZipFile object
    
      def __enter__(self): # On entering...
        return(self) # Return object created in __init__ part
      def __exit__(self, exc_type, exc_val, exc_tb): # On exiting...
        self.close() # Use close method of zipfile.ZipFile
    

    Usage:

    with MyZipFile('new.zip', 'w') as tempzip: # Use content manager of MyZipFile
      tempzip.write('sbdtools.py') # Write file to our archive
    

    If you type

    help(MyZipFile)
    

    you can see all methods of original zipfile.ZipFile and your own methods: init, enter and exit. You can add another own functions if you want. Good luck!