Results of a rewrite pass
[python/dscho.git] / Lib / email / _compat21.py
blobd220723793a0ebdf11e79ca696cdc508568daba6
1 # Copyright (C) 2002 Python Software Foundation
2 # Author: barry@zope.com
4 """Module containing compatibility functions for Python 2.1.
5 """
7 from cStringIO import StringIO
8 from types import StringType, UnicodeType
12 # This function will become a method of the Message class
13 def walk(self):
14 """Walk over the message tree, yielding each subpart.
16 The walk is performed in depth-first order. This method is a
17 generator.
18 """
19 parts = []
20 parts.append(self)
21 if self.is_multipart():
22 for subpart in self.get_payload():
23 parts.extend(subpart.walk())
24 return parts
27 # Python 2.2 spells floor division //
28 def _floordiv(i, j):
29 """Do a floor division, i/j."""
30 return i / j
33 def _isstring(obj):
34 return isinstance(obj, StringType) or isinstance(obj, UnicodeType)
38 # These two functions are imported into the Iterators.py interface module.
39 # The Python 2.2 version uses generators for efficiency.
40 def body_line_iterator(msg):
41 """Iterate over the parts, returning string payloads line-by-line."""
42 lines = []
43 for subpart in msg.walk():
44 payload = subpart.get_payload()
45 if _isstring(payload):
46 for line in StringIO(payload).readlines():
47 lines.append(line)
48 return lines
51 def typed_subpart_iterator(msg, maintype='text', subtype=None):
52 """Iterate over the subparts with a given MIME type.
54 Use `maintype' as the main MIME type to match against; this defaults to
55 "text". Optional `subtype' is the MIME subtype to match against; if
56 omitted, only the main type is matched.
57 """
58 parts = []
59 for subpart in msg.walk():
60 if subpart.get_main_type('text') == maintype:
61 if subtype is None or subpart.get_subtype('plain') == subtype:
62 parts.append(subpart)
63 return parts