Importing Version Specific Modules

skip at pobox.com skip at pobox.com
Thu Dec 4 19:33:40 EST 2008


    Michael> if sys.version_info[:2] >= (2, 5):
    Michael>     from string import Template
    Michael> else:
    Michael>     from our.compat.string import Template

This is "look before you leap" (LBYL).

    Michael> try:
    Michael>     from string import Template
    Michael> except ImportError:
    Michael>     from our.compat.string import Template

This is "easier to ask forgiveness than permission" (EAFP).  This tends to
be more Pythonic (and thus, preferred).  You don't *really* care what the
version just, but whether or not the string module has a Template object.
Besides, what if some bright admin at some customer decides to backport the
Template implementation to their 2.4 installation?  The first form would
load your compatibility version, probably not what they were hoping when
they put in the effort to backport.

This might be more obvious if the example was ctypes, a module which is
available recently as part of Python proper, but can also be built for older
versions of Python (for some vague definition of "older").  Some of your
customers might have installed the external version to work with their
Python installation.  Your simple version test would miss that.

-- 
Skip Montanaro - skip at pobox.com - http://smontanaro.dyndns.org/



More information about the Python-list mailing list