Wholistic code cleanup / modernization:

* Use +=
* Replace loop logic with str.splitlines equivalent
* Don't use variable names that shadow tuple, list, and str
* Use dict.get instead of equivalent try/except
* Minor loop logic simplications
This commit is contained in:
Raymond Hettinger 2005-02-08 08:05:13 +00:00
parent 9aa890a149
commit bb5fbc4af9
1 changed files with 63 additions and 75 deletions

View File

@ -90,8 +90,6 @@ class Message:
fp.tell()
except (AttributeError, IOError):
seekable = 0
else:
seekable = 1
self.fp = fp
self.seekable = seekable
self.startofheaders = None
@ -134,7 +132,7 @@ class Message:
"""
self.dict = {}
self.unixfrom = ''
self.headers = list = []
self.headers = lst = []
self.status = ''
headerseen = ""
firstline = 1
@ -161,7 +159,7 @@ class Message:
firstline = 0
if headerseen and line[0] in ' \t':
# It's a continuation line.
list.append(line)
lst.append(line)
x = (self.dict[headerseen] + "\n " + line.strip())
self.dict[headerseen] = x.strip()
continue
@ -174,7 +172,7 @@ class Message:
headerseen = self.isheader(line)
if headerseen:
# It's a legal header line, save it.
list.append(line)
lst.append(line)
self.dict[headerseen] = line[len(headerseen)+1:].strip()
continue
else:
@ -202,7 +200,6 @@ class Message:
i = line.find(':')
if i > 0:
return line[:i].lower()
else:
return None
def islast(self, line):
@ -235,7 +232,7 @@ class Message:
"""
name = name.lower() + ':'
n = len(name)
list = []
lst = []
hit = 0
for line in self.headers:
if line[:n].lower() == name:
@ -243,8 +240,8 @@ class Message:
elif not line[:1].isspace():
hit = 0
if hit:
list.append(line)
return list
lst.append(line)
return lst
def getfirstmatchingheader(self, name):
"""Get the first header line matching name.
@ -254,7 +251,7 @@ class Message:
"""
name = name.lower() + ':'
n = len(name)
list = []
lst = []
hit = 0
for line in self.headers:
if hit:
@ -263,8 +260,8 @@ class Message:
elif line[:n].lower() == name:
hit = 1
if hit:
list.append(line)
return list
lst.append(line)
return lst
def getrawheader(self, name):
"""A higher-level interface to getfirstmatchingheader().
@ -275,11 +272,11 @@ class Message:
occur.
"""
list = self.getfirstmatchingheader(name)
if not list:
lst = self.getfirstmatchingheader(name)
if not lst:
return None
list[0] = list[0][len(name) + 1:]
return ''.join(list)
lst[0] = lst[0][len(name) + 1:]
return ''.join(lst)
def getheader(self, name, default=None):
"""Get the header value for a name.
@ -288,10 +285,7 @@ class Message:
header value for a given header name, or None if it doesn't exist.
This uses the dictionary version which finds the *last* such header.
"""
try:
return self.dict[name.lower()]
except KeyError:
return default
return self.dict.get(name.lower(), default)
get = getheader
def getheaders(self, name):
@ -399,9 +393,8 @@ class Message:
del self[name] # Won't fail if it doesn't exist
self.dict[name.lower()] = value
text = name + ": " + value
lines = text.split("\n")
for line in lines:
self.headers.append(line + "\n")
self.headers.extend(text.splitlines(True))
self.headers.append('\n')
def __delitem__(self, name):
"""Delete all occurrences of a specific header, if it is present."""
@ -411,7 +404,7 @@ class Message:
del self.dict[name]
name = name + ':'
n = len(name)
list = []
lst = []
hit = 0
for i in range(len(self.headers)):
line = self.headers[i]
@ -420,8 +413,8 @@ class Message:
elif not line[:1].isspace():
hit = 0
if hit:
list.append(i)
for i in reversed(list):
lst.append(i)
for i in reversed(lst):
del self.headers[i]
def setdefault(self, name, default=""):
@ -430,9 +423,8 @@ class Message:
return self.dict[lowername]
else:
text = name + ": " + default
lines = text.split("\n")
for line in lines:
self.headers.append(line + "\n")
self.headers.extend(text.splitlines(True))
self.headers.append('\n')
self.dict[lowername] = default
return default
@ -473,29 +465,28 @@ class Message:
# XXX The inverses of the parse functions may also be useful.
def unquote(str):
def unquote(s):
"""Remove quotes from a string."""
if len(str) > 1:
if str.startswith('"') and str.endswith('"'):
return str[1:-1].replace('\\\\', '\\').replace('\\"', '"')
if str.startswith('<') and str.endswith('>'):
return str[1:-1]
return str
if len(s) > 1:
if s.startswith('"') and s.endswith('"'):
return s[1:-1].replace('\\\\', '\\').replace('\\"', '"')
if s.startswith('<') and s.endswith('>'):
return s[1:-1]
return s
def quote(str):
def quote(s):
"""Add quotes around a string."""
return str.replace('\\', '\\\\').replace('"', '\\"')
return s.replace('\\', '\\\\').replace('"', '\\"')
def parseaddr(address):
"""Parse an address into a (realname, mailaddr) tuple."""
a = AddressList(address)
list = a.addresslist
if not list:
lst = a.addresslist
if not lst:
return (None, None)
else:
return list[0]
return lst[0]
class AddrlistClass:
@ -543,12 +534,10 @@ class AddrlistClass:
Returns a list containing all of the addresses.
"""
result = []
while 1:
ad = self.getaddress()
if ad:
while ad:
result += ad
else:
break
ad = self.getaddress()
return result
def getaddress(self):
@ -581,11 +570,11 @@ class AddrlistClass:
returnlist = []
fieldlen = len(self.field)
self.pos = self.pos + 1
self.pos += 1
while self.pos < len(self.field):
self.gotonext()
if self.pos < fieldlen and self.field[self.pos] == ';':
self.pos = self.pos + 1
self.pos += 1
break
returnlist = returnlist + self.getaddress()
@ -602,11 +591,11 @@ class AddrlistClass:
if plist:
returnlist = [(' '.join(self.commentlist), plist[0])]
elif self.field[self.pos] in self.specials:
self.pos = self.pos + 1
self.pos += 1
self.gotonext()
if self.pos < len(self.field) and self.field[self.pos] == ',':
self.pos = self.pos + 1
self.pos += 1
return returnlist
def getrouteaddr(self):
@ -618,7 +607,7 @@ class AddrlistClass:
return
expectroute = 0
self.pos = self.pos + 1
self.pos += 1
self.gotonext()
adlist = ""
while self.pos < len(self.field):
@ -626,16 +615,16 @@ class AddrlistClass:
self.getdomain()
expectroute = 0
elif self.field[self.pos] == '>':
self.pos = self.pos + 1
self.pos += 1
break
elif self.field[self.pos] == '@':
self.pos = self.pos + 1
self.pos += 1
expectroute = 1
elif self.field[self.pos] == ':':
self.pos = self.pos + 1
self.pos += 1
else:
adlist = self.getaddrspec()
self.pos = self.pos + 1
self.pos += 1
break
self.gotonext()
@ -649,7 +638,7 @@ class AddrlistClass:
while self.pos < len(self.field):
if self.field[self.pos] == '.':
aslist.append('.')
self.pos = self.pos + 1
self.pos += 1
elif self.field[self.pos] == '"':
aslist.append('"%s"' % self.getquote())
elif self.field[self.pos] in self.atomends:
@ -661,7 +650,7 @@ class AddrlistClass:
return ''.join(aslist)
aslist.append('@')
self.pos = self.pos + 1
self.pos += 1
self.gotonext()
return ''.join(aslist) + self.getdomain()
@ -670,13 +659,13 @@ class AddrlistClass:
sdlist = []
while self.pos < len(self.field):
if self.field[self.pos] in self.LWS:
self.pos = self.pos + 1
self.pos += 1
elif self.field[self.pos] == '(':
self.commentlist.append(self.getcomment())
elif self.field[self.pos] == '[':
sdlist.append(self.getdomainliteral())
elif self.field[self.pos] == '.':
self.pos = self.pos + 1
self.pos += 1
sdlist.append('.')
elif self.field[self.pos] in self.atomends:
break
@ -701,13 +690,13 @@ class AddrlistClass:
slist = ['']
quote = 0
self.pos = self.pos + 1
self.pos += 1
while self.pos < len(self.field):
if quote == 1:
slist.append(self.field[self.pos])
quote = 0
elif self.field[self.pos] in endchars:
self.pos = self.pos + 1
self.pos += 1
break
elif allowcomments and self.field[self.pos] == '(':
slist.append(self.getcomment())
@ -715,7 +704,7 @@ class AddrlistClass:
quote = 1
else:
slist.append(self.field[self.pos])
self.pos = self.pos + 1
self.pos += 1
return ''.join(slist)
@ -746,7 +735,7 @@ class AddrlistClass:
if self.field[self.pos] in atomends:
break
else: atomlist.append(self.field[self.pos])
self.pos = self.pos + 1
self.pos += 1
return ''.join(atomlist)
@ -761,7 +750,7 @@ class AddrlistClass:
while self.pos < len(self.field):
if self.field[self.pos] in self.LWS:
self.pos = self.pos + 1
self.pos += 1
elif self.field[self.pos] == '"':
plist.append(self.getquote())
elif self.field[self.pos] == '(':
@ -930,16 +919,15 @@ def parsedate_tz(data):
else:
tzsign = 1
tzoffset = tzsign * ( (tzoffset//100)*3600 + (tzoffset % 100)*60)
tuple = (yy, mm, dd, thh, tmm, tss, 0, 1, 0, tzoffset)
return tuple
return (yy, mm, dd, thh, tmm, tss, 0, 1, 0, tzoffset)
def parsedate(data):
"""Convert a time string to a time tuple."""
t = parsedate_tz(data)
if type(t) == type( () ):
if t is None:
return t
return t[:9]
else: return t
def mktime_tz(data):
@ -965,10 +953,10 @@ def formatdate(timeval=None):
timeval = time.time()
timeval = time.gmtime(timeval)
return "%s, %02d %s %04d %02d:%02d:%02d GMT" % (
["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"][timeval[6]],
("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun")[timeval[6]],
timeval[2],
["Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"][timeval[1]-1],
("Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec")[timeval[1]-1],
timeval[0], timeval[3], timeval[4], timeval[5])
@ -1002,7 +990,7 @@ if __name__ == '__main__':
m.rewindbody()
n = 0
while f.readline():
n = n + 1
n += 1
print 'Lines:', n
print '-'*70
print 'len =', len(m)