Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 2 additions & 6 deletions Lib/test/test_xml_etree.py
Original file line number Diff line number Diff line change
Expand Up @@ -3760,17 +3760,13 @@ def test_write_to_text_file(self):
tree.write(f, encoding='unicode')
self.assertFalse(f.closed)
with open(TESTFN, 'rb') as f:
self.assertEqual(f.read(), convlinesep(
b'''<?xml version='1.0' encoding='ascii'?>\n'''
b'''<site>&#248;</site>'''))
self.assertEqual(f.read(), b'''<site>&#248;</site>''')

with open(TESTFN, 'w', encoding='ISO-8859-1') as f:
tree.write(f, encoding='unicode')
self.assertFalse(f.closed)
with open(TESTFN, 'rb') as f:
self.assertEqual(f.read(), convlinesep(
b'''<?xml version='1.0' encoding='ISO-8859-1'?>\n'''
b'''<site>\xf8</site>'''))
self.assertEqual(f.read(), b'''<site>\xf8</site>''')

def test_write_to_binary_file(self):
self.addCleanup(os_helper.unlink, TESTFN)
Expand Down
2 changes: 2 additions & 0 deletions Lib/xml/etree/ElementTree.py
Original file line number Diff line number Diff line change
Expand Up @@ -731,6 +731,8 @@ def write(self, file_or_filename,
with _get_writer(file_or_filename, encoding) as (write, declared_encoding):
if method == "xml" and (xml_declaration or
(xml_declaration is None and
not (encoding.lower() == "unicode" and
hasattr(file_or_filename, "write")) and
declared_encoding.lower() not in ("utf-8", "us-ascii"))):
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why not just this?

xml_declaration is None and encoding.lower() not in ("utf-8", "us-ascii", "unicode")

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Because it will write an invalid XML file when pass a file name on non-UTF-8 locale. Run test_write_to_filename_as_unicode on non-UTF-8 locale.

When the default encoding in open() be UTF-8, and only UTF-8, and nothing except UTF-8, this code could be simplified.

It can even be done earlier if open the file in UTF-8 instead of the default encoding with encoding='unicode'. But such change is not for backporting. I'll create a separate PR for the main branch only.

write("<?xml version='1.0' encoding='%s'?>\n" % (
declared_encoding,))
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Suppress writing an XML declaration in open files in ``ElementTree.write()``
with ``encoding='unicode'`` and ``xml_declaration=None``.