3

cElementTree is the fast, C implementation of the XML API ElementTree. In python 2 you would load it explicitly (aliasing it to ElementTree), but in the Python 3 docs I read this:

Changed in version 3.3: This module will use a fast implementation whenever available. The xml.etree.cElementTree module is deprecated.

Indeed, xml.etree.cElementTree.py now simply imports from xml.etree.ElementTree. The question: How do I get access to the "fast implementation"? How do I tell if it's "available", and where do I get it from if for some reason it's not distributed with python?

Introspection on ElementTree in my program suggests that I'm getting the python version. In ElementTree.py, I didn't spot any hooks to the C version. When and how does it come into play? The ElementTree documentation offered no clues, and neither did a quick search on google and stackoverflow.

alexis
  • 48,685
  • 16
  • 101
  • 161

1 Answers1

4

From the "What's New in Python 3.3" docs:

The xml.etree.ElementTree module now imports its C accelerator by default; there is no longer a need to explicitly import xml.etree.cElementTree (this module stays for backwards compatibility, but is now deprecated). In addition, the iter family of methods of Element has been optimized (rewritten in C). The module’s documentation has also been greatly improved with added examples and a more detailed reference.

While it may look as though it isn't happening the import takes place silently. You will find a section of code in ElelementTree.py that reads

# Import the C accelerators
try:
    # Element, SubElement, ParseError, TreeBuilder, XMLParser
    from _elementtree import *
except ImportError:
    pass
else:
    # Overwrite 'ElementTree.parse' and 'iterparse' to use the C XMLParser

    class ElementTree(ElementTree):
       ...

There doesn't seem to be an easy way to verify that the C module is being imported, but I think you can take it that it is. If you are really worried (and I personally wouldn't be) then you can patch a print in there to check.

holdenweb
  • 33,305
  • 7
  • 57
  • 77
  • Yes, that's also what the `ElementTree` documentation I quoted says... except for the "whenever available" part. Since it looks like it's not happening, how do I check? – alexis May 31 '15 at 14:51