This commit was manufactured by cvs2svn to create tag 'r23b1-mac'.
[python/dscho.git] / Lib / email / _compat21.py
blob1e1f66692feb74efdc6f2ddde08bb0978c7d5f09
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
10 False = 0
11 True = 1
15 # This function will become a method of the Message class
16 def walk(self):
17 """Walk over the message tree, yielding each subpart.
19 The walk is performed in depth-first order. This method is a
20 generator.
21 """
22 parts = []
23 parts.append(self)
24 if self.is_multipart():
25 for subpart in self.get_payload():
26 parts.extend(subpart.walk())
27 return parts
30 # Python 2.2 spells floor division //
31 def _floordiv(i, j):
32 """Do a floor division, i/j."""
33 return i / j
36 def _isstring(obj):
37 return isinstance(obj, StringType) or isinstance(obj, UnicodeType)
41 # These two functions are imported into the Iterators.py interface module.
42 # The Python 2.2 version uses generators for efficiency.
43 def body_line_iterator(msg, decode=False):
44 """Iterate over the parts, returning string payloads line-by-line.
46 Optional decode (default False) is passed through to .get_payload().
47 """
48 lines = []
49 for subpart in msg.walk():
50 payload = subpart.get_payload(decode=decode)
51 if _isstring(payload):
52 for line in StringIO(payload).readlines():
53 lines.append(line)
54 return lines
57 def typed_subpart_iterator(msg, maintype='text', subtype=None):
58 """Iterate over the subparts with a given MIME type.
60 Use `maintype' as the main MIME type to match against; this defaults to
61 "text". Optional `subtype' is the MIME subtype to match against; if
62 omitted, only the main type is matched.
63 """
64 parts = []
65 for subpart in msg.walk():
66 if subpart.get_content_maintype() == maintype:
67 if subtype is None or subpart.get_content_subtype() == subtype:
68 parts.append(subpart)
69 return parts