[docs] Documentation but in xml.etree.ElementTree.write

Bob Felice bob.felice at gmail.com
Fri Jan 15 15:28:20 EST 2016

I was recently tripped up by a bug in the documentation for
the xml.etree.ElementTree write function that I found here:

The documentation says

>  *xml_declaration* controls if an XML declaration should be added to the
> file. Use False for never, True for always, None for only if not US-ASCII
> or UTF-8 (default is None).

However, setting *xml_declaration *to True does nothing unless the *encoding
*parameter is also set.

Here is the relevant code, from Python27\Lib\xml\etree\ElementTree.py:
def write(self, file_or_filename,
              # keyword arguments
        # assert self._root is not None
        if not method:
            method = "xml"
        elif method not in _serialize:
            # FIXME: raise an ImportError for c14n if ElementC14N is
            raise ValueError("unknown method %r" % method)
        if hasattr(file_or_filename, "write"):
            file = file_or_filename
            file = open(file_or_filename, "wb")
        write = file.write
        *if not encoding:*
            if method == "c14n":
                encoding = "utf-8"
                encoding = "us-ascii"
        *elif xml_declaration* or (*xml_declaration *is None and
                                 encoding not in ("utf-8", "us-ascii")):
            if method == "xml":
                write("<?xml version='1.0' encoding='%s'?>\n" % encoding)

The problem is, write does not even look at the value of the *xml_declaration
*unless the *encoding *parameter was specified. Even then, it won't write
the xml version string unless *method *is set to xml.

So, to be accurate, the documentation should say something like,

 write adds an xml declaration when *encoding *is specified and *method *equals
xml and either
*1) xml_declaration* is True, or
2) *xml_declaration *is None and *encoding *is neither utf-8 or us-ascii

Frankly, this code is overly complicated for what it is trying to do. I am
glad to see it was re-written for Python 3.


-- bob felice
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/docs/attachments/20160115/90463081/attachment-0001.html>

More information about the docs mailing list