I keep stumbling over the same thing in different contexts: namespacing and how to address particular objects. It’s very context sensitive, and I’m not quite grokking it yet, especially on the ‘pythonic’ way to do it. The documentation is not very clear on a first reading of how to deal with it.

Here’s an example of simple module I just started:

import xml.parsers.expat from xml.dom.minidom import parse, parseStringimport string

class RFRData:   DATA = None

   @classmethod   def get(cls):       
                    if not DATA:           
                      cls.init()

   @classmethod   def init(cls, conf=None):       
                    cls.load_data(conf)       
                    cls.validate_data()

   @classmethod   def load_data(cls, conf=None):       
                    try:           
                      if conf:               
                        if conf.find('

It took me about 15 minutes to find:

  • What module the ExpatError class lived in
  • How to import the module correctly

If I don’t trap the error, and the xml is invalid, I get this message:

ExpatError: mismatched tag: line 21, column 6

Fine, but how to trap it? My expectation, based on that message, would be that I could have this line:

except ExpatError, err:

But no, python reports:

NameError: global name 'ExpatError' is not defined

That won’t work because I only imported a couple methods from the xml.dom.minidom package. So I try…

import xml.dom.minidom[...]except xml.dom.minidom.ExpatError, err:

And no, that doesn’t work, either:

AttributeError: 'module' object has no attribute 'ExpatError'

Which, of course, is correct, because it’s just a dom module, not a parser module. I just tried those two reflexively, based on my expectations.

So, where does ExpatError live? In the xml.parsers.expat module, where one would expect it to live. And I have to import it to trap errors from xml.dom.minidom.parse().

My beef is that:

  • The documentation for xml.dom and xml.dom.minidom don’t mention the need to use xml.parsers.expat directly, nor is it shown in the examples.
  • Python error handling returns an exception object from legitimate code that I can’t reference unless I import an additional package, and it is not clear at all which package I should be importing. It took me a few minutes of looking at the docs to find it this time, but in a difference situation, this type of problem could have stumped me for a while.