Best way to import version-specific python modules

∥☆過路亽.° 提交于 2019-12-03 02:16:57

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

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!