python - Closing a connection with a `with` statement -


i want have class represents imap connection , use with statement 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 log in')          return connection      def __exit__(self, type, value, traceback):         self.close()  imapconnection() c:     rv, data = c.list()     print(rv, data) 

naturally fails since imapconnections has no attribute close. how can store connection , pass __exit__ function when with statement finished?

you need store connection in object attributes. this:

class imapconnection:     def __enter__(self):         self.connection = imaplib.imap4_ssl(imap_host)          try:             self.connection.login(mail_username, mail_pass)         except imaplib.imap4.error:             log.error('failed log in')          return self.connection      def __exit__(self, type, value, traceback):         self.connection.close() 

you want implement list method class.

edit: realized actual problem is. when with someclass(*args, **kwargs) c c not value returned __enter__ method. c instance of someclass. that's root of problem returned connection __enter__ , assumed c said connection.


Comments

Popular posts from this blog

angular - Is it possible to get native element for formControl? -

unity3d - Rotate an object to face an opposite direction -

javascript - Why jQuery Select box change event is now working? -