Created
November 10, 2010 09:39
-
-
Save ekarulf/670611 to your computer and use it in GitHub Desktop.
Import ElementTree with preference to faster libraries
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def etree(packages=('lxml.etree', 'xml.etree.cElementTree', | |
'cElementTree', 'elementtree.ElementTree')): | |
for pkg_name in packages: | |
try: | |
pkg = __import__(pkg_name) | |
except ImportError: | |
continue | |
else: | |
for subpkg_name in pkg_name.split('.')[1:]: # skip the base package | |
pkg = getattr(pkg, subpkg_name) | |
return pkg | |
raise ImportError('ElementTree library could not be found') | |
# If this makes you queasy, rename the function above to _import_etree | |
etree = etree() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment