Incoming poplib refactoring using windows python 2.3
Question: Hi Guys could you please help me refactor this so that it is sensibly
pythonic.

    
    
    import sys
    import poplib
    import string
    import StringIO, rfc822
    import datetime
    import logging
    
    def _dump_pop_emails(self):
        self.logger.info("open pop account %s with username: %s" % (self.account[0], self.account[1]))
        self.popinstance = poplib.POP3(self.account[0])
        self.logger.info(self.popinstance.getwelcome()) 
        self.popinstance.user(self.account[1])
        self.popinstance.pass_(self.account[2])
        try:
            (numMsgs, totalSize) = self.popinstance.stat()
            for thisNum in range(1, numMsgs+1):
                (server_msg, body, octets) = self.popinstance.retr(thisNum)
                text = string.join(body, '\n')
                mesg = StringIO.StringIO(text)                               
                msg = rfc822.Message(mesg)
                name, email = msg.getaddr("From")
                emailpath = str(self._emailpath + self._inboxfolder + "\\" + email + "_" + msg.getheader("Subject") + ".eml")
                emailpath = self._replace_whitespace(emailpath)
                file = open(emailpath,"wb")
                file.write(text)
                file.close()
                self.popinstance.dele(thisNum)
        finally:
            self.logger.info(self.popinstance.quit())
    
    def _replace_whitespace(self,name):
        name = str(name)
        return name.replace(" ", "_")
    

Also in the _replace_whitespace method I would like to have some kind of
cleaning routine which takes out all illegal characters which could cause
processing.

Basically I want to write the email to the inbox directory in a standard way.

Am i doing something wrong here?


Answer: I don't see anything significant wrong with that code -- is it behaving
incorrectly, or are you just looking for general style guidelines?

A few notes:

  1. Instead of `logger.info ("foo %s %s" % (bar, baz))`, use `"foo %s %s", bar, baz`. This avoids the overhead of string formatting if the message won't be printed.
  2. Put a `try...finally` around opening `emailpath`.
  3. Use `'\n'.join (body)`, instead of `string.join (body, '\n')`.
  4. Instead of `msg.getaddr("From")`, just `msg.From`.

