5

I like to use full namespaces in python when it comes to modules/libraries for readability. I'm wondering why this doesn't work the the xml library. I figure import xml will also import etree and everything else in the namespace. At least that's behavior I've noticed for other modules.

$ ptpython
>>> import xml

>>> dir(xml.etree.ElementTree)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'etree'
'module' object has no attribute 'etree'

>>> import xml.etree.ElementTree

>>> dir(xml.etree.ElementTree)
['Comment', 'Element', 'ElementPath', 'ElementTree', 'HTML_EMPTY', 'PI',...]

Two questions:

  1. Why is this happening with the xml library?
  2. Is there a way to import it all with something short like import xml?
jonschipp
  • 781
  • 2
  • 9
  • 21

3 Answers3

7

I figure import xml will also import etree and everything else in the namespace. At least that's behavior I've noticed for other modules.

Importing a package doesn't automatically import submodules in that package. It's true that some packages do this for you as a convenience, but it's not default behavior. In this case, you need to do what you already figured out: import xml.etree.ElementTree.

BrenBarn
  • 242,874
  • 37
  • 412
  • 384
2

this is a compatibility issue with previous versions of defusedxml with python3.6 ... if you are still running into the error now, upgrade defusedxml to version 0.6.0. Worked for me.

karuoro
  • 541
  • 4
  • 12
1

Try using from xml.etree import ElementTree this works for me.