SMTP instances from the smtplib module are not creating their sock attribute consistently after __init__ When host is sent as parameter a sock object is created (and hopefully, connected) When the host is not sent, the sock attribute doesn't exist at all
My use case: try: s = SMTP('myhost') s.do_some_sending() finaly: if s is not None and s.sock is not None: s.quit() But I realize just now that in that case, if s was initialized correctly, its sock was inevitably set
You are right, but... if there is an exception in the connect method before the init of self.sock, the sock attribute will not exist and in this case, and only in this case, there will be an exception in the close method. your code will work fine if you use a try/finally but not in the case where we use the with statement, for example. with SMTP('myhost') as smtp: smtp.do_something() If there is an exception in the __init__ of SMTP and self.sock is not initialized -> traceback.