Best way to import version-specific python modules

前端 未结 2 1932
难免孤独
难免孤独 2021-02-05 16:19

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 enviro

2条回答
  •  攒了一身酷
    2021-02-05 16:37

    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
    

提交回复
热议问题