blob: ec2d2f8a0a9e52b583f521714b2c15840547ae4a [file] [log] [blame]
Barry Warsaw8c1aac22002-05-19 23:44:19 +00001# Copyright (C) 2002 Python Software Foundation
2# Author: barry@zope.com
3
4"""Module containing compatibility functions for Python 2.1.
5"""
6
7from __future__ import generators
8from __future__ import division
9from cStringIO import StringIO
10from types import StringTypes
11
12
13
14# This function will become a method of the Message class
15def walk(self):
16 """Walk over the message tree, yielding each subpart.
17
18 The walk is performed in depth-first order. This method is a
19 generator.
20 """
21 yield self
22 if self.is_multipart():
23 for subpart in self.get_payload():
24 for subsubpart in subpart.walk():
25 yield subsubpart
26
27
Barry Warsawff492792002-06-02 18:59:06 +000028# Python 2.2 spells floor division //
29def _floordiv(i, j):
30 """Do a floor division, i/j."""
31 return i // j
Barry Warsaw8c1aac22002-05-19 23:44:19 +000032
33
Barry Warsaw356afac2002-09-10 16:09:06 +000034def _isstring(obj):
35 return isinstance(obj, StringTypes)
36
37
Barry Warsaw8c1aac22002-05-19 23:44:19 +000038
39# These two functions are imported into the Iterators.py interface module.
40# The Python 2.2 version uses generators for efficiency.
Barry Warsaw12dc2302003-03-11 04:41:35 +000041def body_line_iterator(msg, decode=False):
42 """Iterate over the parts, returning string payloads line-by-line.
43
44 Optional decode (default False) is passed through to .get_payload().
45 """
Barry Warsaw8c1aac22002-05-19 23:44:19 +000046 for subpart in msg.walk():
Barry Warsaw12dc2302003-03-11 04:41:35 +000047 payload = subpart.get_payload(decode=decode)
Barry Warsaw356afac2002-09-10 16:09:06 +000048 if _isstring(payload):
Barry Warsaw8c1aac22002-05-19 23:44:19 +000049 for line in StringIO(payload):
50 yield line
51
52
53def typed_subpart_iterator(msg, maintype='text', subtype=None):
54 """Iterate over the subparts with a given MIME type.
55
56 Use `maintype' as the main MIME type to match against; this defaults to
57 "text". Optional `subtype' is the MIME subtype to match against; if
58 omitted, only the main type is matched.
59 """
60 for subpart in msg.walk():
61 if subpart.get_main_type('text') == maintype:
62 if subtype is None or subpart.get_subtype('plain') == subtype:
63 yield subpart