Best way to import version-specific python modules
Asked Answered
J

2

15

Which method makes the most sense for importing a module in python that is version specific? My use case is that I'm writing code that will be deployed into a python 2.3 environment and in a few months be upgraded to python 2.5. This:

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

or this

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

I know that either case is equally correct and works correctly but which one is preferable?

Jackdaw answered 4/12, 2008 at 23:28 Comment(0)
A
29

Always the second way - you never know what different Python installations will have installed. Template is a specific case where it matters less, but when you test for the capability instead of the versioning you're always more robust.

That's how I make Testoob support Python 2.2 - 2.6: I try to import a module in different ways until it works. It's also relevant to 3rd-party libraries.

Here's an extreme case - supporting different options for ElementTree to appear:

try: import elementtree.ElementTree as ET
except ImportError:
    try: import cElementTree as ET
    except ImportError:
        try: import lxml.etree as ET
        except ImportError:
            import xml.etree.ElementTree as ET # Python 2.5 and up
Applicative answered 4/12, 2008 at 23:57 Comment(1)
You've missed from xml.etree import cElementTree as ET for Python 2.5 and upInterdependent
T
2

I would probably argue that the second one would be preferable. Sometimes, you can install a module from a newer version of python into an older one. For example, wsgiref comes with Python 2.5, but it isn't entirely uncommon for it to be installed into older versions (I think it will work with python 2.3 up).

Ternate answered 4/12, 2008 at 23:40 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.