Search code examples
pythonsax

TypeError: setDocumentLocator() missing 1 required positional argument: 'locator'


I get an error running the following code:

#!/usr/bin/env python

from xml import sax
import sys


class MySaxHandler(sax.ContentHandler, object):

    def startElement(self, name, attrs):
        print(name, attrs)

if __name__ == '__main__':
    sax.parse(sys.stdin, MySaxHandler)

Here is the traceback:

Traceback (most recent call last):
  File "/tmp/a.py", line 13, in <module>
    sax.parse(sys.stdin, MySaxHandler)
  File "/usr/lib/python3.6/xml/sax/__init__.py", line 33, in parse
    parser.parse(source)
  File "/usr/lib/python3.6/xml/sax/expatreader.py", line 110, in parse
    self._cont_handler.setDocumentLocator(ExpatLocator(self))
TypeError: setDocumentLocator() missing 1 required positional argument: 'locator'

Why is that?


Solution

  • It's subtle, but you need to pass an instance to the handler, not the class. See this line:

    sax.parse(sys.stdin, MySaxHandler)
    

    It should be instead:

    sax.parse(sys.stdin, MySaxHandler())