I have seen code like this (Python 3 code):
import ftplib
from contextlib import closing
with closing(ftplib.FTP()) as ftp:
Is the usage of the closing
method necessary? In an interesting answer, we can read that in database connection objects the context manager's __exit__
method does not close the connection (at least not for SQLite), but commits a transaction instead. Therefore, using the closing
method is necessary.
How is it with the Python's FTP class?
Looking at the sources of the Python ftplib, we can find this:
# Context management protocol: try to quit() if active
def __exit__(self, *args):
if self.sock is not None:
try:
self.quit()
except (OSError, EOFError):
pass
finally:
if self.sock is not None:
self.close()
The quit
method is called hence I think that we don't have to use the closing
method for Python 3. So we can use just:
with (ftplib.FTP()) as ftp:
Since __exit__
method is missing in Python 2, closing
is necessary for Python 2 code.
Is this correct?