Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to import version-specific python modules

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?

like image 214
mcrute Avatar asked Dec 04 '08 23:12

mcrute


People also ask

How do I import a specific version of a package in Python?

How do I Install a Specific Version of a Python Package? To install a specific version of a Python package you can use pip: pip install YourPackage==YourVersion . For example, if you want to install an older version of Pandas you can do as follows: pip install pandas==1.1.

Which is the correct way to import modules?

To use the module, you have to import it using the import keyword. The function or variables present inside the file can be used in another file by importing the module.

What are the two ways to import module in Python?

So there's four different ways to import: Import the whole module using its original name: pycon import random. Import specific things from the module: pycon from random import choice, randint. Import the whole module and rename it, usually using a shorter variable name: pycon import pandas as pd.


2 Answers

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
like image 195
orip Avatar answered Sep 20 '22 17:09

orip


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).

like image 33
Jason Baker Avatar answered Sep 17 '22 17:09

Jason Baker