I want to have a class that represents an IMAP connection and use it with a with
statement as follows:
class IMAPConnection:
def __enter__(self):
connection = imaplib.IMAP4_SSL(IMAP_HOST)
try:
connection.login(MAIL_USERNAME, MAIL_PASS)
except imaplib.IMAP4.error:
log.error('Failed to log in')
return connection
def __exit__(self, type, value, traceback):
self.close()
with IMAPConnection() as c:
rv, data = c.list()
print(rv, data)
Naturally this fails since IMAPConnections
has no attribute close
. How can I store the connection and pass it to the __exit__
function when the with
statement is finished?