[New-bugs-announce] [issue14078] Add 'sourceline' property to xml.etree Elements

Leon Matthews report at bugs.python.org
Tue Feb 21 23:25:34 CET 2012

New submission from Leon Matthews <leon at lost.co.nz>:

The lxml implementation of the ElementTree API puts a `sourceline` property onto every Element object, which I recently found useful when producing diagnostic messages.  I think it would be a useful improvement to make the standard library's ElementTree implementation.

The attached patch works by copying the current line number from the Expat parser into the Element object after the Element object is created (so as to minimise its intrusiveness for now).

The patch is just a proof of concept, and although all tests pass, the patch currently smells a little hacky and fragile to me.  Hopefully though, it will start a discussion with somebody more experienced.

PS. So as not to create a hard dependency on lxml.etree, in my project I worked around the issue as follows.  While this works in my case, the standard library seems a more logical place for this change::

    class XMLParserWithLines(XMLParser):
        Add a `sourceline` attribute to element, like lxml.etree
        def _start_list(self, *args, **kwargs):
            element = super(self.__class__, self)._start_list(*args, **kwargs)
        element.sourceline = self._parser.CurrentLineNumber
        return element

    >>> tree = ElementTree()
    >>> tree.parse(path, parser=XMLParserWithLines())
    >>> ...

components: Library (Lib)
files: elementtree-sourceline.diff
keywords: patch
messages: 153907
nosy: leonov
priority: normal
severity: normal
status: open
title: Add 'sourceline' property to xml.etree Elements
versions: Python 3.3
Added file: http://bugs.python.org/file24594/elementtree-sourceline.diff

Python tracker <report at bugs.python.org>

More information about the New-bugs-announce mailing list