Skip to content

Instantly share code, notes, and snippets.

@ekarulf
Created November 10, 2010 09:39
Show Gist options
  • Save ekarulf/670611 to your computer and use it in GitHub Desktop.
Save ekarulf/670611 to your computer and use it in GitHub Desktop.
Import ElementTree with preference to faster libraries
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