[RFC] importing 'email' package on Python 3
Alejandro Santos
alejolp at alejolp.com
Fri Jul 31 16:17:28 CDT 2009
Hi,
I'd like to receive some feedback on the best way to import the email
package to keep compatibility for Python 2.4, 2.5, 2.6 and Py3k.
On Python 2.4, the sub-packages inside 'email' used a Java-like naming
convention. Then, on Python 2.5 the classes names were regrouped and
the sub-package names changed to lowercase:
(Py2.4 => Py2.5+)
- email.MIMEBase.MIMEBase => email.mime.base.MIMEBase
- email.MIMEAudio => email.mime.audio.MIMEAudio
On Py2.5 the 'email' package uses the __init__.py trick to keep
compatibility with 2.4 code. But that trick was removed on Py3k.
In no specific order, and from uglier to ugliest, so far I have:
Option 1: Use a try:/except ImportError: block, and use a Py2.4 alias:
# See patchbomb.py
try: # Py2.5+, Py3k
import email.mime.multipart as MIMEMultipart
import email.mime.base as MIMEBase
import email.utils as Utils
import email.encoders as Encoders
import email.generator as Generator
except ImportError: # Py2.4
import email.MIMEMultipart as MIMEMultipart
import email.MIMEBase as MIMEBase
import email.Utils as Utils
import email.Encoders as Encoders
import email.Generator as Generator
This alternative goes against coding style (Uppercase, CamelCase), but
is the least intrusive to the actual codebase.
Option 2: Similar as before, using a lowercase convention and the
'email' prefix to reduce at some degree name colissions:
try: # Py2.5+, Py3k
import email.mime.multipart as emailmimemultipart
import email.utils as emailutils # Don't confuse with mercurial.util
except ImportError: # Py2.4
import email.MIMEMultipart as emailmimemultipart
import email.Utils as emailutils
This alternative follows the coding style but breaks the standars
email package usage:
print emailmimemultipart.MIMEMultipart().items()
Option 3: Create a wrapper class and use the __getattr__ trick to
follow a Py2.5+ naming convention:
class emailwrap(object):
def __getattr__(self, name):
# ...
from emailwrap.mime.multipart import MIMEMultipart
import emailwrap.utils
Option 4: Some other alternative that I'm currently unaware of.
Cheers,
--
Alejandro Santos,
alejolp at alejolp.com.ar
http://www.alejolp.com.ar
More information about the Mercurial-devel
mailing list